2011-08-24 127 views
9

我有问题,可能类似于Fitting a density curve to a histogram in R。使用qplot我已经创建了7个直方图使用此命令:如何将高斯曲线添加到使用qplot创建的直方图?

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

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

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

+1

不能混合基图形功能('线()'等)与网格图形。 –

回答

14

你试过stat_function

+ stat_function(fun = dnorm) 

你可能会想用绘制的aes(y = ..density..)直方图,以绘制密度值,而不是计数。

了很多有用的信息可以在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

从I挂,则创建一个单独的数据帧中的问题不同的正常曲线:

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

+0

我在R的初学者,只有它几天。我会看看它,谢谢你的提示! – mkk

+0

Muito Bom!我ajudou horrores !!!! – Jean

5

ggplot2使用不同的图形范例比基础的图形。 (虽然你可以使用grid显卡,拥有它,最好的办法是到一个新的stat_function层添加到情节。该ggplot2代码如下。

请注意,我不能让这个使用qplot工作,但过渡到ggplot是相当简单明了,最重要的区别在于你的数据必须是data.frame格式

另外要注意的显式映射在y审美aes=aes(y=..density..)) - 这是不寻常的性能稍微但采取stat_function结果它映射到数据:

作为所使用的** gpplot2 **和** **晶格包
library(ggplot2) 
data <- data.frame(V1 <- rnorm(700), V2=sample(LETTERS[1:7], 700, replace=TRUE)) 
ggplot(data, aes(x=V1)) + 
    stat_bin(aes(y=..density..)) + 
    stat_function(fun=dnorm) + 
    facet_grid(V2~.) 

enter image description here