2013-05-07 71 views
12

我試圖在背景圖上繪製一些數據。問題在於兩個圖層最終都使用相同的比例。這是不幸的問題。使用ggplot在背景圖上繪製數據

一個例子。

我想繪製一些數據在這image

sample image

權。所以我把它繪製成ggplot就像這樣。

img <- readJPEG("image.jpg") 
image <- apply(img, 1:2, function(v) rgb(v[1], v[2], v[3])) 
image <- melt(image) 
ggplot(image, aes(row, -column, fill=fill)) + geom_tile() + scale_fill_identity() 

它運作良好。所以,讓我們在頂部添加一些數據。

df <- data.frame(x=sample(1:64, 1000, replace=T), 
    y=sample(1:64, 1000, replace=T)) 
ggplot(df, aes(x,y)) + stat_bin2d() 

繪製樣本數據,我得到thisenter image description here

所以我只是希望這個數據情節分層在漸變圖像上。

ggplot(image, aes(row, -column, fill=fill)) + geom_tile() + 
    scale_fill_identity() + geom_point(data=df2, aes(x=x, y=-y)) 

但它最終像this

enter image description here

試圖指定第二填充縮放拋出一個錯誤。我看到this說它不能完成,但我希望有一個解決方法或我忽略的東西。

+0

[這](http://kohske.wordpress.com/2010/12/26/use-image-for-background -gGplot2 /)post是舊的,需要對ggplot的新版本進行一些更新,但它至少可以提供一條出路。 – joran 2013-05-07 03:33:51

回答

17

嘗試此,(或備選地annotation_raster)

library(ggplot2) 
library(jpeg) 
library(grid) 

img <- readJPEG("image.jpg") 

df <- data.frame(x=sample(1:64, 1000, replace=T), 
       y=sample(1:64, 1000, replace=T)) 

ggplot(df, aes(x,y)) + 
    annotation_custom(rasterGrob(img, width=unit(1,"npc"), height=unit(1,"npc")), 
        -Inf, Inf, -Inf, Inf) + 
    stat_bin2d() + 
    scale_x_continuous(expand=c(0,0)) + 
    scale_y_continuous(expand=c(0,0)) 

screenshot

+0

請注意,這不適用於'coord_polar',但可以在這個問題找到解決方案http://stackoverflow.com/questions/34496000/trying-to-add-an-image-toa-a-極積給出了錯誤的註釋,定製只工作。 – Deleet 2016-08-16 00:18:49