【问题标题】:normalized bar heights in ggplotggplot中的标准化条形高度
【发布时间】:2015-03-10 16:46:08
【问题描述】:

我正在尝试将两组计数数据与 ggplot 进行比较。数据集的长度不同,我无法弄清楚如何将条形高度标准化为每个数据集中的行数。请看下面的代码示例:

示例数据集

set.seed(47)
BG.restricted.hs = round(runif(100, min = 47, max = 1660380))
FG.hs = round(runif(1000, min = 0, max = 1820786))

dat = data.frame(x = c(BG.restricted.hs, FG.hs), 
             source = c(rep("BG", length(BG.restricted.hs)),
                        rep("FG", length(FG.hs))))
dat$bin = cut(dat$x, breaks = 200)

第一次尝试:没有标准化。由于数据集的大小,条形高度有很大的不同!

ggplot(dat, aes(x = bin, fill = source)) +
    geom_bar(position = "identity", alpha = 0.2) +
    theme_bw() +
    scale_x_discrete(breaks = NULL)

第二次尝试:尝试使用 ..count.. 属性进行标准化

ggplot(dat,aes(x = bin, fill = source))+
    geom_bar(aes(y = ..count../sum(..count..)), alpha=0.5, position='identity')

这产生了视觉上相同的结果,仅缩放了整个 y 轴。 ..count.. 似乎没有查看“源”列中的标签,尽管经过数小时的试验,我似乎无法找到一种方法来做到这一点。这可能吗?

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    stat_bin 也返回density: density of points in bin, scaled to integrate to 1 所以

    ggplot(dat,aes(x = bin, fill = source)) + 
        stat_bin(aes(group=source, y=..density..))
    

    【讨论】:

      【解决方案2】:

      我相信应该这样做。将source 设置为ggplot 调用中的组:

      ggplot(dat, aes(x = bin, y = ..density.., group = source, fill = source)) +
          geom_bar(alpha = 0.5, position = 'identity')
      

      【讨论】:

      • 这非常有效!我想我必须遗漏一些简单的东西......非常感谢!
      猜你喜欢
      • 2012-02-05
      • 2017-07-20
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 2017-02-26
      • 1970-01-01
      相关资源
      最近更新 更多