共享传奇3x3 ggplots

时间:2015-10-23 15:52:42

标签: r ggplot2 legend gridextra

我需要一个带有共享图例的3x3 ggplot。 Controlling the plot layout when sharing legends between several ggplot2 graphs问题和答案解决了这个1x4图(不是3x3,这是我需要的)。我试图根据自己的需要修改功能,经过多次尝试,我必须承认,洗礼功能远远超出了我的R知识。

这是一个MWE,基于提到的问题中的相同示例(希望可以借用它)。

library(ggplot2)
library(grid)
library(gridExtra)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(cut, price, data=dsamp, colour=clarity)
p3 <- qplot(color, price, data=dsamp, colour=clarity)
p4 <- qplot(depth, price, data=dsamp, colour=clarity)
p5 <- qplot(carat, price, data=dsamp, colour=clarity)
p6 <- qplot(cut, price, data=dsamp, colour=clarity)
p7 <- qplot(color, price, data=dsamp, colour=clarity)
p8 <- qplot(depth, price, data=dsamp, colour=clarity)
p9 <- qplot(carat, price, data=dsamp, colour=clarity)

grid_arrange_shared_legend <- function(..., layout = rbind(c(1,2,3,4), 
                                                           c(5,5,5,5))) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lheight <- sum(legend$height)
  gl <- lapply(plots, function(x) x + theme(legend.position="none"))
  grid.arrange(grobs = c(gl, list(legend)), layout_matrix = layout,
               heights = grid::unit.c(unit(1, "npc") - lheight, lheight))
}

grid_arrange_shared_legend(p1, p2, p3, p4)  # This works
grid_arrange_shared_legend(p1, p2, p3, p4, p5, p6, p7, p8, p9)  # This is what I need

这是我需要工作的示例中的最后一行。

1 个答案:

答案 0 :(得分:3)

看起来提供的示例代码仅适用于单行图。你可以把它改成更适合:

grid_arrange_shared_legend <- function(..., layout = rbind(c(1,2,3,4), 
                                                           c(5,5,5,5))) {
  plots <- list(...)
  g <- ggplotGrob(plots[[1]] + theme(legend.position="bottom"))$grobs
  legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
  lheight <- sum(legend$height)
  gl <- lapply(plots, function(x) x + theme(legend.position="none"))
  grid.arrange(grobs = c(gl, list(legend)), layout_matrix = layout,
               heights = grid::unit.c(rep((unit(1, "npc") - lheight)*(1/(nrow(layout)-1)),nrow(layout)-1), lheight))
} 

grid_arrange_shared_legend(p1, p2, p3, p4, p5, p6, p7, p8, p9, layout=rbind(1:3, 4:6, 7:9, rep(10,3)))

enter image description here