首页 文章

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

提问于
浏览
1

在回答了我的former question后,我又提出了一个问题:

如何在不重新整形数据的情况下,根据另一个类别绘制具有不同颜色的堆积条形图,同时使用stats =“identity”来汇总每个堆积区域的值?

统计信息标识很好地总结了值,但是对于非堆叠列 . 在堆叠列中,堆叠以某种方式“倍增”或“条纹”,见下图 .

一些数据样本:

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 = category1,y = qty,fill = category2))geom_bar(stat = "identity")

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

ggplot graph is striped
为什么会出现这种行为?

是否仍然可以选择正确分组颜色而不重塑我的数据?

2 回答

  • 1

    一种方法是按 category2 订购数据 . 这也可以在 ggplot() 调用中完成 .

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

    我正在使用这个解决方案,但它发生在我的大型数据库(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)
    

    普莱尔:

    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:计算列函数的名称:要应用的函数 - 这里是总和()6:应用该功能的列

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

    ggplot2:ggplot(d,aes(x = category1,y = qty,fill = category2))geom_bar(stat =“identity”)

    现在,正如RomanLuš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-bootcamp https://dl.dropbox.com/u/1811289/RBootcamp/slides/Tutorial3_DataSort.html

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

    ......只是因为?ddply有点......奇怪(例子与选项的解释不同) - 看起来没有什么告诉写简写......但我可能错过了一点......

相关问题