[R] plot with a regression line(s)

S Ellison S.Ellison at LGCGroup.com
Wed Apr 4 20:25:09 CEST 2012


 

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Sam Steingold
>
> plot.glm <- function (x, y, file = NULL, xlab = 
> deparse(substitute(x)),
>                       ylab = deparse(substitute(y)), main = NULL) {
>   m <- glm(y ~ x)
>   if (!is.null(file))
>     pdf(file = file)
>   plot(x, y, xlab = xlab, ylab = ylab, main = main)
>   lines(x, y = m$fitted.values, col = "green")
>   if (!is.null(file))
>     dev.off()
>   print(m)
> }
> 
> is there a better/easier/more general way?


There is no guarantee that x is sorted in ascending order for a glm (or any other model), so lines(x, fitted()) can give very spiny results. Even if sorted, non-linear fits with large gaps in x will not give smooth lines.

Better to use something along the lines of the budworm example in the glm help page, which uses predict() on a new sequence.
If you want something a bit more general, you can use either range(x) to get the new sequence limits or  par("usr")[1:2]  to gets the current plot x limits.


S Ellison
*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list