首页 文章

R堆积百分比条形图,包含二元因子和标签的百分比(使用ggplot)

提问于
浏览
20

我想生成一个看起来像这样的图形:

enter image description here

我的原始数据集看起来像这样:

> bb[sample(nrow(bb), 20), ]
      IMG QUANT FIX
25663   1     1   0
7936    2     2   0
23586   3     2   0
23017   2     2   1
31363   1     3   1
7886    2     2   0
23819   3     3   1
29838   2     2   1
8169    2     3   1
9870    2     3   0
31440   2     1   0
35564   3     1   0
24066   1     2   0
12020   3     2   0
6742    3     2   0
6189    2     3   0
26692   2     3   0
1387    3     2   0
31839   2     3   1
28637   3     2   0

所以这个想法是条形显示 FIX = 1 每个因子 QUANT 和每个因子 IMG .

我使用 plyr 将我的数据集聚合为百分比

library(plyr)
bb.perc <- ddply(bb,.(QUANT,IMG),summarise,FIX.PROP = sum(FIX) / length(FIX))

它几乎是正确的事情:

QUANT IMG   FIX.PROP
1     1   1 0.52439024
2     1   2 0.19085366
3     1   3 0.13658537
4     2   1 0.20414201
5     2   2 0.53964497
6     2   3 0.09585799
7     3   1 0.29000000
8     3   2 0.13000000
9     3   3 0.40705882

但是现在如果我制作一个图表,它不会考虑 FIX==0 情况,即所有条形都有相同的高度,即100%,这不是100%:

> sum(bb.perc[1:3,]$FIX.PROP)
[1] 0.8518293
> sum(bb.perc[4:6,]$FIX.PROP)
[1] 0.839645
> sum(bb.perc[7:9,]$FIX.PROP)
[1] 0.8270588

我能用R做的最好的就是显示计数:

# Take only the positive samples
bb.pos <- bb[bb$FIX == 1,]
# Plot the counts
ggplot(bb,aes(factor(QUANT),fill=factor(IMG))) + geom_bar() +
  scale_y_continuous(labels=percent)

结果:
enter image description here
这也不是我想要的:

  • 百分比尺度偏离 . 我需要一种方法将100%的点传递给 percent 函数,但我不知道如何 .

  • 它没有标签 .

关于SO已经有很多类似的问题了,但我似乎缺乏足够的智力(或对R的理解)来从他们推断出我的特定问题的解决方案 .

感谢您的任何指示!

编辑:Sven Hohenstein已经提供了一个答案,但这也是我自己也是这样做的结果:

> ggplot(bb.perc,aes(x=factor(QUANT),y=FIX.PROP,label=paste(round(FIX.PROP*100),
     "%"),fill=factor(IMG)))+ geom_bar(stat="identity") + geom_text(position="stack",
     aes(ymax=1),vjust=5) + scale_y_continuous(labels = percent)

使用 bb.perc ,我使用 plyr 进一步定义 . 这个优点是百分比是按列本地计算的,而不是全局计算的 .

谢谢大家的帮助 . 以下两个问题及其各自的答案帮助我做了大量工作:

Stacked Bar Graph Labels with ggplot2

Adding labels to ggplot bar chart

我最初做错了,是将 position = "fill" 参数传递给 geom_bar() ,由于某种原因使得所有的栏都有相同的高度!

1 回答

  • 22

    这是一种生成图的方法:

    ggplot(bb[bb$FIX == 1, ],aes(x = factor(QUANT), fill = factor(IMG), 
                                 y = (..count..)/sum(..count..))) +
     geom_bar() +
     stat_bin(geom = "text",
              aes(label = paste(round((..count..)/sum(..count..)*100), "%")),
              vjust = 5) +
     scale_y_continuous(labels = percent)
    

    更改 vjust 参数的值以调整标签的垂直位置 .

    enter image description here

相关问题