使用 ggplot 在背景图像上绘制数据 [英] Plot data over background image with ggplot

查看:19
本文介绍了使用 ggplot 在背景图像上绘制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

一个例子.

我想在这个.

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

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

但结果是 说它无法完成,但是我希望有一种解决方法或我忽略的东西.

解决方案

试试这个,(或者 annotation_raster)

库(ggplot2)图书馆(jpeg)图书馆(网格)img <- readJPEG("image.jpg")df <- data.frame(x=sample(1:64, 1000, replace=T),y=样本(1:64, 1000, 替换=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))

I'm trying to plot some data over a background image. The problem is that both layers end up using the same scale. This is unfortunately problematic.

An example.

I want to plot some data over this image.

Right. So I plot it in ggplot like so.

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()

And it works well. So, let's add some data on top.

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

Plotting the sample data, I get this.

So I just want this data plot layered over the gradient image.

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

But it ends up like this

Trying to specify a second fill scale throws an error. I see this says it can't be done, but I'm hoping that there is a workaround or something I'm overlooking.

解决方案

Try this, (or alternatively 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)) 

这篇关于使用 ggplot 在背景图像上绘制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆