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

标签 r ggplot2

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

一个例子。

我想在这个 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()

绘制样本数据,我得到 this .
enter 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说它无法完成,但我希望有一种解决方法或我忽略的东西。

最佳答案

试试这个,(或者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

关于r - 使用 ggplot 在背景图像上绘制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16409935/

相关文章:

r - 为嵌套列表的每个叶提取名称层次结构

r - 在 R 中的 igraph 中导入边列表

r - ggplot2中没有数据时换行

r - ggplot2;如何在分类变量中绘制两个不同组的组均值线

r - 在绘图标题中混合不同的字体大小/面孔

r - 计算误差线并将其添加到 ggplot2 直方图的好方法是什么?

r - 根据列值拆分数据并创建散点图。

r - 如何在R中将Matlab时间转换为日期?

r - 动态改变ggplot2的背景颜色

r - 向量子集与列表子集