Place an image into an R plot

There a basically two options on how to place arbitrary images as a point symbol into a plot in R. If you want to use a raster images such as GIF, JPG or BMP, opt for the “pixmap” package.  You will have to convert your image into the PPM format and then use the “add_logo” function of the package. An example usage is given here or here. However, the result will often not render nicely.

An alternative is to import vector graphics such as SVG or PS using the “grImport” package (Vignette). Suppose you have a postscript graphics named “candle.ps” (if you have an SVG graphics, then use e.g. Inkscape to convert SVG to PS), the following gives the desired plot:

## Read postscript
library(grImport)
PostScriptTrace("candle.ps")
ca = readPicture("candle.ps.xml")

## Set up some points and set background color
library(lattice)
library(grid)
N = 22; x = seq(9,N*10,9); y = rnorm(N, 40, 30)
trellis.par.set("background", list(col = "#380000"))

## Plot with lattice function
xyplot(y~x , xlim=c(0, 9*N + 5), ylim=c(20,100),
panel = function(x, y, ...) {
grid.symbols(ca, x, y, units = "native", size = unit(13, "mm"))})

The result could look like this:

Candle Plot

Please note two things. First, postscript does not support transparency. It might be necessary that you replace transparent colors with solid colors using Inkscape, for example. Furthermore, grImport does not paint on the default “base” graphics system (functions like plot, hist), but only on the “grid” graphics system. Therefore we use “lattice” to produce graphics, as the package utilizes grid graphics. These slides from package creator Paul Murell are an helpful further reading.

Comments are closed.