用经验密度和dnorm函数叠加直方图

用经验密度和dnorm函数叠加直方图,r,ggplot2,R,Ggplot2,我想将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 =

我想将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"))
库(ggplot2)
种子集(1234)

v我根据@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"))
库(ggplot2)
n=1000
平均值=10
sd=2.5
宽度=0.5
种子集(1234)

实际上,ggplot2支持第二个y轴。实际上,我不认为它是重复的,而是由不同的问题组成的,突出的,最后的。
p2 <- p1 + stat_function(fun = dnorm, aes(color = 'Normal'),
                     args = list(mean = 10, sd = 2.5))
p2  
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"))