8

我想ggplot2为条形图(男性、女性)和组(研究 1、研究 2...)使用闪避的组和轴标签创建一个条形图。这是我希望图表的外观:

在此处输入图像描述

还有一些 R 代码。在这种情况下,只有组被标记在轴上(而不是组内的条)。轴中的条形标签基本上取代了图例。

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

在此处输入图像描述

4

1 回答 1

8

受到@Sandy Muspratt 对这个 SO question的回答的启发。

首先,创建并保存为没有图例的对象图,并将 x 轴标签更改FemaleMale. 用inscale_x_continuous()在绘图下添加额外的空间。plot.margin=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"))

现在使用函数annotation_custom()textGrob()添加标签Study 1Study 2在绘图设置 x 和 y 坐标下(y 的负坐标将标签放在绘图下)。

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)

为确保绘制新标签,您应该将绘图转换为 grobs 对象,然后禁用裁剪。

gt <- ggplot_gtable(ggplot_build(p1))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

在此处输入图像描述

于 2013-04-29T13:33:45.350 回答