Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align barplots using grid.arrange?

Tags:

r

ggplot2

I need many bar plots to display horizontally. I've tried many ways and found grid.arrange to be hopeful except for the x-axis label issues.

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

Please run the code and I appreciate it really.

Is there anyway to fix the height of the bar plots so the x-axis labels starts from the same height? Thank you very much.

like image 938
John Avatar asked Mar 16 '23 03:03

John


1 Answers

You can do

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)

or, more compactly,

grid::grid.draw(gridExtra:::cbind_gtable(ggplotGrob(p1),ggplotGrob(p2)))
like image 86
baptiste Avatar answered Mar 25 '23 12:03

baptiste