如何使用grid_arrange_shared_legend

时间:2016-03-14 08:27:34

标签: r ggplot2

我一直在尝试使用grid_arrange_shared_legend code创建一个带有单个图例的ggplot2图表列(我不能使用直面,因为我需要使用coord_flip并且具有不同的x轴大小 - 这个已被Hadley记录为不工作 - https://github.com/hadley/ggplot2/issues/95

代码打印出4个图作为2x2矩阵,下面是图例(见http://rpubs.com/sjackman/grid_arrange_shared_legend)。

我一直试图在一个专栏中获得4个情节加上传奇,但却失败了。奇怪的是,我认为grid.arrange的ncol = 1参数会使它全部成为一列,但事实并非如此。

目前,给定4个图表和一个图例,代码给出了这种布局:

+-----------+      +-----------+
|           |      |           |
|     1     |      |    3      |
|           |      |           |
+-----------+      +-----------+

+-----------+      +-----------+
|           |      |           |
|     2     |      |    4      |
|           |      |           |
+-----------+      +-----------+


        LEGEND HERE

我想要

+-----------+    
|           |   
|     1     |   
|           |    
+-----------+ 

+-----------+ 
|           |  
|     2     |  
|           |  
+-----------+ 

+-----------+    
|           |   
|     3     |   
|           |    
+-----------+ 

+-----------+ 
|           |  
|     4     |  
|           |  
+-----------+ 

 LEGEND HERE

任何帮助表示赞赏。 问候 皮特

1 个答案:

答案 0 :(得分:4)

这个版本有一个用于图表布局的列参数(另一个ncol用于排列图表和图例组)

grid_arrange_shared_legend <- function(..., ncol=1) {
  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)
  grid.arrange(
    do.call(arrangeGrob, c(ncol=ncol, lapply(plots, function(x)
      x + theme(legend.position="none")))),
    legend,
    ncol = 1,
    heights = unit.c(unit(1, "npc") - lheight, lheight))
}

或者,考虑这个将对齐面板的策略

library(gridExtra)

get_legend <- function(p, position="bottom"){
  g <- ggplotGrob(p + theme(legend.position=position))
  gtable::gtable_filter(g, "guide-box")
} 
strip_legend <- function(pl) lapply(pl, function(x) x + theme(legend.position="none"))

legend <- get_legend(p1)
pl <- strip_legend(list(p1,p2,p3,p4))
gl <- lapply(pl, ggplotGrob)
lheight <- sum(legend$heights)
grid.arrange(do.call(rbind, gl), legend, 
             heights = unit.c(unit(1,"npc") - lheight, lheight))

enter image description here

相关问题