Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading