Inspired by @Sandy Muspratt answer on this SO question.
First, create and save as object plot that has no legend and change x axis labels to Female
or Male
with scale_x_continuous()
. Add extra space under the plot with plot.margin=
in theme()
.
library(ggplot2)
library(gridExtra)
p<-ggplot(df,aes(x=group,y=x,fill=gender)) +
geom_bar(stat="identity",position="dodge") +
scale_x_continuous("",breaks=c(-0.25,0.25,0.75,1.25,1.75,2.25,2.75,3.25),
labels=rep(c("Female","Male"),times=4))+
theme(legend.position="none")+
theme(plot.margin = unit(c(1,2,3,1), "lines"))
Now with functions annotation_custom()
and textGrob()
add labels Study 1
, Study 2
under the plot setting x and y coordinates (negative coordinates for y puts labels under the plot).
p1<-p+annotation_custom(grob=textGrob("Study 1"),
xmin=0,xmax=0,ymin=-.2,ymax=-0.2)+
annotation_custom(grob=textGrob("Study 2"),
xmin=1,xmax=1,ymin=-.2,ymax=-0.2)+
annotation_custom(grob=textGrob("Study 3"),
xmin=2,xmax=2,ymin=-.2,ymax=-0.2)+
annotation_custom(grob=textGrob("Study 4"),
xmin=3,xmax=3,ymin=-.2,ymax=-0.2)
To ensure that new labels are plotted, you should convert plot to grobs object and then disable clipping.
gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)