1

I try to mark my graphs with the average specific of each graph :

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 = NULL, x = 0.6, y = 0, label = mean(carat), size=5) +
   coord_flip()

For example, here I would like the graph of "Fair" is displayed average of "Fair", that of "Good" is displayed average of "Good", etc.

Also, but this is an extra, I would like to be positioned with respect to x if the average is 1.0, while the average is displayed at x = 1.0

1 Answer 1

1

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

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Warning in install.packages : package ‘dplyr’ is not available (for R version 2.15.1) and I can't change the version of R studio (online server service)
Try ddply from the plyr package: library(plyr); diamonds2 = transform(ddply(diamonds, .(cut), summarise, label = mean(carat)), Label = sprintf("%.02f", label)) Otherwise look at ?aggregate or ?by. 2.15.1 - That's nearly 2 years old.
I have follow your recommandation but if I build this graph, it possible to see a difference in a mean in geom_text et in a mean in geom_boxplot that I don't know how to explain it... snag.gy/xtbSs.jpg
The bar inside the box of the boxplot is the median.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.