【发布时间】:2017-12-28 13:30:06
【问题描述】:
library(ggplot2)
library(gridExtra)
df1 <- data.frame(x=c("A1","A2","A3","A4"),something=c(10,18,24,32),col=rep(c("A","B"),2))
df2 <- data.frame(x=c("C1","C2","C3","C4"),somethingelse=c(10543,182334,242334,32255),col=rep(c("A","B"),2))
p1 <- ggplot(df1,aes(x,something,fill=col))+
ggtitle("Plot")+
geom_bar(stat="identity")+
theme(legend.position="top",
legend.justification="right",
legend.direction="horizontal")
p2 <- ggplot(df2,aes(x,somethingelse,fill=col))+
ggtitle("Plot")+
geom_bar(stat="identity")+
theme(legend.position="top",
legend.justification="right",
legend.direction="horizontal")
我有这两个图,我想将它们与相等的宽度、共同的标题和图例组合在一起。我认为与其拉出标题和传说 grobs,不如将其留在顶部情节并将其隐藏在第二个情节中。这样,我就不必在grid.arrange() 中手动设置高度了。
#using loops to generalise to n plots
plist <- list()
plist[[1]] <- p1
plist[[2]] <- p2
grobs <- list()
for (i in 1:length(plist)){
if(i!=1) plist[[i]] <- plist[[i]]+theme(legend.position="none",plot.title=element_blank())
grobs[[i]] <- ggplotGrob(plist[[i]])
widths[[i]] <- grobs[[i]]$widths[2:5]
}
# fix widths
maxwidth <- do.call(grid::unit.pmax, widths)
for (i in 1:length(grobs)){
grobs[[i]]$widths[2:5] <- as.list(maxwidth)
}
#plot
pgrob = do.call("arrangeGrob",grobs)
grid.arrange(pgrob)
但是,这里的地块高度是非常不同的。所以我手动将所有地块的高度设置为第一个。
for (i in 1:length(grobs)){
grobs[[i]]$heights[2:5] <- grobs[[1]]$heights[2:5]
}
#plot
pgrob = do.call("arrangeGrob",grobs)
grid.arrange(pgrob)
现在,我在第二个情节上方得到了这个巨大的空白区域。我该如何摆脱它?
【问题讨论】:
-
我真的建议坚持使用
ggpubr。非常适合自定义出版质量图(对齐图、图例等)