提问者:小点点

ggplot2 stats=“identity”和条形图中的堆叠颜色提供“条纹”条形图


在回答前一个问题之后,我提出了另一个问题:

如何在不重新塑造数据的情况下,根据另一个类别绘制不同颜色的堆叠条形图,同时使用stats=“标识”来总结每个堆叠区域的值?

统计标识可以很好地总结值,但对于非堆叠列。在堆叠列中,堆叠以某种方式被“乘以”或“条纹”,见下图。

一些数据样本:

element <- rep("apples", 15)
qty <- c(2, 1, 4, 3, 6, 2, 1, 4, 3, 6, 2, 1, 4, 3, 6)
category1 <- c("Red", "Green", "Red", "Green", "Yellow")
category2 <- c("small","big","big","small","small")
d <- data.frame(element=element, qty=qty, category1=category1, category2=category2)

该表给出了:

id  element  qty category1 category2
1   apples   2       Red     small
2   apples   1     Green       big
3   apples   4       Red       big
4   apples   3     Green     small
5   apples   6    Yellow     small
6   apples   2       Red     small
7   apples   1     Green       big
8   apples   4       Red       big
9   apples   3     Green     small
10  apples   6    Yellow     small
11  apples   2       Red     small
12  apples   1     Green       big
13  apples   4       Red       big
14  apples   3     Green     small
15  apples   6    Yellow     small

然后:
ggplot(d,aes(x=分类1,y=qty,填充=分类2))geom_bar(stat=标识)

但是图表有点混乱:颜色没有组合在一起!

是否仍有一个选项可以在不重塑数据的情况下正确分组颜色?


共2个答案

匿名用户

一种方法是按类别2对数据进行排序。这也可以在ggplot()调用中完成。

ggplot(d[order(d$category2),], aes(x=category1, y=qty, fill=category2)) + 
             geom_bar(stat="identity")

匿名用户

我使用了一段时间这个解决方案,但碰巧在我的大型数据库(60 000个条目)上,有序堆叠的条形图ggplot2正在绘制,这取决于缩放级别,条形图之间有一些空白。不知道这个问题来自哪里——但一个疯狂的猜测是我堆积了太多的酒吧: p。

使用plyr聚合数据解决了问题:

element <- rep("apples", 15)
qty <- c(2, 1, 4, 3, 6, 2, 1, 4, 3, 6, 2, 1, 4, 3, 6, )
category1 <- c("Red", "Green", "Red", "Green", "Yellow")
category2 <- c("small","big","big","small","small")
d <- data.frame(element=element, qty=qty, category1=category1, category2=category2)

plyr:

d <- ddply(d, .(category1, category2), summarize, qty=sum(qty, na.rm = TRUE))

简单解释一下这个公式的内容:

ddply(1, .(2, 3), summarize, 4=function(6, na.rm = TRUE))

1:数据帧名称2,3:要保留的列-

4,5,6可以重复更多的计算字段...

ggplot2:ggplot(d,aes(x=类别1,y=数量,fill=类别2))几何图形栏(stat=“identity”)

因此,现在,正如Roman Luštrik所建议的那样,数据根据要显示的图表进行聚合。

应用ddply后,数据确实更清晰:

  category1 category2 qty
1     Green       big   3
2     Green     small   9
3       Red       big  12
4       Red     small   6
5    Yellow     small  18

我终于明白了如何管理我的数据集,由于这个非常好的信息源:http://jaredknowles.com/r-bootcamphttps://dl.dropbox.com/u/1811289/RBootcamp/slides/Tutorial3_DataSort.html

还有那个:http://streaming.stat.iastate.edu/workshops/r-intro/lectures/6-advancedmanipulation.pdf

...只是因为?DDply有点...奇怪(例子不同于选项的解释)-看起来没有什么告诉速记写作...但是我可能忽略了一点...