Search code examples
rr-sfggmap

Set Colorbar Limits in R


I am relatively new to R. I am trying to set the colorbar limits on a grid map, colored based on the average elevation of each grid in R using scale_fill_gradient(). I want to have a fixed colorbar larger than the range of elevations available and I don't know how to include that.

This is the current code that I am using:

 ggmap(basemap) + 
    geom_sf(data = grid, aes(fill = elevation), col = NA, 
    show.legend = "POLYGON", inherit.aes = FALSE, alpha=.8) +
    coord_sf(crs = 4326)+
    scale_fill_gradient(guide = guide_colorbar(title = 'Elevation',barheight = 10))

Solution

  • Try setting limits=c(min,max) on scale_fill_gradient:

    library(mapSpain)
    library(sf)
    library(tidyverse)
    
    # Since you didn't provide an example...
    # Create a mock grid
    grid <- esp_get_ccaa("Cataluña", epsg = "3857") %>%
      st_make_grid(n = 40)
    
    # Mock elevation between 0 and 20
    grid <- st_as_sf(elevation = runif(length(grid), 0, 20), grid)
    
    # Plot
    ggplot() +
      geom_sf(
        data = grid, aes(fill = elevation), col = NA,
        show.legend = "POLYGON", inherit.aes = FALSE, alpha = .8
      ) +
      scale_fill_gradient(
        guide = guide_colorbar(title = "Elevation", barheight = 10)
      ) +
      labs(title = "No Limits")
    

    # Solution
    ggplot() +
      geom_sf(
        data = grid, aes(fill = elevation), col = NA,
        show.legend = "POLYGON", inherit.aes = FALSE, alpha = .8
      ) +
      scale_fill_gradient(
        guide = guide_colorbar(title = "Elevation", barheight = 10),
        # Set your limits
        limits = c(-200, 200)
      ) +
      labs(title = "With Limits")
    

    Created on 2021-05-31 by the reprex package (v2.0.0)