[R] Plotting two regression lines on one graph

Dylan Beaudette dylan.beaudette at gmail.com
Mon Jun 8 06:23:47 CEST 2009


One approach to this is generating a representative sequence of your
x-variable(s) with seq() or expand.grid(). Next use the predict()
function to make predictions from your glm object along the sequence.
Finally, plot the predictions vs. the new sequence. Putting everything
into a dataframe helps.

# generate some data:
x <- rnorm(10)
y <- x * 2 + rnorm(10, sd=0.5)

# plot
plot(y ~ x)

# generate linear model:
l <- lm(y ~ x)

# generate sequence along x-var
# and predictions
d <- data.frame(x.new=seq(from=-1.5, to=1.2, by=0.1))
d$y.new <- predict(l, data.frame(x=d$x.new))

# add to plot:
lines(y.new ~ x.new, data=d, lwd=2)

Cheers,
Dylan


On Sun, Jun 7, 2009 at 8:36 PM, Jo Stringer<JStringer at bses.org.au> wrote:
> Hi!
>
>
> I have fitted two glms assuming a poisson distribution which are:
>
> fit1 <- glm(Aids ~ Year, data=aids, family=poisson())
>
> fit2 <- glm(Aids ~ Year+I(Year^2), data=aids, family=poisson())
>
>
> I am trying to work out how to represent the fitted regression curves of fit1 and fit2 on the one graph. I have tried:
>
> graphics.off()
>
> plot(Aids ~ Year, data = aids)
>
>
> line(glm(Aids ~ Year, data=aids, family=poisson()))
> line(glm(Aids ~ Year+I(Year^2), data=aids, family=poisson()))
>
> but this does not work.
>
> Can anyone help me?
>
> Thanks
>
> Jo
>
> BSES Limited Disclaimer
>
> --------------------------------------------------------------------------------
>
> This email and any files transmitted with it are confide...{{dropped:15}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list