如何使用 R 和 ggplot2 使 annotation_custom() grob 与 scale_y_reverse() 一起显示?

jto*_*lle 6 r ggplot2

我是 R 的新手,ggplot2而且相对较新。我可以在绘图上显示图片,并且可以使 y 轴反向缩放,但我不知道如何同时进行。例如:

library(ggplot2)

y=c(1,2,3)
x=c(0,0,0)
d=data.frame(x=x, y=y)

#following http://stackoverflow.com/questions/9917049/inserting-an-image-to-ggplot2/9917684#9917684
library(png)
library(grid)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img, interpolate=TRUE)

#these work fine - either reversing scale, or adding custom annotation
ggplot(d, aes(x, y)) + geom_point()
ggplot(d, aes(x, y)) + geom_point() + scale_y_reverse()
ggplot(d, aes(x, y)) + geom_point() + annotation_custom(g, xmin=.23, xmax=.27, ymin=1.8, ymax=2.2)

#these don't...combining both reverse scale and custom annotation
ggplot(d, aes(x, y)) + geom_point() + annotation_custom(g, xmin=.23, xmax=.27, ymin=1.8, ymax=2.2) + scale_y_reverse()
ggplot(d, aes(x, y)) + geom_point() + annotation_custom(g, xmin=.23, xmax=.27, ymin=2.2, ymax=1.8) + scale_y_reverse()
Run Code Online (Sandbox Code Playgroud)

我确定我错过了一些非常基本的东西。我应该从哪里开始寻找让我的小图形显示在反向比例图上,并更好地理解引擎盖下的事情?

对评论的澄清:上面的例子是我试图简化我遇到的问题。我不知道这是否重要,但我不仅仅是试图在静态图像上叠加一些数据。我实际上想根据绘图中的数据将图像放置在绘图的某个位置。但是,当轴刻度反转时,我似乎无法做到这一点。而且,事实证明,当比例反转时,我什至无法将图像放在绝对位置,所以这就是我发布的代码示例。

San*_*att 7

使用scale_y_reverse,您需要将里面的 y 坐标设置为annotation_custom负数。

library(ggplot2)
y=c(1,2,3)
x=c(0,0,0)
d=data.frame(x=x, y=y)


library(png)
library(grid)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img, interpolate=TRUE)

ggplot(d, aes(x, y)) + geom_point() + 
   annotation_custom(g, xmin=.20, xmax=.30, ymin=-2.2, ymax=-1.7) + 
   scale_y_reverse()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

为什么是负面的?y 坐标是原始坐标的负数。看看这个:

(p = ggplot(d, aes(x=x, y=y)) + geom_point() + scale_y_reverse())
y.axis.limits = ggplot_build(p)$layout$panel_params[[1]][["y.range"]]
y.axis.limits
Run Code Online (Sandbox Code Playgroud)

或者,以相对单位设置 grob 的坐标和大小rasterGrob

g <- rasterGrob(img, x = .75, y = .5, height = .1, width = .2, interpolate=TRUE)

ggplot(d, aes(x, y)) + geom_point() + 
   annotation_custom(g) +
   scale_y_reverse() 
Run Code Online (Sandbox Code Playgroud)