Julio Diaz
Julio Diaz

Reputation: 9437

How to label graph with the mean of the values using ggplot2

I have created a geom_point graph where the y axis points are the mean of the values respective to each x-axis value. When I try to label the point with the mean, what I get is all the values.

This is what I have so far:

ggplot(test, aes(x=reorder(Type, Rating, mean), y=Rating, label=Rating)) +
       stat_summary(fun.y="mean", geom="point") +
       geom_text()

Upvotes: 9

Views: 14914

Answers (1)

kohske
kohske

Reputation: 66852

you can combine stat_summary and geom_text like this:

d <- data.frame(grp=gl(3,5, labels=letters[1:3]), v=rnorm(15))
ggplot(d, aes(grp, v)) + 
  stat_summary(fun.y=mean, geom="point") +
  stat_summary(aes(label=..y..), fun.y=mean, geom="text", size=8)

but probably it is better to aggregate beforehand and format the label:

ggplot(transform(ddply(d, .(grp), summarize, v=mean(v)), V=sprintf("%.02f", v)), 
  aes(grp, v)) +
  geom_point() + geom_text(aes(label=V))

Upvotes: 20

Related Questions