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 = d
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.