followup: Re: [R] Issue with predict() for glm models

Marc Schwartz MSchwartz at
Thu Sep 23 19:42:32 CEST 2004

On Thu, 2004-09-23 at 12:02, Paul Johnson wrote:
> I have a follow up question that fits with this thread.
> Can you force an overlaid plot showing predicted values to follow the 
> scaling of the axes of the plot over which it is laid?
> Here is an example based on linear regression, just for clarity.  I have 
> followed the procedure described below to create predictions and now 
> want to plot the predicted values "on top" of a small section of the x-y 
> scatterplot.
> x <- rnorm(100, 10, 10)
> e <- rnorm(100, 0, 5)
> y <- 5 + 10 *x + e
> myReg1 <- lm (y~x)
> plot(x,y)
> newX <- seq(1,10,1)
> myPred <- predict(myReg1,data.frame(x=newX))
> Now, if I do this, I get 2 graphs "overlaid" but their axes do not "line 
> up".
> par(new=T)
> plot(newX,myPred$fit)
> The problem is that the second one uses the "whole width" of the graph 
> space, when I'd rather just have it go from the small subset where its x 
> is defined, from 1 to 10.  Its stretching the range (1,10) for newX to 
> use the same scale that goes from (-15, 35) where it plots x
> I know abline() can do this for lm, but for some other kinds of models, 
> no  lines() method is provided, and so I am doing this the old fashioned 
> way.


Instead of using plot() for the second set of points, use points():

x <- rnorm(100, 10, 10)
e <- rnorm(100, 0, 5)
y <- 5 + 10 * x + e

myReg1 <- lm (y ~ x)
plot(x, y)

newX <- seq(1, 10, 1)
myPred <- predict(myReg1, data.frame(x = newX))

points(newX, myPred$fit, pch = 19)

This will preserve the axis scaling. If you use plot() without
explicitly indicating xlim and ylim, it will automatically scale the
axes based upon your new data, even if you indicated that the underlying
plot should not be cleared.

Alternatively, you could also use the lines() function, which will draw
point to point lines:

lines(newX, myPred$fit, col = "red")

If you want fitted lines and prediction/confidence intervals, you could
use a function like matlines(), presuming that a predict method exists
for the model type you want to use.

There is an example of using this in "R Help Desk" in R News Vol 3
Number 2 (October 2003), in the first example, with a standard linear
regression model.


Marc Schwartz

More information about the R-help mailing list