开发者

How to plot with a png as background? [duplicate]

This question already has answers here: Overlay data onto background image 开发者_JS百科 (3 answers) Closed 5 years ago.

I made a plot with a 3 million points and saved it as PNG. It took a few hours and I would like to avoid re-drawing all the points.

How to plot with a png as background? [duplicate]

How can I generate a new plot that has this PNG as a background?


Try this:

library(png)

#Replace the directory and file information with your info
ima <- readPNG("C:\\Documents and Settings\\Bill\\Data\\R\\Data\\Images\\sun.png")

#Set up the plot area
plot(1:2, type='n', main="Plotting Over an Image", xlab="x", ylab="y")

#Get the plot information so the image will fill the plot box, and draw it
lim <- par()
rasterImage(ima, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
grid()
lines(c(1, 1.2, 1.4, 1.6, 1.8, 2.0), c(1, 1.3, 1.7, 1.6, 1.7, 1.0), type="b", lwd=5, col="white")

Below is the plot.

How to plot with a png as background? [duplicate]


While @bill_080's answer directly answers your question, is this really what you want? If you want to plot onto this, you'll have to carefully align your coordinate systems. See e.g. Houston Crime Map how this can be done with ggplot2.

For your problem, it seems to me that there may be an easier solution: binning, i.e. ceating 2d histograms.

> df <- data.frame (x = rnorm (1e6), y = rnorm (1e6))
> system.time (plot (df))
       User      System verstrichen 
     54.468       0.044      54.658 
> library (hexbin)
> system.time (binned <- hexbin (df, xbins=200))
       User      System verstrichen 
      0.252       0.012       0.266 
> system.time (plot (binned))
       User      System verstrichen 
      0.704       0.040       0.784

How to plot with a png as background? [duplicate]

hexbin works directly with lattice and ggplot2, but the center coordinates of the bins are in binned@xcm and binned@ycm, so you could also plot the result in base graphics. With high number of bins, you get a fast version of your original plot:

> system.time (plot (binned@xcm, binned@ycm, pch = 20, cex=0.4))
       User      System verstrichen 
      0.780       0.004       0.786 

How to plot with a png as background? [duplicate]

but you can easily have the colours coding the density:

> plot (binned@xcm, binned@ycm, pch = 20, cex=0.4, col = as.character (col))

> col <- cut (binned@count, 20)
> levels (col) <- grey.colors (20, start=0.9, end = 0)
> plot (binned@xcm, binned@ycm, pch = 20, cex=0.4, col = as.character (col))

How to plot with a png as background? [duplicate]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜