2015-11-21 42 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

相關問題