Rtist
Rtist

Reputation: 4205

Plotting the means in ggplot, without using stat_summary()

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?

Upvotes: 2

Views: 727

Answers (1)

MrFlick
MrFlick

Reputation: 206177

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()

Upvotes: 4

Related Questions