rlatticegrimport

How do I use a 'picture' object as a symbol in a graph key?


I'm creating a graph using xyplot() from lattice, and using the grImport package to plot a picture as a plotting symbols with grid.symbols().

This is a brief version of the code for my graph, where 'mypic' is the picture object (created with grImport) I'm using as a plotting symbol.

xyplot(y~x, data=dat,
  panel=function(x, y, ...) {
   grid.symbols(mypic, x, y, units = "native",
    size = unit(10, "mm"),
    use.gc = FALSE,
    gp = gpar(col = "white", fill = c("red","blue")))
})

I want to create a legend that shows the same plotting symbol I've used in the graph. I thought something like this would work:

key = list(...
  points = list(pch = grid.picture(mypic))
)

but it doesn't.

So my question is: how do I pass the picture object to the 'key' argument to use it as the symbol in the key?


Solution

  • As far as I know there is no way to pass your picture from grImport to key without modifying the code.

    I have a solution, although is is quite ad hoc, particularly since the images in the key move then the image is resized. (I think that could be fixed given some effort.) Anyway, using key (or auto.key) and manually placing the images at the key will get something close to the desired result.

    library(lattice)
    library(grImport)
    
    dat <- data.frame(x = rnorm(10), y = rnorm(10), ind = c("A", "B"))
    
    PostScriptTrace("petal.ps") # from https://www.jstatsoft.org/article/view/v030i04
    petal <- readPicture("petal.ps.xml") 
    
    xyplot(y ~ x, groups = ind, data = dat,
           auto.key = list(points = FALSE),
           panel = function(x, y, ...) {
             grid.symbols(petal, x, y, units = "native",
                          size = unit(4, "mm"),
                          use.gc = FALSE,
                          gp = gpar(col = "white", fill = c("red","blue")))
           })
    
    grid.symbols(petal, c(0.55, 0.55), c(0.92, 0.95), 
                 size = unit(4, "mm"),
                 use.gc = FALSE,
                 gp = gpar(col = "white", fill = c("red","blue")))
    

    Imgur