【问题标题】:r frequency counts on overlayed histogram and density plotr 频率计数叠加直方图和密度图
【发布时间】:2020-08-08 09:42:35
【问题描述】:

我有兴趣在由密度图覆盖的直方图上添加频率计数。 This question is similar to a question already posted on SO 其他用户。我尝试了为该问题提供的解决方案,但没有奏效。

这是我的测试数据集

df <- data.frame(cond = factor( rep(c("A","B"), each=200)), 
                 rating = c(rnorm(200), rnorm(200, mean=.8)))

这将绘制一个带有计数的直方图

ggplot(df, aes(x=rating)) + geom_histogram(binwidth=.5, colour="black", fill="white")

这将绘制这样的密度图

ggplot(df, aes(x=rating)) + geom_density()

我尝试将两者结合起来,

ggplot(df, aes(x=rating)) + geom_histogram(aes(y=..count..), binwidth=.5, colour="black", fill="white") + geom_density(alpha=.2, fill="#FF6666")

叠加的密度图不见了。

我试过这种方法

ggplot(df, aes(x=rating)) + geom_histogram(binwidth=0.5, colour="black", fill="white") + stat_bin(aes(y=..count.., ,binwidth=0.5,label=..count..), geom="text", vjust=-.5) + geom_density(alpha=.2, fill="#FF6666")

这几乎没问题,但不显示密度图并覆盖了我的 bindwidth 值(头部刮刀)。

我如何保留带有计数的直方图并显示重叠的密度图?

【问题讨论】:

    标签: r ggplot2 histogram density-plot


    【解决方案1】:

    这将解决您的问题。问题与 binwidth 有关您需要通过计数和 bin 宽度调整密度图的 y 值,因为密度始终 = 1。

    library(ggplot2)
    
    set.seed(1234)
    
    df <- data.frame(cond = factor( rep(c("A","B"), each=200)), 
                     rating = c(rnorm(200), rnorm(200, mean=.8)))
    
    ggplot(df, aes(x=rating)) + 
      geom_histogram(aes(y = ..count..), binwidth = 0.5, colour = "black", fill="white") +
      stat_bin(aes(y=..count.., binwidth = 0.5,label=..count..), geom="text", vjust=-.5) + 
      geom_density(aes(y = ..count.. * 0.5), alpha=.2, fill="#FF6666")
    
    
    # This is more elegant: using the built-in computed variables for the geom_ functions
    
    
    ggplot(df, aes(x = rating)) + 
      geom_histogram(aes(y = ..ncount..), binwidth = 0.5, colour = "black", fill="white") +
      stat_bin(aes(y=..ncount.., binwidth = 0.5,label=..count..), geom="text", vjust=-.5) + 
      geom_density(aes(y = ..scaled..), alpha=.2, fill="#FF6666")
    
    

    结果:

    【讨论】:

    • 谢谢彼得。我将更改 binwidth 值并调整绘图以适合我的数据。
    • 由你决定你做什么......但第二个解决方案是迄今为止最好的,因为它将独立于 binwidth。
    猜你喜欢
    • 2020-06-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2021-03-14
    相关资源
    最近更新 更多