Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...