Created
May 23, 2019 03:52
-
-
Save johnbaums/cfd8d76b348fba30ab45fb79b57034bb to your computer and use it in GitHub Desktop.
Plot a second colorkey using levelplot and grid graphics in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(raster) | |
library(rasterVis) | |
library(RColorBrewer) | |
library(grid) | |
library(viridisLite) | |
r1 <- raster(matrix(runif(100), 10)) | |
r2 <- raster(matrix(runif(100), 10)) | |
xy <- xyFromCell(r1, sample(ncell(r1), 10), spatial=TRUE) | |
dif <- raster::extract(r2, xy) - raster::extract(r1, xy) | |
p <- levelplot(r, margin=FALSE, colorkey=list(height=0.6), | |
at=seq(0, 1, length=100), xlab='', ylab='', | |
col.regions=viridisLite::viridis, | |
main='A plot', | |
par.settings=list(layout.heights=list(axis.bottom=1.6))) | |
ramp <- colorRampPalette(brewer.pal(11, 'RdBu')) | |
k <- draw.colorkey( | |
list(space='bottom', at=seq(-1, 1, length=100), height=0.25, | |
col=ramp) | |
) | |
k$framevp$y <- unit(0.05, "npc") | |
k$framevp$name <- 'key2' | |
p + layer( | |
sp.points(xy, pch=21, cex=1.5, lwd=2, | |
col=ramp(100)[as.numeric(cut(dif, seq(-1, 1, length=100)))]) | |
) | |
grid.draw(k) | |
seekViewport('key2') | |
pushViewport(grid::current.vpTree(all=FALSE)$children[[1]]) | |
grid.text('difference', 0.5, 1.2, hjust=0.5, vjust=0, gp=gpar(font=2)) |
Author
johnbaums
commented
May 23, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment