3
$\begingroup$

I want to plot the results of a regression model, but allowing two variable to vary simultaneously. I guess I could do that using predict() function in R, but I am running a model that does not have such function developed yet.

Let's suppose we have a data set

x1 <- rnorm(100)
x2 <- rnorm(100)
y <- 1 + x1*5 + x2*3 + rnorm(100)

And we run a simple model and calculate yhat.

mod <- lm(y ~ x1 + x2)
yhat <- predict(mod)
dt <- as.data.frame(cbind(yhat,x1,x2))

How can I plot the expected value of y for different values of x1 and x2? I tried this, but it didn't work:

contour(dt$x1, dt$x2, dt$yhat)

Error in contour.default(dt$x1, dt$x2, dt$yhat) : 
  increasing 'x' and 'y' values expected
$\endgroup$
1
  • $\begingroup$ What's your purpose behind plotting? If it is to see how well the model fits wouldn't plotting residuals make more sense? $\endgroup$ Commented Mar 31, 2013 at 4:50

1 Answer 1

4
$\begingroup$

To use a plot like contour() your vertical z axis is going to be a matrix so x and y need to be the points defining a grid over which to draw z. So you want something more like:

# Changed data and model from yours to make it easier to check the axes are the right way 
# around later on:

x1 <- rnorm(100)
x2 <- rnorm(100,5,1)

y <- 1 + x1*5 + x2*(-3) + rnorm(100) 

mod <- lm(y ~ x1 + x2)

gridded <- data.frame(
    x1=seq(from=min(x1), to=max(x1), length.out=100),
    x2=seq(from=min(x2), to=max(x2), length.out=100))

yhat <- predict(mod, newdata=expand.grid(gridded))

image(gridded$x1, gridded$x2, matrix(yhat,nrow=100, byrow=FALSE))
contour(gridded$x1, gridded$x2, matrix(yhat,nrow=100, byrow=FALSE), add=TRUE)

enter image description here

$\endgroup$
1
  • $\begingroup$ There's probably a better way of doing this, someone who does it all the time will point it out I hope. $\endgroup$ Commented Mar 31, 2013 at 3:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.