问题描述
像这样的,我也使用 geom_text
来标注gglot2中的图。我想将这些注释放在相对坐标(面H和W的比例)而不是数据坐标中。对于大多数情节来说足够简单,但在我的情况下,我正在处理直方图。我确信y规模的相关信息必须潜伏在plot对象的某处(在添加 geom_histogram
之后),但我看不到在哪里。
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.
我的问题:如何从包含 geom_histogram
的分面ggplot2对象读取最大条形高度?任何人都可以帮忙吗?
My question: How do I read maximum bar height from a faceted ggplot2 object containing geom_histogram
? Can anyone help?
推荐答案
试试这个:
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))
这篇关于ggplot2:从包含geom_histogram的绘图对象读取最大高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!