【问题标题】:How to avoid a flat density line in ggplot2如何避免ggplot2中的平坦密度线
【发布时间】:2020-08-14 14:14:30
【问题描述】:

我试图在 2 个重叠的直方图上绘制一条密度线,但是对于我使用的每个代码,这条线都会变得“平坦”。

我必须创建两个直方图,每个直方图都具有正态分布和不同数量的样本。然后我必须将两者重叠并写下密度线。全部带有 ggplot2 包。

这是我尝试过的:

xx<-data.frame(dat = rnorm(n, mean, sd))
yy<-data.frame(dat = rnorm(n, mean, sd))
both<-rbind(xx, yy)

ggplot(both, aes(x=dat)) + 
    geom_histogram(data = xx, fill = "red", alpha = 0.2,binwidth=0.25) + 
    geom_histogram(data = yy, fill = "blue", alpha = 0.2, binwidth=0.25) +
    theme_light() +
    geom_line(data=samples, stat = "density")

我也试过geom_density,但结果是一样的......

【问题讨论】:

  • 请您编辑问题以包含一些示例数据(您可以使用dput(sample1))。最好的策略可能是将 sample1 和 sample2 与dplyr::bind_rows 结合起来,并将fill 添加到aes

标签: r ggplot2 histogram kernel-density density-plot


【解决方案1】:

密度线不是平坦的,它只是相对于直方图的一个非常不同的比例,因为默认情况下,直方图是使用 y 轴上的计数创建的。

你应该指定y = after_stat(density)

# packages
library(ggplot2)

# data
set.seed(1)
sample1 <- data.frame(dat = rnorm(10000, 0, 1))
sample2 <- data.frame(dat = rnorm(15000, 3, 1))
both <- rbind(sample1, sample2)

ggplot(both, aes(x = dat)) + 
  geom_histogram(aes(y = after_stat(density)), data = sample1, fill = "red", alpha = 0.2, binwidth = 0.25) + 
  geom_histogram(aes(y = after_stat(density)), data = sample2, fill = "blue", alpha = 0.2, binwidth=0.25) +
  theme_light() +
  geom_line(stat = "density")

reprex package (v0.3.0) 于 2020 年 4 月 30 日创建

黑线表示两种正态分布的混合。您应该阅读after_stat 函数的帮助页面以获取更多详细信息。

【讨论】:

  • 我收到一个错误,说Error in after_stat(density) : could not find function "after_stat"虽然library(ggplot2) 已激活
  • after_stat() 函数是在 ggplot2 的 3.3.0 版中引入的(请参阅此处“新功能”部分的第一个要点:cran.r-project.org/web/packages/ggplot2/news/news.html)。如果可以,我认为您应该更新软件包,否则您可以使用旧方法,即y = stat(density)y = ..density..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
相关资源
最近更新 更多