plotting multiple attribute columns of shapefile in panel

57 views Asked by At

I have a GIS vector file containing multiple attribute columns, such as t1, t2, t3, up to t8. My objective is to create individual plots for each attribute column within a panel display. Despite my attempts using terra, ggplot, and tidyterra, I consistently encounter errors during the process. I am not able to loop over with column names. aes fill is not taking column names and considering it as a discrete variable. Any assistance in resolving this challenge would be greatly appreciated.

grids = vect('5k_grid_scenarios.gpkg')

grids = grids %>% 
            select(t1:t8)

p = c()

for (i in names(grids)){

  plot = 
    grids %>% 
    autoplot(aes(fill = i))+
    scale_fill_whitebox_c(palette = "pi_y_g")
  p[[i]] =plot
  
}

ggarrange(p)


1

There are 1 answers

0
dieghernan On

You may need to create a "long" version with tidyr::pivot_longer() and skip the use of ggarrange.

tidyterra does not provide a direct pivot_longer() method for Spatvector but you can convert the SpatVector to a tibble with a column with the geometry dat and regenerate the object after pivoting, see:

library(terra)
#> terra 1.7.71
library(ggplot2)
library(tidyterra)
library(dplyr)
library(tidyr)

# I am using here a file to mock your input
grids <- vect(system.file("extdata/cyl.gpkg", package = "tidyterra"))

# Create t1:t8
set.seed(1234)
for (i in 1:8) {
  df <- tibble(col = runif(nrow(grids)))
  names(df) <- paste0("t", i)
  grids <- bind_spat_cols(grids, df)
}

# Your starting point
grids <- grids %>%
  select(t1:t8)

# Keep the crs for regenerate
keep_crs <- crs(grids)

# Pivot via as_tibble() and regenerate with as_spatvector()
grids_long <- grids %>%
  # The tibble would have a `geometry` column with the geometry info
  as_tibble(geom = "wkt") %>%
  pivot_longer(cols = t1:t8) %>%
  # Regenerate from tibble to SpatVector, see the crs here
  as_spatvector(geom = "geometry", crs = keep_crs)


# Faceted plot with facet_wrap()
autoplot(grids_long, aes(fill = value)) +
  facet_wrap(~name, ncol = 2) +
  scale_fill_whitebox_c(palette = "pi_y_g")

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