Reputation: 1
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)
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
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?
Upvotes: 0
Views: 8157
Reputation: 12165
You're missing two key points about how ggplot
manages aesthetics:
Each geom_*
layer will inherit the aes
settings from the parent ggplot
call, unless you manually override it. So in you first example, the 3rd geom_point
inherits the x
and y
values from ggplot
, not the "mean" layer above it, and thus renders a red point on top of each colored point.
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).
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")
Upvotes: 1