r - 如何避免ggplot2中的平坦密度线
问题描述
我正在尝试在 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
,但结果是一样的......
解决方案
密度线不是平坦的,它只是相对于直方图的一个非常不同的比例,因为默认情况下,直方图是使用 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 包(v0.3.0)于 2020-04-30 创建
黑线代表两种正态分布的混合。您应该阅读该after_stat
功能的帮助页面以获取更多详细信息。
推荐阅读
- vue.js - Feathers vuex:刷新后用户不再登录
- flutter - 使用应用图标打开应用时获取所有通知消息(如果有)
- laravel - Vuetify 中的未知自定义元素
- python - 散景:触发回调后,Hovertool 在旧实例上堆叠
- vba - 如何创建邮件项?
- javascript - 在服务器端代码命中之前获取 AjaxUpload 中的 onComplete
- r - 基于条件的R数据表分组并根据条件获取计数
- javascript - 如何使用 Javascript 读取具有自动生成的文档 ID 的 Firebase 文档
- vb.net - IsNumeric() 允许最后的值减去
- ios - 如何在 UITableViewCell 中制作选择样式