ggplot geom_point() 具有基于特定离散值的颜色 [英] ggplot geom_point() with colors based on specific, discrete values

查看:35
本文介绍了ggplot geom_point() 具有基于特定离散值的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为三个值范围绘制具有三种不同颜色的数据点.例如:

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

以上产生:

现在,我想修改它,使 qseq 值 <17 为黑色,17 到 19 之间的值为黄色,19 以上的值为红色.我尝试了各种方法,但它们似乎都不起作用:

  • 取自中给出的解决方案似乎很有希望,但我无法得到它们使用 geom_point().

  • 同样适用于各种类似的帖子,例如边栏中列出的帖子.

我意识到我可能需要使用某种离散比例而不是 scale_fill_gradientn 但我尝试使用 scale_color_manual() 失败:

ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(color = factor(qsec))) +scale_color_manual(values=c(黑色",黄色",红色")错误:手动刻度值不足.需要30个,但只提供了4个.

我猜我将不得不以某种方式使用 cut()factor() 但我似乎无法弄清楚如何使用.有什么建议吗?

解决方案

你需要cut你的值到区间:

库(ggplot2)ggplot(mtcars, aes(wt, mpg)) +geom_point(aes(colour = cut(qsec, c(-Inf, 17, 19, Inf))),大小 = 5) +scale_color_manual(name = "qsec",values = c("(-Inf,17]" = "黑色","(17,19]" = "黄色","(19, Inf]" = "红色"),标签 = c("<= 17", "17 < qsec <= 19", "> 19"))

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:

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:

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?

解决方案

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

这篇关于ggplot geom_point() 具有基于特定离散值的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆