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 aes
here:
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'))