How to plot with a png as background?

Aleksandr Levchuk picture Aleksandr Levchuk · Mar 11, 2011 · Viewed 23.3k times · Source

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.

enter image description here

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

Answer

bill_080 picture bill_080 · Mar 11, 2011

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.

enter image description here