[R] ggplot - adding regression lines

Ben Bolker bbolker at gmail.com
Thu Dec 13 01:06:51 CET 2012


soon yi <soon.yi <at> ymail.com> writes:

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

  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` ...




More information about the R-help mailing list