[R] Interaction scatterplots in ggplot with multiple regression lines
John Kane
jrkrideau at inbox.com
Wed Sep 26 17:03:10 CEST 2012
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
> -----Original Message-----
> From: dadrivr at gmail.com
> Sent: Wed, 26 Sep 2012 09:45:07 -0400
> To: r-help at r-project.org
> Subject: [R] Interaction scatterplots in ggplot with multiple regression
> lines
>
> 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!
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
____________________________________________________________
FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!
More information about the R-help
mailing list