Search code examples
rcolorslatticelevelplot

Using patterns in addition/instead of background colors in lattice plots


I am using level plots from the R lattice package. My resulting plots look like the one shown below.

My problem now is that I need to generate a black and white version for printing.

Is there a way to change the colors to grayscale and give the rectangles a background pattern so the the red once are distinguishable from the blue ones? For example, dots or diagonal dashes come to mind.

Thanks!

Example image


Solution

  • I found a way to manually draw into the levelplot panel and to draw a diagonal fill pattern over all cells with values greater than 0.5

    However, I couldn't manage to draw the same pattern in the color key legend. After hours of reading forums and trying to understand the lattice source code, I couldn't get a clue. Maybe someone else could fix that. Here is what I got:

    library(lattice)
    library(RColorBrewer)
    cols <- colorRampPalette(brewer.pal(8, "RdBu"))
    
    data <- Harman23.cor$cov    
    
    fx <- fy <- c()
    for (r in seq(nrow(data)))
      for (c in seq(ncol(data)))
      {
        if (data[r, c] > 0.5)
        {
          fx <- c(fx, r);
          fy <- c(fy, c);
        }
      }
    
    diag_pattern <- function(...)
    {
      panel.levelplot(...)
      for (i in seq(length(fx)))
      {
        panel.linejoin(x = c(fx[i],fx[i]+.5), y= c(fy[i]+.5,fy[i]), col="black")
        panel.linejoin(x = c(fx[i]-.5,fx[i]+.5), y= c(fy[i]+.5,fy[i]-.5), col="black")
        panel.linejoin(x = c(fx[i]-.5,fx[i]), y= c(fy[i],fy[i]-.5), col="black")   
      }
    }      
    
    p <- levelplot(data, scales=list(x=list(rot=45)), 
                   xlab="", ylab="", col.regions=cols, panel=diag_pattern)
    print(p)
    

    enter image description here