Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

r - Extract coefficients from ggplot2-created nls fit

There's a nice explanation here of how to use ggplot2 to create a scatterplot, fit the data using nls, and plot the fit, all in one line, like so

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) )

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)) 

My question is: using this construction, is it possible to pull out the actual nls object from that call? I'd like to know my coefficients, etc. Right now I can't figure out how to get them without doing a separate nls call.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My question is: using this construction, is it possible to pull out the actual nls object from that call? I'd like to know my coefficients, etc.

This is currently not possible in ggplot2. The ggplot2 functions return predictions from the model, but not the model object itself. Thus, you cannot extract an nls object from the ggplot object to find the coefficients, etc.

There are two relevant discussions in the ggplot2 and ggplot2-dev mailing lists:

https://groups.google.com/d/topic/ggplot2/7tiUB2sjCxM/discussion

https://groups.google.com/d/topic/ggplot2-dev/dLGJnzIg4ko/discussion

Quick synopsis:

While many users have asked for the ability to extract statistics from ggplot objects, the developers are considering it but seem somewhat opposed. They would prefer users to use ggplot2 for visualization, and appropriate modelling functions to explore modelling parameters. However, Hadley supports the idea of implementing the ability to pass a model object to a ggplot() call. So, instead of trying to extract the nls object from your ggplot object, you would instead:

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

That way, the model only needs to be called once, you can do anything you want to it, and you don't have to go searching through ggplot objects to find it. However, I don't know when or if this will be implemented.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...