首页 > 解决方案 > 具有经验密度和 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 轴)、带有计数轴的经验叠加(我的第二次试验)或使用了我不熟悉的其他(基本)绘图命令。

标签: rggplot2

解决方案


我按照@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()。

在此处输入图像描述


推荐阅读