Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axis labels for each bar and each group in bar charts with dodged groups

Tags:

r

ggplot2

I would like to create a bar chart using ggplot2 with dodged groups and axis labels for both the bars (male, female) and the groups (Study 1, Study 2...). Here is how I would like my chart to look:

enter image description here

And some R code. In this case, only the groups are labeled on the axis (not the bars within the group). The bar labels in the axis basically replace the legend.

x      = runif(8)
gender = factor(c("male","female","male","female","male","female","male","female"))
group  = c(0,0,1,1,2,2,3,3)
df     = data.frame(x,gender,group)

ggplot(df,aes(x=group,y=x,fill=gender)) + 
    geom_bar(stat="identity",position="dodge") + 
    scale_x_continuous("",breaks=c(0:3),
        labels=c('G1','G2','G3','G4'))

enter image description here

like image 695
user2503795 Avatar asked Apr 29 '13 13:04

user2503795


1 Answers

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)

enter image description here

like image 95
Didzis Elferts Avatar answered Nov 15 '22 00:11

Didzis Elferts