【问题标题】:How do I create a stacked histogram w/ ggplot2?如何使用 ggplot2 创建堆叠直方图?
【发布时间】:2013-12-20 17:03:45
【问题描述】:

我想创建一个堆叠直方图,底部显示canceled == TRUE,顶部显示canceled == FALSE。不过,我似乎无法弄清楚。有什么想法可以用 ggplot2 做到这一点,同时保持侧面环绕源吗?

这是我目前拥有的:

ggplot(data, aes(x=days, fill="canceled")) +
    geom_histogram(binwidth=1, position="stack") +
    facet_wrap(~source, ncol=2, scale="free_y") +
    coord_cartesian(xlim=c(0, 21))

我的数据:

days,source,canceled
1,ABC,TRUE
1,ABC,FALSE
1,ABC,TRUE
2,ABC,FALSE
2,XYZ,FALSE

【问题讨论】:

    标签: r histogram ggplot2


    【解决方案1】:

    好吧,您至少应该首先从 ggplot 命令中的“取消”一词周围删除引号。这会导致 TRUE 和 FALSE 值的颜色不同并相互堆叠,这比您之前的要好,但是,它仍然将 TRUE 堆叠在顶部,FALSE 堆叠在底部,与您要求的相反。我不确定如何控制堆叠顺序(毕竟,您可能首先使用 ggplot2 来委派许多详细的低级显示决策),但这至少解决了一半的问题.我对您的代码稍作修改的版本和显示的结果附在下面。

    library(ggplot2)
    
    days <- c(1, 1, 1, 2, 2)
    source <- c("ABC", "ABC", "ABC", "ABC", "XYZ")
    canceled <- c(TRUE, FALSE, TRUE, FALSE, FALSE)
    
    data <- data.frame(days, source, canceled)
    
    print(ggplot(data, aes(x=days, fill=canceled)) + 
                 geom_histogram(binwidth=1, position="stack") +
                 facet_wrap(~source, ncol=2, scale="free_y") +
                 coord_cartesian(xlim=c(0, 21)))
    

    【讨论】:

      【解决方案2】:

      由于您需要通过变量canceled 获取不同的填充值,因此应该使用不带引号的变量。要以相反的顺序堆叠,您可以使用参数order= 并将canceled 设置为负数。

      ggplot(data, aes(x=days, fill=canceled,order=-canceled)) +
        geom_bar(binwidth=1, position="stack") +
        facet_wrap(~source, ncol=2, scale="free_y") +
        coord_cartesian(xlim=c(0, 21))
      

      【讨论】:

        【解决方案3】:

        对于通过谷歌到达这里的其他人,寻找一个非常简单的例子来说明如何使用ggplot2 来制作堆叠直方图:

        ggplot(diamonds, aes(price, fill = cut)) +
          geom_histogram(binwidth = 500)
        

        更多信息here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-05-03
          • 2020-08-11
          • 2012-02-04
          • 2016-08-11
          • 1970-01-01
          • 2012-05-10
          • 2012-10-10
          • 2019-08-27
          相关资源
          最近更新 更多