ggplot2: Reading maximum bar height from plot object containing geom_histogram

强颜欢笑 提交于 2020-01-02 03:29:08

问题


Like this previous poster, I am also using geom_text to annotate plots in gglot2. And I want to position those annotations in relative coordinates (proportion of facet H & W) rather than data coordinates. Easy enough for most plots, but in my case I'm dealing with histograms. I'm sure the relevant information as to the y scale must be lurking in the plot object somewhere (after adding geom_histogram), but I don't see where.

My question: How do I read maximum bar height from a faceted ggplot2 object containing geom_histogram? Can anyone help?


回答1:


Try this:

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



来源:https://stackoverflow.com/questions/12828125/ggplot2-reading-maximum-bar-height-from-plot-object-containing-geom-histogram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!