Search code examples
rggplot2colorsregressionscatter-plot

r plot regression line and scatterplot with different colors


These are the goals

Using the mtcars dataset head(mtcars)

  1. plot a simple scatterplot & regression lines on the scatterplot.

    x axis = wt , y axis = mpg

  2. Color the scatter plots based on values in column vs, vs=0 dots grey, vs=1 dots = red.

  3. Regression lines by group = gear (3 regression lines)

  4. Color the regression lines based on values in column am, am=0 regression line = blue, am=1 regression line = green.

My attempt so far .

Any suggestions on how to accomplish this is much appreciated. Thanks.

head(mtcars)

  mtcars %>%
  ggplot(aes(x=wt , y = mpg))+
  geom_point(size=1, aes(color=vs)) +
  geom_smooth(method=lm, se=FALSE, aes(group=gear))

Solution

  • You can add two different scales to the same ggplot object using the {ggnewscale} package. If you want categories for colours rather than a continuous colour gradient, you should also convert columns to factors/characters rather than numeric (either before or within making the plot).

    Example:

    mtcars %>%
      ggplot(aes(x=wt , y = mpg))+
      geom_point(size=1, aes(color=factor(vs))) +
      scale_colour_manual(values = c("0" = "grey", "1" = "red")) +
      ggnewscale::new_scale_color() +
      geom_smooth(mapping = aes(colour=factor(am)),
                  method=lm, se=FALSE) +
      scale_colour_manual(values = c("0" = "blue", "1" = "green"))
    

    enter image description here