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))
的
0.05
了一下这个传说将出现在联合策划的底部不是顶部 – Vitalijs你尝试在你的第一个情节把'legend.position =“顶部”? – quant
是的,我尝试过! – Vitalijs