2010-12-07 66 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,代替大小和計數,在式規範。

相關問題