在与ggplot背景图像绘图数据(Plot data over background image w

2019-09-02 02:56发布

我想在一个背景图像绘制的一些数据。 的问题是,两个层最终使用相同的刻度。 这是不幸的是有问题的。

一个例子。

我想在这个绘制一些数据图像 。

对。 所以我绘制它在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()

绘制样本数据,我得到这个 。

所以,我只是想在分层梯度图像这个数据曲线。

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

但它最终像这样

试图指定第二填充缩放抛出一个错误。 我看到这个人说不能做,但我希望有一个解决办法或东西我俯瞰。

Answer 1:

尝试此,(或备选地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)) 



文章来源: Plot data over background image with ggplot
标签: r ggplot2