Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

r - Plot data over background image with ggplot

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.

sample 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. enter image description here

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

enter image description here

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

screenshot


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...