How to specify different colors with ggplot

前端 未结 2 947
孤城傲影
孤城傲影 2020-12-20 18:38
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(size=4)

Suppose you have the above scatterplot. How can you speci

2条回答
  •  离开以前
    2020-12-20 19:03

    You do this in two steps:

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

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

    Secondly, by specifying a manual colour or fill scale:

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

    This specifies which colours to use (values) and which labels to assign them to (limits); these are the names of the grouping generated by cut.

    Taken together:

    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]'))
    

    You can improve the legend title by adding the grouping as a separate column to your data, or by providing a guides function call:

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

提交回复
热议问题