使用ggplot在背景图像上绘制数据

rob*_*bie 13 r ggplot2

我正试图在背景图像上绘制一些数据.问题是两个层最终都使用相同的比例.不幸的是,这是有问题的.

一个例子.

我想在这张图片上绘制一些数据.

样本图像

对.所以我在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()
Run Code Online (Sandbox Code Playgroud)

它运作良好.所以,让我们在顶部添加一些数据.

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

绘制样本数据,我得到了这个. 在此输入图像描述

所以我只想在渐变图像上分层这个数据图.

ggplot(image, aes(row, -column, fill=fill)) + geom_tile() + 
  scale_fill_identity() + geom_point(data=df2, aes(x=x, y=-y))
Run Code Online (Sandbox Code Playgroud)

但它最终会像这样

在此输入图像描述

尝试指定第二个填充比例会引发错误.我看到说不能做,但我希望有一个解决方法或我忽略的东西.

bap*_*ste 20

试试这个,(或者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)) 
Run Code Online (Sandbox Code Playgroud)

截图