Skip to content

Interaction scatterplots in ggplot with multiple regression lines

2 messages · Petersen, Isaac T, John Kane

#
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!
#
Some like this help?

mydata$modnew  <-  cut(mydata$moderator, 7)
ggplot(mydata, aes(x=predictor, y=outcome, color=modnew)) +
geom_point() + stat_smooth(method=lm, se=TRUE, fullrange=T)


John Kane
Kingston ON Canada
____________________________________________________________
FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!