【问题标题】:Plot data over background image with ggplot使用 ggplot 在背景图像上绘制数据
【发布时间】:2013-04-30 20:51:16
【问题描述】:

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

一个例子。

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

所以我只希望这个数据图在渐变图像上分层。

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

但它最终像this

尝试指定第二个填充比例会引发错误。我看到this 说它无法完成,但我希望有一种解决方法或我忽略的东西。

【问题讨论】:

  • This 帖子已经过时,需要更新 ggplot 的较新版本,但它至少可能提出了一条出路。

标签: r ggplot2


【解决方案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)) 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-04-10
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多