2017-05-30 127 views
0

我在兩個ggplot圖之間共享一點共同的傳說,我已經使用arrange.grid進行了排列。我得到的最接近的是:ggplot2在頂部的共享圖例

Plot a legend and well-spaced universal y-axis and main titles in grid.arrange但是使用這裏的想法我只能在底部或頂部獲得常見的圖例。這裏是我的嘗試:

library(ggplot2) 
p1<-ggplot(data=diamonds)+geom_bar(aes(x=cut,fill=color))+scale_x_discrete("")+ylab("")+ggtitle("Title 1") 
p2<-ggplot(data=diamonds)+geom_bar(aes(x=cut,fill=color))+scale_x_discrete("")+ylab("")+ggtitle("Title 2") 
legend = gtable_filter(ggplotGrob(p1), "guide-box") 
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"), 
         p2 + theme(legend.position="none"), 
         nrow = 1, 
         top = textGrob("Main Title", vjust = -6, gp = gpar(fontface = "bold", cex = 1.5)), 
         left = textGrob("Global Y-axis Label", rot = 90, vjust = 2.5), 
         bottom = textGrob("Global X-axis Label", vjust =-1)), 
      legend, 
      nrow=1) 

而且這個教程只展示瞭如何把無論是在底部或側面:

https://cran.r-project.org/web/packages/cowplot/vignettes/shared_legends.html

使用該解決方案可幫助而圖形看起來還是相當難看。

p1<-ggplot(data=diamonds)+geom_bar(aes(x=cut,fill=color))+scale_x_discrete("")+ylab("")+ggtitle("Title 1")+guides(fill = guide_legend(title.position = "top",nrow=1))+theme(legend.position = "top", plot.title=element_text(hjust = 0,vjust=-1)) 
p2<-ggplot(data=diamonds)+geom_bar(aes(x=cut,fill=color))+scale_x_discrete("")+ylab("")+ggtitle("Title 2") 

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]] 
    return(legend)} 

mylegend<-g_legend(p1) 

grid.arrange(mylegend,nrow=2,heights=c(0.2,1), 
      arrangeGrob(p1+ theme(legend.position="none"), 
         p2+ theme(legend.position="none"), 
         top = textGrob("Main Title", vjust =-6, gp = gpar(fontface = "bold", cex = 1.5)), 
         left = textGrob("Global Y-axis Label", rot = 90, vjust = 2.5), 
         bottom = textGrob("Global X-axis Label", vjust =-1), 
         nrow=1)) 

回答

1

您可以使用此功能

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]] 
    return(legend)} 

然後你可以做以下

plot1 <- ggplot(...) + ... 

mylegend<-g_legend(plot1) 

plot2 <- ggplot(...) + ... + theme(legend.position="none") 



    grid.arrange(arrangeGrob(plot1+ theme(legend.position="none") 
          ,plot2 
          nrow=1), 
      mylegend,nrow=2,heights=c(10,1)) 

UPDATE

要放在上面的傳說試試這個

grid.arrange(mylegend,nrow=2,heights=c(0.05,1), 
       arrangeGrob(plot1+ theme(legend.position="none") 
          ,plot2 
          ,nrow=1) 
       ) 

您可能需要進行實驗,在heights=c(0.05,1)

+0

0.05了一下這個傳說將出現在聯合策劃的底部不是頂部 – Vitalijs

+0

你嘗試在你的第一個情節把'legend.position =「頂部」? – quant

+0

是的,我嘗試過! – Vitalijs