2010-12-07 63 views
12

显示原始的和拟合的数据(nls + dnorm)我正在探索一些数据,所以我想要做的第一件事就是尝试适应正常(高斯)分布。这是我第一次在R中尝试这个,所以我一次只采取一步。首先,我预先分级我的数据:试图用ggplot2的geom_smooth()

myhist = data.frame(size = 10:27, counts = c(1L, 3L, 5L, 6L, 9L, 14L, 13L, 23L, 31L, 40L, 42L, 22L, 14L, 7L, 4L, 2L, 2L, 1L)) 

qplot(x=size, y=counts, data=myhist) 

plot1

因为我要计数,我需要添加一个归一化因子(N)按比例增加密度:

fit = nls(counts ~ N * dnorm(size, m, s), data=myhist, start=c(m=20, s=5, N=sum(myhist$counts))) 

然后我创建适合显示的数据,一切都很好:

x = seq(10,30,0.2) 
fitted = data.frame(size = x, counts=predict(fit, data.frame(size=x))) 
ggplot(data=myhist, aes(x=size, y=counts)) + geom_point() + geom_line(data=fitted) 

plot2

我很兴奋,当我发现这个线程,其讲述使用geom_smooth()做这一切一步到位,但我不能得到它的工作:

这是我尝试...和我所得到的:

ggplot(data=myhist, aes(x=size, y=counts)) + geom_point() + geom_smooth(method="nls", formula = counts ~ N * dnorm(size, m, s), se=F, start=list(m=20, s=5, N=300, size=10)) 

Error in method(formula, data = data, weights = weight, ...) : 
    parameters without starting value in 'data': counts 

的错误似乎表明,它试图将所观察到的变量,计数,但是这并没有任何意义,而且可预见的怪胎,如果我指定一个计数“启动”太超值了:

fitting parameters ‘m’, ‘s’, ‘N’, ‘size’, ‘counts’ without any variables 

Error in eval(expr, envir, enclos) : object 'counts' not found 

任何想法,我做错了吗?当然,这不是世界末日,但更少的步骤总是更好,而且你们总是为这些常见任务提出最优雅的解决方案。

在此先感谢!

杰弗里

+1

你提到你正在探索数据。是否有必要使用'nls`?使用一个简单的`ggplot(myhist,aes(x = size,y = counts))+ geom_point()+ geom_smooth()`可以让你变得轻松愉快(我相信)。我希望有人会解释如何让`nls`工作,虽然......相当神秘。 – 2010-12-07 22:49:02

+0

我来(不情愿)从自然科学的统计,所以“探索”往往意味着“时间适合高斯!”。尽管如此,我认为我发现了一些很棒的资源,比如利玛窦的“R中的拟合分布”(http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf),并且这个答案在fitdistr( )(http://stackoverflow.com/questions/4290081/fitting-data-to-distributions),但没有一个旧的东西使用ggplot2。 – 2010-12-08 16:12:29

回答

16

第一错误指示GGPLOT2找不到变量“计数”,这是在式中使用,在数据。

统计发生在映射后,即大小 - > x,并计数 - > y。

下面是在使用geom_smooth NLS一个例子:

ggplot(data=myhist, aes(x=size, y=counts)) + geom_point() + 
    geom_smooth(method="nls", formula = y ~ N * dnorm(x, m, s), se=F, 
       start=list(m=20, s=5, N=300)) 

的一点是,使用x和y,代替大小和计数,在式规范。

相关问题