3

I have a plot in which I am displaying individual values from multiple subjects, coloured by group. Added to that are means per group, calculated using stat_summary.

I would like the two means to be coloured by group, but in colours other than the individual data. This turns out to be difficult, at least when using stat_summary. I have the following code:

ggplot(data=dat, 
       aes(x=Round, y=DV, group=Subject, colour=T1)) + 
  geom_line() + geom_point() + theme_bw() +
  stat_summary(fun.y=mean, geom="line", size=1.5,
               linetype="dotted", color="black",
               aes(group=T1))

Which produces this example graph.

The colour for the means created by stat_summary is set to black; otherwise it would be red and blue like the individual data lines. However, it is not possible to set more than one colour - so color=c("black", "blue") does not work.

I've already tried scale_colour_manual as explained here, but this will change the colours of the individual data lines, leaving the mean lines unaffected.

Any suggestion how to solve this? Code and data here.

simoncolumbus
  • 526
  • 1
  • 8
  • 23

1 Answers1

6

You need to create different values for the mapping to color:

ggplot(data=iris, 
       aes(x=Sepal.Length, y=Sepal.Width, color=Species)) + 
  geom_line() + geom_point() + theme_bw() +
  stat_summary(fun.y=mean, geom="line", size=1.5,
               linetype="dotted", aes(color=paste("mean", Species)))

resulting plot

You can then use scale_color_manual to get specific colors.

Roland
  • 127,288
  • 10
  • 191
  • 288
  • Thanks! That's brilliant. For the record (because that took me another moment to figure out), the grouping needs to remain intact, so the aes is aes(color=paste("mean", Role), group=Role). – simoncolumbus Oct 29 '14 at 18:42
  • Can you explain the logic behind `aes(color=paste("mean", Role), group=Role)` why is there a need to include `"mean"`? – Tyler Ruddenfort Mar 26 '22 at 07:46
  • 1
    @TylerRuddenfort To have different colors for the means and to have the means appear separately in the legend. – Roland Mar 28 '22 at 06:24