如何包含条带彩色组的图例

我使用了建议
here的解决方案,根据随数据框提供的变量为使用facet_wrap创建的小平面着色.

我需要添加条形颜色(大小)的图例,它在虚拟中绘制.

知道如何从g2 $布局或任何其他方式获取它?

library(gtable)
library(grid)

d <- data.frame(fruit = rep(c("apple", "orange", "plum", "banana", "pear", "grape")), 
            farm = rep(c(0,1,3,6,9,12), each=6), 
            weight = rnorm(36, 10000, 2500), 
            size=rep(c("small", "large")))

p1 = ggplot(data = d, aes(x = farm, y = weight)) + 
  geom_jitter(position = position_jitter(width = 0.3), 
          aes(color = factor(farm)), size = 2.5, alpha = 1) + 
  facet_wrap(~fruit)

dummy <- ggplot(data = d, aes(x = farm, y = weight))+ facet_wrap(~fruit) + 
  geom_rect(aes(fill=size), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
  theme_minimal()

g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(dummy)

gtable_select <- function (x, ...) 
{
  matches <- c(...)
  x$layout <- x$layout[matches, , drop = FALSE]
  x$grobs <- x$grobs[matches]
  x
}

panels <- grepl(pattern="panel", g2$layout$name)
strips <- grepl(pattern="strip-t", g2$layout$name)
g2$layout$t[panels] <- g2$layout$t[panels] - 1
g2$layout$b[panels] <- g2$layout$b[panels] - 1

new_strips <- gtable_select(g2, panels | strips)
grid.newpage()
grid.draw(new_strips)

gtable_stack <- function(g1, g2){
  g1$grobs <- c(g1$grobs, g2$grobs)
  g1$layout <- transform(g1$layout, z= z-max(z), name="g2")
  g1$layout <- rbind(g1$layout, g2$layout)
  g1
}

new_plot <- gtable_stack(g1, new_strips)
grid.newpage()
grid.draw(new_plot)

最佳答案 借用
this answer中的以下函数,您可以先从虚拟图中提取图例.

# Extract only the legend from "dummy" plot
g_legend <- function(dummy){ 
  tmp <- ggplot_gtable(ggplot_build(dummy)) 
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
 legend <- tmp$grobs[[leg]] 
return(legend)} 
# Assign the legend to a separate object
facet.legend <- g_legend(dummy)

然后你可以使用gridExtra包中的grid.arrange()…

library(gridExtra)
jpeg("plot-with-facet-legend.jpg", width = 8, height = 6, units = "in", res = 300)
print(grid.arrange(new_plot, facet.legend, nrow = 2, widths = c(7, 1), heights = c(6, 0.01)))
dev.off()

…产生以下情节:

《如何包含条带彩色组的图例》

或者:一个更紧凑的解决方案,在执行相同的jpeg(…),print(grid.arrange(…))代码之前直接从g2对象抓取图例:

facet.legend <- g2$grobs[[which(sapply(g2$grobs, function(x) x$name) %in% "guide-box")]]

当然,你可以使用宽度和高度参数来产生一个更整洁的情节,并且可能存在另一种解决方案,它比我的不那么讨厌,但希望这至少大致是你所寻求的.

点赞