How to specify different colors using ggplot

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(size=4)

Suppose you have the above scatterplot. How can you indicate that >= 25mpg points will be displayed red, one between 20 and 25 greenand 0-20 blue?

Can this be done with ggplot?

+6
source share
2 answers

You do this in two steps:

First, you define groups that should have different colors; either by adding another column to the data frame, or inside aes. I use aeshere:

aes(wt, mpg, color = cut(mpg, breaks = c(0, 20, 25, Inf)))

Secondly, specifying a manual color or fill scale:

scale_color_manual(values = c('blue', 'green', 'red'),
                   limits = c('(0,20]', '(20,25]', '(25,Inf]'))

, (values) (limits); , cut.

:

ggplot(mtcars) +
    aes(wt, mpg, color = cut(mpg, breaks = c(0, 20, 25, Inf))) +
    geom_point(size = 4) +
    scale_color_manual(values = c('blue', 'green', 'red'),
                       limits = c('(0,20]', '(20,25]', '(25,Inf]'))

, guides:

guides(color = guide_legend(title = 'mpg range'))
+6

, , ggplot(). ifelse() :

library(ggplot2)

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(size = 4, 
               aes(color = ifelse(mpg > 25, "> 25", 
                                  ifelse(mpg > 20, "20-25", "< 20")))) +
  scale_color_manual(values = c("> 25" = "red", "< 20" = "blue", "20-25" = "green"),
                     name = "MPG"  )

guides() , name =.. scale_color_manual()

+2

Source: https://habr.com/ru/post/1014799/


All Articles