r - 具有经验密度和 dnorm 函数的叠加直方图
问题描述
我想用经验和正常密度曲线覆盖 ggplot 直方图(y 轴 = 计数)。我试过了:
library(ggplot2)
set.seed(1234)
v <- as_tibble(rnorm(1000, 10, 2.5))
ggplot(v, aes(x = value)) +
geom_histogram(aes(y = ..density..),
bins = 40, colour = "black", fill = "white") +
geom_line(aes(y = ..density.., color = 'Empirical'), stat = 'density') +
stat_function(fun = dnorm, aes(color = 'Normal'),
args = list(mean = 10, sd = 2.5)) +
scale_colour_manual(name = "Colors", values = c("red", "blue"))
但这具有作为 y 比例的密度,并且我希望频率作为 y 轴。
我的第二次试验产生了以频率(计数)为 y 轴但仅以经验密度为单位的图。
library(ggplot2)
set.seed(1234)
v <- as_tibble(rnorm(1000, 10, 2.5))
b <- seq(0, 20, by = 0.5)
p1 <- ggplot(v, aes(x = value)) +
geom_histogram(aes(y = ..count..),
breaks = b,
binwidth = 0.5,
colour = "black",
fill = "white") +
geom_line(aes(y = ..density.. * (1000 * 0.5),
color = 'Empirical'),
stat = 'density') +
scale_colour_manual(name = "Colors", values = c("red", "blue"))
我无法在同一个图中也显示一条 dnorm 曲线。例如,当我尝试下一行时,我得到了 x 轴上的密度曲线(蓝线)。
p2 <- p1 + stat_function(fun = dnorm, aes(color = 'Normal'),
args = list(mean = 10, sd = 2.5))
p2
我假设我必须用 binwidth 调整曲线(如经验线),但我不知道该怎么做。
我在 SO 中搜索了这个问题,可以找到许多类似的问题。但是所有这些都解决了我的第一次试验(以密度为 y 轴)、带有计数轴的经验叠加(我的第二次试验)或使用了我不熟悉的其他(基本)绘图命令。
解决方案
我按照@user20650 的链接重写了我的代码,并将@PatrickT 的答案应用于我的问题。
library(ggplot2)
n = 1000
mean = 10
sd = 2.5
binwidth = 0.5
set.seed(1234)
v <- as_tibble(rnorm(n, mean, sd))
b <- seq(0, 20, by = binwidth)
ggplot(v, aes(x = value, mean = mean, sd = sd, binwidth = binwidth, n = n)) +
geom_histogram(aes(y = ..count..),
breaks = b,
binwidth = binwidth,
colour = "black",
fill = "white") +
geom_line(aes(y = ..density.. * n * binwidth, colour = "Empirical"),
size = 1, stat = 'density') +
stat_function(fun = function(x)
{dnorm(x, mean = mean, sd = sd) * n * binwidth},
aes(colour = "Normal"), size = 1) +
labs(x = "Score", y = "Frequency") +
scale_colour_manual(name = "Line colors", values = c("red", "blue"))
决定性的变化在于stat-function
提供了对 n 和 binwidth 的必要调整。此外,我不知道可以将参数传递给 aes()。
推荐阅读
- sql - 在 wp_postmeta 表中存储一些数值并使用 sql 查询获取它是一种好习惯吗?(WordPress,数据库)
- pytorch - 在pytorch中合并两个张量
- r - 我不能在 else 中使用很多 ifelse 吗?
- python - Django中不同角色的权限
- html - 在 hi dpr 屏幕上使用 srcset 时,图像显示大小减半
- python - tf.layers.Dense 不适用于张量流。如何使用它?
- javascript - 如何在套件中使用 nlapiXMLToPDF
- apache-spark - 如何在火花流应用程序中使用滞后/领先功能?
- laravel - 图像不存储在 Laravel 6 中
- python - 如何将 lambda 从 python2 迁移到 python3 并在 python3 中处理删除的元组参数解包