2012-09-21 8 views
13

私はggplot2で作られた私のグラフを配置するグリッド lpackageを使用しています: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行目のプロットを入れたいということです( 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

ありがとうございました。私はまだ新しい変化に慣れていない。 –

関連する問題