geom_spatraster
dropping levels when plotting
#177
-
Hi, I have a spatraster that looks like this:
However, there are more levels defined in the SpatRaster:
I am using
While the legend labels exists for the last two bins, the colors in the legend will not show. Only the first three bins, that are present in the data, are shown.
My question would be, how can I still show all the legend items, even if levels are not present in the data? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
See https://stackoverflow.com/a/45765225/7877917 use library(tidyterra)
#>
#> Adjuntando el paquete: 'tidyterra'
#> The following object is masked from 'package:stats':
#>
#> filter
library(tidyverse)
library(terra)
#> terra 1.8.42
#>
#> Adjuntando el paquete: 'terra'
#> The following object is masked from 'package:tidyr':
#>
#> extract
library(ggplot2)
r_init <- rast(system.file("ex/elev.tif", package = "terra"))
r1 <- r_init %>%
mutate(
cats = scales::rescale(elevation, to = c(0, 60)),
lyr.1 = cut(cats,
breaks = c(0, 10, 30, 60, 90, 120),
labels = c("0-10", "10-30", "30-60", "60-90", "90-120")
)
) %>%
select(lyr.1)
r1
#> class : SpatRaster
#> dimensions : 90, 95, 1 (nrow, ncol, nlyr)
#> resolution : 0.008333333, 0.008333333 (x, y)
#> extent : 5.741667, 6.533333, 49.44167, 50.19167 (xmin, xmax, ymin, ymax)
#> coord. ref. : lon/lat WGS 84 (EPSG:4326)
#> source(s) : memory
#> categories : label
#> name : lyr.1
#> min value : 0-10
#> max value : 30-60
terra::levels(r1)[[1]]
#> value label
#> 1 1 0-10
#> 2 2 10-30
#> 3 3 30-60
#> 4 4 60-90
#> 5 5 90-120
terra::cats(r1)[[1]]
#> value label
#> 1 1 0-10
#> 2 2 10-30
#> 3 3 30-60
#> 4 4 60-90
#> 5 5 90-120
terra::is.factor(r1)
#> [1] TRUE
colorVal <- c("#2892c7", "#a0c79b", "#fafa64", "#fa8d34", "#e81014")
names(colorVal) <- levels(r1$lyr.1)[[1]]$label
colorVal
#> 0-10 10-30 30-60 60-90 90-120
#> "#2892c7" "#a0c79b" "#fafa64" "#fa8d34" "#e81014"
ggplot() +
geom_spatraster(data = r1, show.legend = TRUE) +
scale_fill_manual(values = colorVal, drop = FALSE, na.translate = FALSE) Created on 2025-04-24 with reprex v2.1.1 |
Beta Was this translation helpful? Give feedback.
-
Thanks, I was aware of the +1 for using my desired color scheme. |
Beta Was this translation helpful? Give feedback.
See https://stackoverflow.com/a/45765225/7877917 use
show.legend = TRUE
in the geom anddrop = FALSE
in the scale: