【问题标题】:How to align barplots using grid.arrange?如何使用 grid.arrange 对齐条形图?
【发布时间】:2015-08-10 07:18:35
【问题描述】:

我需要许多条形图来水平显示。我尝试了很多方法,发现 grid.arrange 除了 x 轴标签问题外,还有希望。

library(ggplot2)
library(gridExtra)

x1 = c("x","x","y","x","y","x")
x2 = c("NicholasKimseyLayerDad","GumpedJinseiLacks","NicholasKimseyLayerDad","NicholasKimseyLayerDad"
       ,"GumpedJinseiLacks","GumpedJinseiLacks")
fail = c("F","P","F","F","P","F")
D1=data.frame(x1,fail)
p1 = ggplot(D1,aes(x=x1,fill=fail)) + geom_bar() +geom_text(stat='bin',aes(label=..count..),vjust=-0.3,size=4,color="red")+ 
  theme(legend.position="none",axis.title.y=element_blank(),axis.text.x = element_text(angle = 90, hjust = 1))

p2 = ggplot(D1,aes(x=x2,fill=fail)) + geom_bar() +geom_text(stat='bin',aes(label=..count..),vjust=-0.3,size=4,color="red")+ 
  theme(legend.position="none",axis.title.y=element_blank(),axis.text.x = element_text(angle = 90, hjust = 1))

grid.arrange(p1,p2,ncol=2)

请运行代码,我真的很感激。

有没有办法固定条形图的高度,使 x 轴标签从相同的高度开始?非常感谢。

【问题讨论】:

  • 欢迎来到 SO!除了下面的答案,这里还有一个relevant link

标签: r ggplot2


【解决方案1】:

你可以的

library(gtable)
g1 = ggplotGrob(p1)
g2 = ggplotGrob(p2)
g = cbind(g1, g2, size="first")
g$heights = grid::unit.pmax(g1$heights, g2$heights)
grid::grid.newpage()
grid::grid.draw(g)

或者,更简洁的,

grid::grid.draw(gridExtra:::cbind_gtable(ggplotGrob(p1),ggplotGrob(p2)))

【讨论】:

  • 太完美了。非常感谢。
  • 顺便说一句,我在更新的 gridExtra 包中找不到函数 cbind_gtable( )。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 2019-03-22
  • 2017-04-29
  • 1970-01-01
相关资源
最近更新 更多