How to add tick or bar on color scale for levelplot in R

895 views Asked by At

Using the levelplot function from the lattice package, how can I add a tick or line to highlight a value on the color scale next to the level plot.

More specifically, I am plotting a covariance matrix as a heatmap and for example, I want to be able to indicate the level of significance on the color scale.

library(lattice)

mat <- matrix(rnorm(25),ncol=5,nrow=5)
cov.m <-  cov(mat[,1:5],mat[1:5,])

levelplot(cov.m,  xlab="", ylab="", 
          col.regions= colorRampPalette(c("blue","white","red"), 
          space = "rgb"), cuts=100, at=seq(-0.2,1,0.005))

I now want to indicate 0.18 on the adjacent color scale.

UPDATE: so, I attempted to add an abline to plot.trellis and I do not get an error or a warning but it seems to be ignored. It could be that I'm not even hacking the source code correctly. Anybody with step-by-step instructions on how to modify the code in the lattice package in the context of this question?

2

There are 2 answers

2
IRTFM On

(More of an extended comment on strategy than a final answer.) If you would desire to use grid plotting functons within the context of the levelplot code, you will need to do a "deep dive" into lattice and grid packages.

 methods(levelplot)
 getAnywhere(lattice.matrix)
 getAnywhere(lattice.formula)
 getAnywhere(construct.legend)
 lev <- levelplot(cov.m,  xlab="", ylab="", 
      col.regions= colorRampPalette(c("blue","white","red"), 
      space = "rgb"), cuts=100, at=seq(-0.2,1,0.005))
 lev$legend
 methods(print)
 getAnywhere(print.trellis)
 getAnywhere(plot.trellis)

The legend-drawing lines in the plot.trellis function are at the bottom. You could make a new plot.trellis and use update.trellis to modify the legend node of the lattice-object. Or you could hack around and attempt to position a grid-based annotation.

0
Eko Susilo On

Try using yscale.components=yscale.raster.subticks. For example:

levelplot(cov.m, 
       col.regions= colorRampPalette(c("blue","white","red"), space = "rgb"), 
       at=seq(-0.2,1,0.005)),
       yscale.components=yscale.raster.subticks,
       xscale.components=xscale.raster.subticks,
       margin=FALSE, 
       ylab='Y', 
       xlab='X', 
       main='Plot Name')