There are a number of ways to get the labels (and the positions for the labels). Here, the dplyr
package is used to summarise the diamonds
data frame; that is, to obtain the required means. Also note that the labels are formatted - two decimal places. In the code below, the diamonds2 data frame contains the means and the labels, and is used in the call to geom_text
.
library(ggplot2)
library(dplyr)
diamonds2 = transform(summarise(group_by(diamonds, cut), label = mean(carat)),
Label = sprintf("%.02f", label))
ggplot(diamonds, aes(x = carat, fill=cut)) +
stat_density(aes(ymax = ..density.., ymin = -..density..),
geom = "ribbon", position = "identity") +
facet_grid(. ~ cut) +
xlim(0, 2.5) +
geom_text(data = diamonds2, aes(label = Label, x = label, y = 0), size=5) +
coord_flip()