0

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
  • 1
    Try with aes(fill = .data[[i]]) to refer to the column with name I. Additionally I would suggest to use lapply to create your list of plots, e.g. something like p <- lapply(names(grids), \(i) { grids |> autoplot(aes(fill = .data[[i]])) + ... }). For more help please provide a minimal reproducible example. Commented Feb 17, 2024 at 6:27

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.