Last active
August 4, 2018 05:47
-
-
Save johnbaums/4c62b91000f0528e3439147320cbf349 to your computer and use it in GitHub Desktop.
Plot a raster, modified by a second raster indicating transparency
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
add_transparency <- function(x, alpha_raster, ramp, ...) { | |
# x: The raster to plot, to which transparency will be added. | |
# alpha_raster: A raster with the same extent, resolution and CRS as `x`, with | |
# values indicating relative opacity. The maximum value of alpha_raster is | |
# assigned full opacity; lower values scale linearly to zero. | |
# ramp: A function (like that returned by colorRampPalette) that returns a | |
# vector of hexadecimal colour values. | |
# ...: additional arguments passed to rasterVis::levelplot. | |
require(raster) | |
require(rasterVis) | |
compareRaster(x, alpha_raster, stopiffalse=TRUE, res=TRUE, orig=TRUE, crs=FALSE) | |
r <- raster(x) | |
colr <- ramp(100) | |
if(nchar(colr)[1]==9) colr <- substr(colr, 1, 7) | |
trans <- floor(alpha_raster[]/max(alpha_raster[], na.rm=TRUE)*255) | |
trans[is.na(trans)] <- 0 | |
trans <- sprintf('%x', trans) | |
trans <- ifelse(nchar(trans)==1, paste0('0', trans), trans) | |
cols <- paste0(colr[as.numeric(cut(x[], seq(0, 1, length=101)))], trans) | |
cols[cols=='NA00'] <- '#00000000' | |
cols <- as.factor(cols) | |
r[] <- cols | |
p <- levelplot(r, col.regions=as.character(levels(cols)), ...) | |
if('legend' %in% names(p)) { | |
p2 <- levelplot(x, col.regions=ramp(100), ...) | |
p$legend[[1]]$args$key$at <- p2$legend[[1]]$args$key$at | |
p[[grep('^legend', names(p))]][[1]]$args$key$col <- p2[[grep('^legend', names(p2))]][[1]]$args$key$col | |
p[[grep('^legend', names(p))]][[1]]$args$key$labels <- NULL | |
} | |
p | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example