【问题标题】:ggplot2 geom_density and geom_histrogram in one plotggplot2 geom_density 和 geom_histrogram 在一个图中
【发布时间】:2017-01-27 23:18:21
【问题描述】:

如何制作一个所有条形加起来为 1 的直方图,并在其上方添加一个适合的密度层?

set.seed(1234)
df <- data.frame(
  sex=factor(rep(c("F", "M"), each=200)),
  weight=round(c(rnorm(200, mean=55, sd=5),
                 rnorm(200, mean=65, sd=5)))
  )

(取自:http://www.sthda.com/english/wiki/ggplot2-density-plot-quick-start-guide-r-software-and-data-visualization

ggplot(df, aes(x=weight, color=sex, fill=sex)) + 
 geom_histogram(aes(y=..density..), alpha=0.5, 
                position="identity")+
 geom_density(alpha=.2) 

但是当我将aes(y=..density..) 更改为aes(y=..scaled..) 时,我得到一个错误。

如果我将这个示例与我的(大)数据一起使用,密度会上升到 120。 所以基本上是这样的: ![酒吧]http://www.sthda.com/sthda/RDoc/figure/easy-ggplot2/ggplot2-histogram-multiple-groups3.png 具有不同的 y 轴。 (使一种类型的所有条形加起来为 1)

我不确定使用 geom_smooth 在统计上是否合法?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    尝试使用y = ..density../sum(..density..)

    set.seed(1234)
    df <- data.frame(
        sex=factor(rep(c("F", "M"), each=200)),
        weight=round(c(rnorm(200, mean=55, sd=5),
                       rnorm(200, mean=65, sd=5)))
    )
    
    library(ggplot2)
    
    ggplot(df, aes(x=weight, color=sex, fill=sex)) + 
        geom_histogram(aes(y=..density../sum(..density..)), alpha=0.5, 
                       position="identity")+
        geom_density(alpha=.2)
    

    【讨论】:

    • geom_histogram(aes(y=..count../sum(..count..)), alpha=0.5, position="identity") 也可以。
    猜你喜欢
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2014-11-22
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多