我根据@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()。