r ggplot geom_point更改颜色 [英] r ggplot geom_point change color
问题描述
我正在运行代码,它可以正常工作
I am running the code and it works
ggplot(data_df, aes(x= RR, y= PPW, col = year)) +
geom_point(size = 3, alpha=0.6)
现在,我试图将(x,y)的平均值放在图形上,通过添加使其具有另一种颜色
Now I am trying to put the mean value of (x,y) on graph en give it another color by adding
ggplot(data_df, aes(x= RR, y= PPW, col = year))) +
geom_point(size = 3, alpha=0.6) +
geom_point(data=data_df, aes(x=mean(RR), y=mean(PPW)) +
geom_point(color="red")
可以,但是所有点的颜色现在都是红色
It works, but the color of all points is now red
如果我将颜色放在这样的aes中,则平均点会得到另一种颜色,我也可以在图例中看到它
If I put color inside aes like these, the mean point get another color, and I see it also in legend
ggplot(data_df, aes(x= RR, y= PPW, col = year))) +
geom_point(size = 3, alpha=0.6) +
geom_point(data=data_df, aes(x=mean(RR), y=mean(PPW), color="red"))
我想手动给颜色.有可能吗?
I would like to give the color manually. Is it possible?
推荐答案
您缺少有关ggplot
如何管理美学的两个关键点:
You're missing two key points about how ggplot
manages aesthetics:
-
每个
geom_*
层都将从父ggplot
调用中继承aes
设置,除非您手动覆盖它.因此,在您的第一个示例中,第三个geom_point
继承了ggplot
的x
和y
值,而不是其上方的均值"层,因此在每个有色点的上方都呈现了一个红色点.
Each
geom_*
layer will inherit theaes
settings from the parentggplot
call, unless you manually override it. So in you first example, the 3rdgeom_point
inherits thex
andy
values fromggplot
, not the "mean" layer above it, and thus renders a red point on top of each colored point.
aes
中的值应用于刻度,不按原样使用.因此,在第二个示例中,将color = 'red'
放在aes
中时,并不是将点设为红色,而是说颜色应由类别变量确定(这里是长度1的向量,包括单词"red")基于scale_color_*
.您可以添加scale_color_manual
并设置'red' = 'red'
,以便该值呈现所需的颜色,也可以将color=
移动到aes
之外,以便按原样进行解释(并将该层中的所有点设为红色).
Values in the aes
are applied to a scale, not used as is. So when you put color = 'red'
in the aes
in your second example, you aren't making the points red, you're saying that color should be determined by a categorical variable (which here is a length 1 vector consisting of the word 'red') based on the scale_color_*
. You can either add a scale_color_manual
and set 'red' = 'red'
, so that value renders the desired color, or move the color=
outside the aes
, so it is interpreted as is (and will make all points in that layer red).
记住这些要点,做您想做的事情就像将color
移到aes
之外一样简单:
With those points in mind, doing what you want is as simple as moving the color
outside the aes
:
ggplot(data_df, aes(x= RR, y= PPW, col = year))) +
geom_point(size = 3, alpha=0.6) +
geom_point(data=data_df, aes(x=mean(RR), y=mean(PPW)), color="red")
这篇关于r ggplot geom_point更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!