rr-rasterlevelplotrastervis

R - How to improve color shading of a RasterVis levelplot?


I am trying to improve the color shadings of a levelplot. Please take a look at the code below:

# Load required packages
library(raster)
library(rasterVis)
library(viridis)

# Download file
download.file('https://www.dropbox.com/s/caya1ja5ukpih9e/raster_thiago.tif?dl=1',
              destfile="~/Desktop/raster_thiago.tif", method="auto")

# Open file
r <- readAll(raster("~/Desktop/raster_thiago.tif"))

# Raster version
plot(r, col=viridis_pal(option="D")(255))

enter image description here

Please note how this map looks sharp when plotted with raster::plot. The color shadings are smooth, and you can't see any "contours" between them. However, sadly raster plots are not as customizable as levelplots.

Now, take a look at this attempt to do the same with RasterVis:

# RasterVis version
levelplot(r, margin=FALSE,
          par.settings=rasterTheme(viridis_pal(option = "D")(255)))

enter image description here

Do you see how this map is not as sharp as the previous one? It looks like the color palette doesn't have the same resolution, and you can see how the edges between the color gradients are not as smooth.

Is there any way to improve this look? I've tried to play around with the par.settings and col.regions arguments, but none of them seems to work. I am probably missing something...


Solution

  • With levelplot(), you will also need to explicitly supply an at = argument, a numeric vector giving the breakpoints between the levels to which the colors in col.regions = correspond. Here is a simple reproducible example:

    library(rasterVis)
    library(viridis)
    
    ## Example raster
    f <- system.file("external/test.grd", package="raster")
    r <- raster(f)
    
    ## Option 1: Use `at=` and `col.regions=` to set color gradient
    nlev <- 200
    my.at <- seq(from = cellStats(r, "min"),
                 to = cellStats(r, "max"),
                 length.out = nlev + 1)
    my.cols <- viridis_pal(option = "D")(nlev)
    levelplot(r, margin = FALSE,
              at = my.at,
              col.regions = my.cols)
    
    
    ## Option 2: Pass options via `par.settings = rasterTheme()`
    ##
    ## (NOTE: this only works for nlev up to 100)
    nlev <- 100
    my.at <- seq(cellStats(r, "min"), cellStats(r, "max"),
                 length.out = nlev + 1)
    my.theme <- rasterTheme(viridis_pal(option = "D")(nlev))
    levelplot(r, margin = FALSE,
              at = my.at,
              par.settings = my.theme)
    

    To see that this works, compare plots drawn using nlev = 10 and nlev = 200:

    enter image description here