faceting multiple lm models

27 views
Skip to first unread message

Alexander Shenkin

unread,
Mar 20, 2012, 5:38:38 PM3/20/12
to ggp...@googlegroups.com
Hi folks,

I'm trying to facet a bunch of dotplots along with their lm fits.
Currently, I loop over the various subsets of the data to create a list
of lm fits. I can facet the dot plots, but I'm not sure how to get the
fits from from the list of lm-objects in there.

pseudo-code:
fit_list = list()
for (i in species) {
sub_data = subset(alldata, species == i)
fit_list[i] = lm(growth ~ size, data=sub_data)
}

ggplot(data = alldata, aes(x=size, y=growth)) + geom_point() +
facet_wrap(~ species)

The above gets me the faceted dot plots. I don't think geom_smooth
handles lists of lm fits. Any suggestions are greatly appreciated!

Thanks,
Allie

R. Michael Weylandt

unread,
Mar 20, 2012, 5:56:31 PM3/20/12
to Alexander Shenkin, ggp...@googlegroups.com
If I understand you right, you want the fit line for each facet to
depend only on the points of that facet: I think what you are looking
for is

ggplot(alldata, aes(x = size, y = growth)) + geom_point() +
stat_smooth(method = "lm") + facet_wrap( ~ species)

E.g.,

data(diamonds)
ggplot(diamonds, aes(x = carat, y = price)) + geom_point() +
stat_smooth(method = "lm") + facet_wrap(~ cut, ncol = 1)

Note that in each facet, the resulting line is different.

Hope this helps,
Michael

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2

Alexander Shenkin

unread,
Mar 20, 2012, 6:19:29 PM3/20/12
to R. Michael Weylandt, ggp...@googlegroups.com
Thanks Michael - that was exactly what I was looking for. Perhaps my
question gets filed in the "duh" category.

Somehow I get paranoid about fitting lm myself, and then using ggplot to
plot the lines. For example, if there's some obscure difference in
subsetting, or some problem, etc. In the case that, for whatever
reason, I want to use my manually-fitted lm's for plotting, is there any
way to go about that in ggplot?

thanks again,
allie

baptiste auguie

unread,
Mar 20, 2012, 6:39:33 PM3/20/12
to Alexander Shenkin, ggp...@googlegroups.com
You need to construct a data.frame with the same facetting variable,

data(diamonds)
ggplot(diamonds) + geom_point(aes(x = carat, y = price)) +


facet_wrap(~ cut, ncol = 1)

library(plyr)
fits = ddply(diamonds, .(cut), function(d) coeff = coef(lm(price~carat,data=d)))
last_plot() + geom_abline(aes(intercept=`(Intercept)`,slope =
carat),col="blue",data=fits)

HTH,

b.

Reply all
Reply to author
Forward
0 new messages