簡體   English   中英

試圖用ggplot2的geom_smooth()顯示原始數據和擬合數據(nls + dnorm)

[英]trying to display original and fitted data (nls + dnorm) with ggplot2's geom_smooth()

我正在探索一些數據,所以我想要做的第一件事就是嘗試將正態(高斯)分布擬合到它。 這是我第一次在R中嘗試這個,所以我一步一步。 首先我預先分類我的數據:

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

知道我做錯了什么嗎? 當然,這不是世界末日,但更少的步驟總是更好,你們總是為這些常見任務提出最優雅的解決方案。

提前致謝!

傑弗里

第一個錯誤表明ggplot2無法在數據中找到公式中使用的變量'count'。

映射后進行統計,即size - > x,count - > 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而不是大小和計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM