Shared legend 3x3 ggplots

被刻印的时光 ゝ 提交于 2019-12-25 03:39:50

问题


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:


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)))



来源:https://stackoverflow.com/questions/33306642/shared-legend-3x3-ggplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!