geom_smooth for more than two variables

Viewed 206

I want to create a colored scatter plot and display a (multiple) linear regression. At the moment my code looks like this (using the cars data-set as an example)

my.formula <- y ~ x 
ggplot(mtcars, aes(x=mpg, y=cyl, color=(disp))) + 
  geom_point() + 
  geom_smooth(method=lm, se=FALSE) +
  ggpmisc::stat_poly_eq(formula = my.formula,
                        aes(label = paste(..rr.label.., sep = "~~~")),
                        parse = TRUE) +
  scale_colour_gradientn(colours=RColorBrewer::brewer.pal(9,"YlOrRd")) +
  theme_bw()

enter image description here

However, I would like to include also the information from the second (coloured) information of the scatter plot in the regression model. Does anybody have a suggestion on how to achieve this?

The idea would be to use a formula like: my.formula <- y ~ x1 + x2 where x1 is mpg and x2 is disp. and to create e.g. a plot with the regression and the corresponding data if possible in 2D (also subplots would be possible to see all information)

1 Answers

You can manually create the plot using stat_function and the fit from your model, well described in this ggiraphExtra vignette. However, that package has a nice wrapper that can do exactly this.

library(ggiraphExtra)

mdl <- lm(data = mtcars, cyl ~ mpg + disp)
ggPredict(mdl)

enter image description here

Related