获取刻度/刻面范围(刻度='空闲') [英] get scales/range of facets (scales='free')
问题描述
我有一个刻有自由标度的ggplot。现在我想在每个方面的相同位置注释这个图。如果我知道如何获得每个方面的范围/范围,这很容易做到。问题:是否有任何方法可以获得ggplot中每个方面的尺度?
I have a faceted ggplot with free scales. Now I want to annotate this plot at the same RELATIVE Position at each facet. This would be easy to do, if I knew how to get the range/limits of the scale of each facet. QUESTION: Is there any way to get the scales of each facet in ggplot?
在下面的例子中,我手动完成了它。问题在于如何通过使用 a2
(也可能更准确)的函数来构造 facet_scales
。如果我调用 str(a2)
,它给了我一个 a2 $ scales
的解释。它还指出一个有用的函数可以是 get_scales()
。可悲的是,我不知道如何调用这个函数。
In the following example, I did it manually. The question would be how to construct facet_scales
by a function which uses a2
(which would also be more exact). If i call str(a2)
, it gives me an explanation of a2$scales
. It also states that a useful function could be get_scales()
. Lamentably, i don't know how to call this function.
library(ggplot2)
a <- ggplot(data = msleep, aes(x = bodywt, y = sleep_total))+ geom_point()
a2 <- a + facet_wrap(~vore, scales="free")
a2
facet_scales = data.frame(vore=c(levels(msleep$vore), NA),
x_min = c(0,0,0,0,0),
x_max = c(800,7000,60,90,4),
y_min = c(0,0,5,7.5,5),
y_max = c(20,18,21,19,15)
)
a2 + geom_rect(data=facet_scales, mapping =aes(xmin=x_min, xmax=x_max, ymin=y_min,
ymax=(y_max+y_min)/3, x=NULL, y=NULL ), color='yellow', alpha=0.2)
推荐答案
用函数 ggplot_build()
转换a2。然后,轴范围存储在列表元素面板
子列表范围
中,然后对于每个面板x轴范围在元素 x.range
You can get the range of each facet axis by converting a2 with function ggplot_build()
. Then axis ranges are stored in list element panel
sublist ranges
, and then for each panel x axis range is in element x.range
a3<-ggplot_build(a2)
a3$panel$ranges[[1]]$x.range
[1] -39.9706 839.9986
a3$panel$ranges[[2]]$x.range
[1] -332.6769 6986.6989
这篇关于获取刻度/刻面范围(刻度='空闲')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!