我正在尝试制作一个密度值的直方图,并将其与密度函数(而不是密度估计)的曲线叠加。
使用一个简单的标准正态示例,下面是一些数据:
x <- rnorm(1000)我可以这样做:
q <- qplot( x, geom="histogram")
q + stat_function( fun = dnorm )但这给出了直方图的频率尺度,而不是密度。使用..density..,我可以在直方图上获得适当的比例:
q <- qplot( x,..density.., geom="histogram")
q但现在这给出了一个错误:
q + stat_function( fun = dnorm )是不是有什么我没看到的?
另一个问题是,有没有一种方法可以像curve()一样绘制函数的曲线,但不是作为图层?
发布于 2011-04-17 01:02:00
这就是你要的!
# create some data to work with
x = rnorm(1000);
# overlay histogram, empirical density and normal density
p0 = qplot(x, geom = 'blank') +
geom_line(aes(y = ..density.., colour = 'Empirical'), stat = 'density') +
stat_function(fun = dnorm, aes(colour = 'Normal')) +
geom_histogram(aes(y = ..density..), alpha = 0.4) +
scale_colour_manual(name = 'Density', values = c('red', 'blue')) +
theme(legend.position = c(0.85, 0.85))
print(p0)发布于 2015-12-16 16:29:24
Ramnath答案的更基本的替代方案,传递观察到的平均值和标准差,并使用ggplot而不是qplot
df <- data.frame(x = rnorm(1000, 2, 2))
# overlay histogram and normal density
ggplot(df, aes(x)) +
geom_histogram(aes(y = stat(density))) +
stat_function(
fun = dnorm,
args = list(mean = mean(df$x), sd = sd(df$x)),
lwd = 2,
col = 'red'
)

发布于 2019-02-15 06:43:31
如果使用ggplot2中的geom_density()呢?如下所示:
df <- data.frame(x = rnorm(1000, 2, 2))
ggplot(df, aes(x)) +
geom_histogram(aes(y=..density..)) + # scale histogram y
geom_density(col = "red")

这也适用于多模态分布,例如:
df <- data.frame(x = c(rnorm(1000, 2, 2), rnorm(1000, 12, 2), rnorm(500, -8, 2)))
ggplot(df, aes(x)) +
geom_histogram(aes(y=..density..)) + # scale histogram y
geom_density(col = "red")

https://stackoverflow.com/questions/5688082
复制相似问题