[R] Interaction scatterplots in ggplot with multiple regression lines

Isaac Petersen dadrivr at gmail.com
Wed Sep 26 15:45:07 CEST 2012


I'm trying to treat a continuous variable as discrete for plotting
multiple regression lines in a scatterplot as a function of the level
on the moderating variable.  In the example below, there is only one
regression line plotted to the whole data.  I would like a separate
regression line for each discrete level of the moderator.  The
moderator is continuous, so I'd like to treat it as discrete for
plotting the regression lines.

Here's an example (I would like 7 regression lines corresponding to
the discrete levels of the moderator, as displayed in the legend,
instead of just 1 regression line):

###########################
library(ggplot2)
set.seed(1234)
predictor <- rnorm(1000, 3)
outcome <- rnorm(1000, 10)
moderator <- rnorm(1000)
mydata <- data.frame(predictor, outcome, moderator)

ggplot(mydata, aes(x=predictor, y=outcome, color=moderator)) +
geom_point() + scale_colour_gradient2(low="blue", high="red") +
stat_smooth(method=lm, se=TRUE, fullrange=T)
###########################

Also, how can I set how many discrete levels to plot (e.g., 3 instead of 7)?

Thanks in advance!



More information about the R-help mailing list