ggplot 分离图例和图表

15

我正在使用grid包来放置我用ggplot2制作的图形:

library(ggplot2)
library(grid)

Layout <- grid.layout(nrow = 4, ncol = 4,
          widths = unit(1, "null"), 
          heights = unit(c(0.4, 0.8, 1.2, 1.2), c("null", "null", "null")))
grid.show.layout(Layout)

plot1 = ggplot(diamonds, aes(clarity, fill = color)) + 
            geom_bar() + 
            facet_wrap(~cut, nrow = 1)
print(plot1 + theme(legend.position = "none"), 
vp = viewport(layout.pos.row = 3, layout.pos.col = 1:4))
问题在于我想把图形放在第三行(3,1)-(3,4)的位置,并将图例放在(4,4)的位置。不幸的是,我找不到创建只有图例变量的方法。在网上搜索后,我找到了最接近的解决方案,使用旧版本的+ opts(keep = "legend_box"),但已被弃用。更早的解决方案请参考此链接
2个回答

30

您可以从ggplot的grob对象中获取图例。 然后,您可以使用grid.arrange函数对所有内容进行定位。

library(gridExtra)
g_legend<-function(a.gplot){
    tmp <- ggplot_gtable(ggplot_build(a.gplot))
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
    legend <- tmp$grobs[[leg]]
    legend
}

legend <- g_legend(plot1)

grid.arrange(legend, plot1+ theme(legend.position = 'none'), 
    ncol=2, nrow=1, widths=c(1/6,5/6))

网络上有很多使用g_legend函数的例子。

希望对你有所帮助。


谢谢你。我还没有开始使用新的更改。 - Jase_

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接