每个条形图的轴标签以及带闪避组的条形图中的每个组 [英] Axis labels for each bar and each group in bar charts with dodged groups

查看:129
本文介绍了每个条形图的轴标签以及带闪避组的条形图中的每个组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 ggplot2 创建一个条形图,并为两个酒吧(男性,女性)和组(条目1,研究2 ...)。这里是我希望我的图表看起来如何:

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:

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

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

推荐答案

受@Sandy Muspratt启发这个SO问题

Inspired by @Sandy Muspratt answer on this SO question.

首先,创建并保存为没有图例的对象图,并将x轴标签更改为,其中 scale_x_continuous()。在 theme()中用 plot.margin = 在图下添加额外空间。

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



<现在使用函数 annotation_custom() textGrob()添加标签 code>,学习2 在绘图设置的x和y坐标下(y的负坐标将标签放在绘图下)。

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)

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

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)

< img src =https://i.stack.imgur.com/JOGRQ.pngalt =在这里输入图片描述>

这篇关于每个条形图的轴标签以及带闪避组的条形图中的每个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆