Ggplot2: Reading the maximum height of a bar from a plot object containing geom_histogram

Like this previous poster , I also use geom_text to comment on graphs in gglot2. And I want to position these annotations in relative coordinates (the proportion of the faces H and W), not the data coordinates. Easy enough for most stories, but in my case I'm dealing with histograms. I am sure that the relevant information on the y scale should be hidden in the plot object somewhere (after adding geom_histogram ), but I donโ€™t see where.

My question is: How to read the maximum height of a bar from a faceted ggplot2 object containing geom_histogram ? Can anyone help?

+7
source share
1 answer

Try the following:

 library(plyr) library(scales) p <- ggplot(mtcars, aes(mpg)) + geom_histogram(aes(y = ..density..)) + facet_wrap(~am) r <- print(p) # in data coordinate (dc <- dlply(r$data[[1]], .(PANEL), function(x) max(x$density))) (mx <- dlply(r$data[[1]], .(PANEL), function(x) x[which.max(x$density), ]$x)) # add annotation (see figure below) p + geom_text(aes(x, y, label = text), data = data.frame(x = unlist(mx), y = unlist(dc), text = LETTERS[1:2], am = 0:1), colour = "red", vjust = 0) # scale range (yr <- llply(r$panel$ranges, "[[", "y.range")) # in relative coordinates (rc <- mapply(function(d, y) rescale(d, from = y), dc, yr)) 

enter image description here

+6
source

All Articles