Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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()
like image 534
Julio Diaz Avatar asked Mar 09 '11 06:03

Julio Diaz


People also ask

Which function is used to add labels to the graph in the ggplot() function?

Method 1: Using geom_text() This method is used to add Text labels to data points in ggplot2 plots.

How do you add labels to a graph in R?

Use the title( ) function to add labels to a plot. Many other graphical parameters (such as text size, font, rotation, and color) can also be specified in the title( ) function. # labels 25% smaller than the default and green.

Which arguments can be used to add labels in Ggplot?

To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .


1 Answers

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))
like image 92
kohske Avatar answered Oct 12 '22 05:10

kohske