在 R 中设置颜色条限制

Set Colorbar Limits in R

我是 R 的新手。我正在尝试在网格地图上设置颜色条限制,使用 scale_fill_gradient() 根据 R 中每个网格的平均海拔进行着色。我想要一个大于可用海拔范围的固定颜色条,但我不知道如何包含它。

这是我当前使用的代码:

 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))

尝试在 scale_fill_gradient 上设置 limits=c(min,max):

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")

reprex package (v2.0.0)

于 2021-05-31 创建