使用 R 中的 ggplot2 和 gridExtra 使图例特定于图形中的图形

Making legends specific to graphs within a figure using ggplot2 and gridExtra in R

我有以下情节:

df1 <- data.frame(col1 = rep(LETTERS[1:3], each = 4), col2 = rnorm(12), col3 = runif(12), col4 = rep(c("Fred", "Bob"), each = 6))
df1_list <- split(df1, df1$col1)
gridExtra::grid.arrange(grobs = mapply(function (x, y) {
  ggplot2::ggplot(x, ggplot2::aes(x = col2, y = col3, col = col4)) +
    ggplot2::geom_point() +
    ggplot2::ggtitle(y) +
    ggplot2::scale_color_manual('Person', values = c('Fred' = 'red', 'Bob' = 'blue'))
}, x = df1_list, y = names(df1_list), SIMPLIFY = F))

在这张图的第一张图上,所有的点都代表Fred,但是在图例中,还是出现了Bob。是否可以在图例中只包含每个图表中出现的人?

我想确保 'Fred' 总是 'red' 并且 'Bob' 总是 'blue',所以使用 scale_discrete_manual 函数的 drop = T争论是行不通的。

谢谢!

这是一个可能的解决方案,其中 scale_color_manual 中的 values 参数是动态创建的。

set.seed(1234)
df1 <- data.frame(col1 = rep(LETTERS[1:3], each = 4), col2 = rnorm(12), 
             col3 = runif(12), col4 = rep(c("Fred", "Bob"), each = 6))
df1$col4 <- factor(df1$col4)
df1_list <- split(df1, df1$col1)
cols <- setNames(c('red', 'blue'), c('Fred','Bob'))
gridExtra::grid.arrange(grobs = mapply(function (x, y) {
  x$col4 <- droplevels(x$col4)
  idx <- match(levels(x$col4), names(cols))
  ggplot2::ggplot(x, ggplot2::aes(x = col2, y = col3, col = col4)) +
    ggplot2::geom_point() +
    ggplot2::ggtitle(y) +
    ggplot2::scale_color_manual('Person', values = cols[idx])
}, x = df1_list, y = names(df1_list), SIMPLIFY = F))

能否分享您的 sessionInfo() 以便我们查看您 运行 的软件包版本?我 运行 你的代码,这就是我得到的。