Search code examples
rggplot2rasterterratidyterra

Changing color categories and scale in rasters in ggplot2 in R


I would like to modify the colors across which my palette operate, to expand the yellow region so that extreme values in my figure stand out more dramatically. I can't figure out how to change this, but have an example below.

Loading required libraries:


library(tidyterra)
library(ggplot2)
library(terra)
library(dplyr)

Creating an example dataframe that I will then convert to a raster:

df <- data.frame( x = rep( 0:1, each = 2 ),
                  y = rep( 0:1,  2),
                  l = rnorm( 4 ))

df_raster <- rasterFromXYZ(df) %>% terra::rast()

And below, I try to use breaks = to break the color palette into different categories. Unfortunately, it seems to do nothing. I want to expand the yellow region in the middle of the bl_yl_rd, and would be happy to designate certain numbers to indicate where along the values of my raster it should transition colors. Is there a way to do this, or a different function other than scale_fill_whitebox that will do a better job of this?

ggplot() + geom_spatraster(data = df_raster) + 
  scale_fill_whitebox_c(palette = "bl_yl_rd", breaks = 2)


Solution

  • Use the breaks as a vector like:

    set.seed(234)
    df <- data.frame( x = rep( 0:1, each = 2 ),
                      y = rep( 0:1,  2),
                      l = rnorm( 4 ))
    
    df_raster <- terra::rast(df)
    
    ggplot2::ggplot() + 
      tidyterra::geom_spatraster(data = df_raster) +
      tidyterra::scale_fill_whitebox_b(palette = "bl_yl_rd", breaks = c(0,1))
    

    Created on 2024-02-29 with reprex v2.1.0