1
votes

In ggplot, I want to compute the means (per group) and plot them as points. I would like to do that with geom_point(), and not stat_summary(). Here are my data.

group = rep(c('a', 'b'), each = 3)
grade = 1:6
df = data.frame(group, grade)
# this does the job
ggplot(df, aes(group, grade)) + 
  stat_summary(fun.y = 'mean', geom = 'point')
# but this does not
ggplot(df, aes(group, grade)) + 
  geom_point(stat = 'mean')

What value can take the stat argument above? Is it possible to compute the means, using geom_point(), without computing a new data frame?

1

1 Answers

4
votes

You could do

ggplot(df, aes(group, grade)) + 
  geom_point(stat = 'summary', fun.y="mean")

But in general its really not a great idea to rely on ggplot to do your data manipulation for you. Just let ggplot take of the plotting. You can use packages like dplyr to help with the summarizing

df %>% group_by(group) %>% 
  summarize(grade=mean(grade)) %>% 
  ggplot(aes(group, grade)) + 
    geom_point()