9

I'd like to build on this example of conditioning line color on slope to add a line for the mean (line from mean t=1 to mean t=2).

library(dplyr)
set.seed(205)
dat = data.frame(t=rep(1:2, each=10), 
                 pairs=rep(1:10,2), 
                 value=rnorm(20))

ggplot(dat %>% group_by(pairs) %>%
         mutate(slope = (value[t==2] - value[t==1])/(2-1)),
       aes(t, value, group=pairs, colour=slope > 0)) +
  geom_point() +
  geom_line()

I tried adding stat_summary(fun.y=mean, geom="line") without any luck.

Computation failed in stat_summary(): 'what' must be a function or character string

Community
  • 1
  • 1
Eric Green
  • 7,385
  • 11
  • 56
  • 102

1 Answers1

13

I didn't get the error you describe (with ggplot2 v 2.2.0), but in order to get the desired result I did have to override the grouping you specified in the main plot:

stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thanks, @benbolker. I upgraded to 2.2 and restarted R, but it would not produce the correct plot until I closed my RStudio project. Some localized issue on the warning I guess. – Eric Green Nov 30 '16 at 03:46