ggplot geom_point()使用基于特定离散值的颜色 [英] ggplot geom_point() with colors based on specific, discrete values
问题描述
我试图用三种不同颜色绘制三个数值范围的数据点。例如:
library(ggplot2)
ggplot(mtcars,aes(wt,mpg))+ geom_point(aes (color = 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(black,yellow,red))
错误:手动缩放值不足,需要30个,但只提供了4个
我是猜测我会以某种方式使用
cut()
或factor()
,但我似乎无法弄清楚。任何建议?解决方案您需要将
cut
:
library(ggplot2)
ggplot(mtcars,aes(wt,mpg))+
geom_point (aes(color = cut(qsec,c(-Inf,17,19,Inf))),
size = 5)+
scale_color_manual(name =qsec,
values = c(( - Inf,17)=bl ack,
(17,19)=黄色,
(19,Inf)=红色),
labels = 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_gradientn(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.
The solutions given in ggplot2 heatmap with colors for ranged values seem promising but I can't get them to work with
geom_point()
.Same goes for various similar posts such as those listed in the sidebar.
I realize I will probably need to use some kind of discrete scale instead of
scale_fill_gradientn
but my attempts to usescale_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()
orfactor()
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屋!
查看全文