【问题标题】:General rule of overlaying density plot using ggplot2使用ggplot2覆盖密度图的一般规则
【发布时间】:2020-04-15 09:15:31
【问题描述】:

我是 R 编程语言的新手。使用 ggplot2 在直方图上叠加密度曲线的标准/通用方法是什么?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这取决于您是需要经验密度估计还是拟合理论密度。在这两种情况下,您都需要将直方图箱的宽度与密度相匹配。

    对于经验核密度估计:

    library(ggplot2)
    
    # dummy data
    df <- data.frame(
      x = rnorm(1000)
    )
    
    binwidth <- 0.1
    ggplot(df, aes(x)) +
      geom_histogram(binwidth = binwidth) +
      geom_density(aes(y = after_stat(count * binwidth)),
                   color = "red")
    

    理论密度估计并不存在于 ggplot2 中,而是存在于扩展包中。免责声明:我是以下包的作者,所以我有偏见:

    library(ggh4x)
    
    ggplot(df, aes(x)) +
      geom_histogram(binwidth = binwidth) +
      stat_theodensity(aes(y = after_stat(count * binwidth)),
                       color = "red")
    

    或者,如果您不想设置 binwidths,您也可以将直方图缩放为密度:

    ggplot(df, aes(x)) +
      geom_histogram(aes(y = after_stat(density))) +
      geom_density(color = "red")
    

    注意:after_stat() 需要 ggplot2 v3.3.0,早期版本使用stat()

    【讨论】:

    • 谢谢。第三种选择奏效了。另外两个给出了以下错误消息:层中的错误(数据=数据,映射=映射,stat = stat,geom = GeomBar,找不到对象'binwidth'
    • 这可能是因为binwidth 是一个变量,您会事先分配给自己,例如在我的答案的第一个代码块中。
    【解决方案2】:

    您需要确保将密度图调用中 ..count.. 的值乘以直方图调用中 binwidth 的值。

    你可以这样做:

    set.seed(100)
    a = data.frame(z = rnorm(10000))
    binwidthVal=0.1
    ggplot(a, aes(x=z)) + 
    geom_histogram(binwidth = binwidthVal) + 
    geom_density(colour='red', aes(y=binwidthVal * ..count..))
    

    Credit to Brian Diggs for the idea.

    编辑:似乎已经有一个非常好的答案here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 2019-11-07
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 2012-09-28
      相关资源
      最近更新 更多