Open danbebber opened 2 months ago
Maybe this? fortify
to a tibble with tidyterra method, and then pivot, split labels and plot as a regular data frame.
library(terra)
#> terra 1.7.78
library(ggplot2)
library(tidyterra)
#>
#> Attaching package: 'tidyterra'
#> The following object is masked from 'package:stats':
#>
#> filter
x <- rast(array(data = rnorm(120, 0, 1), dim = c(5, 5, 4)))
names(x) <- c("A_1", "B_1", "A_2", "B_2")
ggplot() +
geom_spatraster(data = x) +
facet_wrap(~lyr, ncol = 2) +
coord_sf(crs = pull_crs(x)) +
labs(x = "", y = "")
# Fortify method converting to data.frame
x_frt <- fortify(x) %>%
pivot_longer(-c(x:y), names_to = "lyr", values_to = "value") %>%
mutate(
col_n = stringr::str_split_i(lyr, "_", 1),
row_n = stringr::str_split_i(lyr, "_", 2)
)
x_frt
#> # A tibble: 100 × 6
#> x y lyr value col_n row_n
#> <dbl> <dbl> <chr> <dbl> <chr> <chr>
#> 1 0.5 4.5 A_1 -0.318 A 1
#> 2 0.5 4.5 B_1 1.02 B 1
#> 3 0.5 4.5 A_2 -0.612 A 2
#> 4 0.5 4.5 B_2 0.989 B 2
#> 5 1.5 4.5 A_1 -2.68 A 1
#> 6 1.5 4.5 B_1 1.83 B 1
#> 7 1.5 4.5 A_2 -0.792 A 2
#> 8 1.5 4.5 B_2 0.132 B 2
#> 9 2.5 4.5 A_1 0.274 A 1
#> 10 2.5 4.5 B_1 0.128 B 1
#> # ℹ 90 more rows
ggplot(x_frt, aes(x, y, z = value, fill = value)) +
geom_raster() +
facet_grid(vars(row_n), vars(col_n)) +
coord_sf(crs = pull_crs(x)) +
labs(x = "", y = "")
Created on 2024-07-30 with reprex v2.1.1
I've posted this on Stack Overflow: tidyterra allows use of
facet_wrap(~lyr)
to plot multiple spatial raster layers in one figure.Is there any way of implementing
facet_grid
in tidyterra so that, in the case above for example, the rows would be labelled 1 and 2, and columns would be labelled A and B? This would require a spatraster object to have more than one attribute (the name of the layer) associated with it, I guess. I don't know if a data.frame can be associated with a spatraster object in which each row refers to a layer?