Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

r - How to specify different colors with ggplot

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

Suppose you have the above scatterplot. How can you specify that the points that are >= 25 mpg will be plotted red, the one between 20 and 25 green and the 0-20 blue?

Can this be done with ggplot specifically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...