Domanda

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

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top