0

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?

user11243039
  • 1
  • 1
  • 2
  • 2
    It is always easier to answer questions when you provide sample data and in this case example plots. But if I understood correctly you want the plot from your last code block, but without the point in the legend? I see two solutions: Either move the color argument out of the `aes()` call, but still within the same `geom_point()` or add `show.legend = NA` to the second `geom_point()` call to remove the legend entry for the mean points. – Mojoesque Mar 22 '19 at 15:22
  • 1
    Possible duplicate of [r - ggplot2 - highlighting selected points and strange behavior](https://stackoverflow.com/questions/11467965/r-ggplot2-highlighting-selected-points-and-strange-behavior) – divibisan Mar 22 '19 at 15:49
  • yes indeed. It's not the solution, but I can continue. Thanks @divibisan – user11243039 Mar 25 '19 at 11:21
  • @Mojoesque, thanks. I'll learn how to put data and example plots to question. – user11243039 Mar 25 '19 at 11:22

1 Answers1

1

You're missing two key points about how ggplot manages aesthetics:

  1. 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.

  2. 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")
divibisan
  • 11,659
  • 11
  • 40
  • 58