Shared legend 3x3 ggplots

2019-09-10 10:52发布

I need a 3x3 ggplot with a shared legend. The Controlling the plot layout when sharing legends between several ggplot2 graphs question and answers solve this for 1x4 plot (not 3x3 which is what I need). I have tried to modify the function for my needs, after many attempts, I must admit that baptistes function is much beyond my R-knowledge.

Here is a MWE, based on the same example in the refered question (hope it is ok to borrow it).

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

It is the last line in the example I need working.

1条回答
相关推荐>>
2楼-- · 2019-09-10 11:13

Looks like the sample code provided will only work with a single row of plots. you can change it to be more accomidating:

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

查看更多
登录 后发表回答