ggplot单独的传说和情节

我正在使用网格 lpackage放置我用ggplot2制作的graphics

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)的位置上。 不幸的是,我无法真正find创build一个图例variables的方法。 我在网上search,最近我得到的是使用较旧的+ opts(keep = "legend_box")但已被弃用。

旧的解决scheme

您可以从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函数的例子。

HTH

有一个函数grid_arrange_shared_legend由ggplot2自己的开发者build议: https : //github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs ,它工作得很好。