ggplot2:组合图时固定轴高度/宽度

时间:2017-12-28 08:45:13

标签: r ggplot2

library(ggplot2)
library(gridExtra)

df1 <- data.frame(x=c("A1","A2","A3","A4"),something=c(10,18,24,32))
df2 <- data.frame(x=c("C1","C2","C3","C4"),somethingelse=c(10543,182334,242334,32255))


p1 <- ggplot(df1,aes(x,something))+
  geom_bar(stat="identity")
p2 <- ggplot(df2,aes(x,somethingelse))+
  geom_bar(stat="identity")


png("test.png",height=8,width=6,res=120,units="cm")
gridExtra::grid.arrange(p1,p2,heights=grid::unit(c(4,4),"cm"))
dev.off()

enter image description here

当我手动组合上面的两个或多个图时,如何将y轴宽度固定为相同,以便所有图中的条形图(A1-C1,A2-C2,..)对齐?有没有办法计算最大y标签宽度并将该宽度应用于所有图的y轴?不,在这种特殊情况下,方面不是我想要的。

1 个答案:

答案 0 :(得分:2)

您可以使用ggpubr中的ggarrange与参数align = "v"

# Plotting figures provided by OP
ggpubr::ggarrange(p1, p2, heights = c(4, 4), nrow = 2, align = "v")

enter image description here