2015-11-21 53 views
3

我是ggplot2的新手,对R来说比较新。我可以让一张照片出现在一张图上,我可以使y轴反转缩放,但我不知道如何同时做两个。例如:如何使用R和ggplot2将annotation_custom()grob与scale_y_reverse()一起显示?

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

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

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

+0

当我看到一个似乎已经被请求的问题时,我从问题标题中找出关键词并做一些SO搜索。 –

+0

@ 42,我也是如此。特别是有什么特别的,我可能错过了而没有意识到它包含我的答案? – jtolle

+0

有很多问题和答案显示在png图像上叠加数据的能力:http://stackoverflow.com/questions/30152309/how-to-overlay-and-position-a-logo-over-any-r -plot-igraph-ggplot2-etc-so-ic –

回答

3

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

enter image description here

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

(p = ggplot(d, aes(x=x, y=y)) + geom_point() + scale_y_reverse()) 
y.axis.limits = ggplot_build(p)$layout$panel_ranges[[1]][["y.range"]] 
y.axis.limits 

OR,设置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() 
+1

谢谢!我的负面坐标没有亮起。关于相对单位的额外信息也非常有帮助。 – jtolle

相关问题