2012-09-21 40 views
13

我使用電網 lpackage把我的圖表,我GGPLOT2提出:ggplot獨立的傳奇人物,情節

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"),但已被棄用。

older solution

回答

24

您可以從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

+0

謝謝。我仍然無法應對新的變化。 –