gpt4 book ai didi

r - 如何使用 grid.arrange 对齐条形图?

转载 作者:行者123 更新时间:2023-12-04 23:44:25 24 4
gpt4 key购买 nike

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

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)

enter image description here

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

无论如何要固定条形图的高度,以便 x 轴标签从相同的高度开始?非常感谢。

最佳答案

你可以做

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)))

关于r - 如何使用 grid.arrange 对齐条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31913686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com