2013-05-07 75 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