如何将高斯曲线添加到使用qplot创建的直方图? [英] How to add gaussian curve to histogram created with qplot?
问题描述
我的问题可能类似于将密度曲线拟合为R中的直方图。使用qplot我用这个命令创建了7个直方图:
(qplot(V1,data = data,binwidth = 10,facets = V2〜。)
对于每个切片,我想添加一个拟合的高斯曲线。使用 lines()
方法,我得到错误:
Error in plot.xy(xy.coords(x,y),type = type,...):
plot.new尚未被调用
正确地执行该命令的是什么命令?
stat_function
?
+ stat_function(fun = dnorm)
您可能需要使用 aes(y = ..density .. )
来绘制密度值而不是计数。
大量有用的信息可以在此问题,包括一些关于在不同方面绘制不同正常曲线的建议。
以下是一些示例:
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,color =red)
从我链接到的问题,创建一个单独的数据框与不同的正常曲线:
grid< - with(dat ,seq(min(x),max(x),length = 100))
normaldens < - ddply(dat,a,function(df){
data.frame(
预测=网格,
密度= dnorm(网格,平均值(df $ x),s d(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 =密度),color =red)
I have question probably similar to Fitting a density curve to a histogram in R. Using qplot I have created 7 histograms with this command:
(qplot(V1, data=data, binwidth=10, facets=V2~.)
For each slice, I would like to add a fitting gaussian curve. When I try to use lines()
method, I get error:
Error in plot.xy(xy.coords(x, y), type = type, ...) :
plot.new has not been called yet
What is the command to do it correctly?
Have you tried stat_function
?
+ stat_function(fun = dnorm)
You'll probably want to plot the histograms using aes(y = ..density..)
in order to plot the density values rather than the counts.
A lot of useful information can be found in this question, including some advice on plotting different normal curves on different facets.
Here are some examples:
dat <- data.frame(x = c(rnorm(100),rnorm(100,2,0.5)),
a = rep(letters[1:2],each = 100))
Overlay a single normal density on each facet:
ggplot(data = dat,aes(x = x)) +
facet_wrap(~a) +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, colour = "red")
From the question I linked to, create a separate data frame with the different normal curves:
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))
)
})
And plot them separately using 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")
这篇关于如何将高斯曲线添加到使用qplot创建的直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!