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
668 views
in Technique[技术] by (71.8m points)

r - ggplot geom_point() with colors based on specific, discrete values

I am trying to plot data points with three different colors for three value ranges. For example:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(colour = qsec))

The above produces:

enter image description here

Now, I would like to modify this so that qseq values <17 are black, values between 17 and 19 are yellow and values above 19 are red. I've tried various approaches, but none of them seems to work:

  • Taken from here

      ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(fill = qsec)) + 
      scale_fill_gradient(colours = c("black","yellow","red"), 
      breaks=c(0,17,19), labels = format(c("0","17","19")))
    

This produces:

enter image description here

So, the colorbar seems correct but the colors are not actually applied.

I realize I will probably need to use some kind of discrete scale instead of scale_fill_gradientn but my attempts to use scale_color_manual() fail:

ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(color = factor(qsec))) + 
scale_color_manual(values=c("black", "yellow","red")
Error: Insufficient values in manual scale. 30 needed but only 4 provided.

I am guessing I will somehow have to use cut() or factor() but I can't seem to figure out how. Any suggestions?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to cut your values into intervals:

library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + 
  geom_point(aes(colour = cut(qsec, c(-Inf, 17, 19, Inf))),
             size = 5) +
  scale_color_manual(name = "qsec",
                     values = c("(-Inf,17]" = "black",
                                  "(17,19]" = "yellow",
                                  "(19, Inf]" = "red"),
                     labels = c("<= 17", "17 < qsec <= 19", "> 19"))

resulting plot


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

...