Skip to content

ggplot - adding regression lines

2 messages · soon yi, Ben Bolker

#
Hi

I am using ggplot to overlay two regression lines on a scatter plot each
corresponding to a treatment group.

The default plot gives a different slope for each treatment group. However,
in some cases i want the lines to be parallel -ie no significant
interaction. 

My code:

ggplot(data=df,X,Y,colour=treatment) + geom_point() +
geom_smooth(method="lm")

I think i use the 'formula' option in geom_smooth but have been unable to
find a solution.

thanks for any advice.

sy




--
View this message in context: http://r.789695.n4.nabble.com/ggplot-adding-regression-lines-tp4652906.html
Sent from the R help mailing list archive at Nabble.com.
#
soon yi <soon.yi <at> ymail.com> writes:
I don't think you can actually do this entirely within ggplot.
  Instead I think you need something like

modelfit <- lm(Y~X+treatment,data=df)
newdata <- with(df,expand.grid(X=seq(min(X),max(X),length=41),
                               treatment=levels(treatment))
newdata$Y <- predict(modelfit,newdata)

ggplot(data=df,X,Y,colour=treatment) + geom_point() +
 geom_line(data=newdata)

The confidence intervals are a little bit more work: see `?predict`
and `geom_ribbon` ...