【问题标题】:How do I get annotation_custom() grob to display along with scale_y_reverse() using R and ggplot2?如何使用 R 和 ggplot2 让 annotation_custom() grob 与 scale_y_reverse() 一起显示?
【发布时间】:2018-07-17 06:55:19
【问题描述】:

我是 ggplot2 的新手,对 R 来说相对较新。我可以让图片出现在绘图上,我可以让 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()

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

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

【问题讨论】:

  • 当我看到一个似乎已经被请求过的问题时,我会从问题标题中提取关键词并进行一些 SO 搜索。
  • @42,我也是。特别是关于 SO 的任何我可能在没有意识到的情况下错过的内容包含我的答案?
  • 关于 SO 的多个问题和答案显示了在 png 图像上覆盖数据的能力:stackoverflow.com/questions/30152309/…
  • @42,确实。事实上,这就是我最初发现如何使用annotation_custom 的方法。我不知道如何将它与scale_y_reverse 一起使用。万一这很重要,我的实际目标是根据我正在绘制的数据放置图像,但我什至不能在固定位置进行,所以我给出了这个例子,因为它是相似的。 (请参阅我的编辑。)您是否知道如何做我想做的事情,或者您是否有一个链接可以解释为什么我正在尝试做的事情不起作用?也许我只是没有在自己的搜索结果中认出答案。
  • 希望现在@Sandy 的答案会在 Google 或 SO 搜索“annotation_custom scale_y_reverse”时出现!

标签: r ggplot2


【解决方案1】:

使用scale_y_reverse,您需要将annotation_custom 内部的y 坐标设置为负值。

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

为什么是负面的? 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

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

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

【讨论】:

  • 谢谢!我没有想到负坐标。您关于相对单位的额外信息也很有帮助。
猜你喜欢
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
相关资源
最近更新 更多