ggplot2:从包含geom_histogram的绘图对象中读取最大条形高度

Dav*_*aze 7 r histogram ggplot2

像这张上一张海报一样,我也用它geom_text来注释gglot2中的情节.我想将这些注释放在相对坐标(面H&W的比例)而不是数据坐标中.对于大多数情节来说足够容易,但在我的情况下,我正在处理直方图.我确定关于y比例的相关信息必须潜伏在某个地方(添加后geom_histogram)的情节对象中,但我看不到哪里.

我的问题:如何从包含geom_histogram?的刻面ggplot2对象中读取最大条形高度?有人可以帮忙吗?

koh*_*ske 5

试试这个:

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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述