【问题标题】:Normalizing y-axis in histograms in R ggplot to proportion将R ggplot中直方图中的y轴标准化为比例
【发布时间】:2012-07-30 19:09:33
【问题描述】:

我有一个非常简单的问题让我把头撞在墙上。

我想缩放直方图的 y 轴以反映每个 bin 构成的比例(0 到 1),而不是像使用 y=..density 那样让条形的面积总和为 1。 . 确实,或者最高条为 1,就像 y=..ncount.. 一样。

我的输入是名称和值的列表,格式如下:

name    value
A   0.0000354
B   0.00768
C   0.00309
D   0.000123

我的一次失败尝试:

library(ggplot2)
mydataframe < read.delim(mydata)
ggplot(mydataframe, aes(x = value)) +
geom_histogram(aes(x=value,y=..density..))

这给了我一个区域为 1,但高度为 2000 和 1000 的直方图:

and y=..ncount.. 给了我一个最高柱为 1.0 的直方图,其余按比例缩放:

但我希望第一个条的高度为 0.5,其他两个为 0.25。

R 也不识别 scale_y_continuous 的这些用法。

scale_y_continuous(formatter="percent")
scale_y_continuous(labels = percent)
scale_y_continuous(expand=c(1/(nrow(mydataframe)-1),0)

感谢您的帮助。

【问题讨论】:

    标签: r plot ggplot2 histogram


    【解决方案1】:

    总结以上答案:

    library(tidyverse)
    
    mydataframe <- data.frame(name = c("A", "B", "C", "D"),
                              value = c(0.0000354, 0.00768, 0.00309, 0.000123))
    
    ggplot(mydataframe, aes(x = value)) +
      geom_histogram(aes(y = stat(count / sum(count)))) +
      scale_y_continuous(labels = scales::percent_format()) +
      labs(x="", y="")
    

    【讨论】:

      【解决方案2】:

      我只是想缩放轴,将 y 轴除以 1000,所以我做了:

      ggplot(mydataframe, aes(x=value)) +
        geom_histogram(aes(y=..count../1000))
      

      【讨论】:

        【解决方案3】:

        从最新最好的 ggplot2 版本 3.0.0 开始,格式发生了变化。现在您可以将y 值包装在stat() 中,而不是与.. 混淆。

        ggplot(mydataframe, aes(x = value)) +
          geom_histogram(aes(y = stat(count / sum(count))))
        

        【讨论】:

        • @CephBirk假设我还为审美指定了fill=columncount/sum(count) 是按总数归一化,还是按每个填充组中的数归一化?
        • 这个答案解决了这个问题:stackoverflow.com/a/22181949/188963
        【解决方案4】:

        从 ggplot2 0.9 开始,许多格式化程序函数已移至 scales 包中,包括 percent_format()

        library(ggplot2)
        library(scales)
        
        mydataframe <- data.frame(name = c("A", "B", "C", "D"),
                                  value = c(0.0000354, 0.00768, 0.00309, 0.000123))
        
        ggplot(mydataframe) + 
          geom_histogram(aes(x = value, y = ..ncount..)) +
          scale_y_continuous(labels = percent_format())
        

        【讨论】:

        • 感谢您的澄清!我想知道我的格式有什么问题...
        【解决方案5】:

        请注意,..ncount.. 重新缩放到最大值 1.0,而 ..count.. 是未缩放的 bin 计数。

        ggplot(mydataframe, aes(x=value)) +
          geom_histogram(aes(y=..count../sum(..count..)))
        

        这给出了:

        【讨论】:

        • 这正是我想要的。你让人觉得自己像个白痴,我真的很感谢你!
        • 我不知道可以做这样的事情。多亏了这个技巧,我能够使用aes(y=1-cumsum(..count..)/sum(..count..)) 生成生存/可靠性(即 1-CDF)直方图。
        猜你喜欢
        • 2014-04-06
        • 2017-12-19
        • 1970-01-01
        • 1970-01-01
        • 2014-01-30
        • 2019-04-13
        • 1970-01-01
        • 2017-10-05
        相关资源
        最近更新 更多