gpt4 book ai didi

r - 如何将高斯曲线添加到使用 qplot 创建的直方图?

转载 作者:行者123 更新时间:2023-12-02 09:33:20 25 4
gpt4 key购买 nike

我的问题可能类似于 Fitting a density curve to a histogram in R 。使用 qplot 我用这个命令创建了 7 个直方图:

 (qplot(V1, data=data, binwidth=10, facets=V2~.)   

对于每个切片,我想添加一条拟合高斯曲线。当我尝试使用 lines() 方法时,出现错误:

Error in plot.xy(xy.coords(x, y), type = type, ...) : 
plot.new has not been called yet

正确执行此操作的命令是什么?

最佳答案

您尝试过stat_function吗?

+ stat_function(fun = dnorm)

您可能需要使用 aes(y = ..密度..) 绘制直方图,以便绘制密度值而不是计数。

很多有用的信息可以在this中找到。问题,包括在不同方面绘制不同正态曲线的一些建议。

以下是一些示例:

dat <- data.frame(x = c(rnorm(100),rnorm(100,2,0.5)), 
a = rep(letters[1:2],each = 100))

在每个面上覆盖单个法线密度:

ggplot(data = dat,aes(x = x)) + 
facet_wrap(~a) +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, colour = "red")

enter image description here

根据我链接到的问题,创建一个具有不同正态曲线的单独数据框:

grid <- with(dat, seq(min(x), max(x), length = 100))
normaldens <- ddply(dat, "a", function(df) {
data.frame(
predicted = grid,
density = dnorm(grid, mean(df$x), sd(df$x))
)
})

并使用geom_line分别绘制它们:

ggplot(data = dat,aes(x = x)) + 
facet_wrap(~a) +
geom_histogram(aes(y = ..density..)) +
geom_line(data = normaldens, aes(x = predicted, y = density), colour = "red")

enter image description here

关于r - 如何将高斯曲线添加到使用 qplot 创建的直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7182556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com