rfacetterratmapr-stars

How to reorder facets in tmap r?


I want to reorder the facets of tmap raster plot. I am using the following code

library(tmap)
library(stars)
library(terra)

#Read some data
tif = system.file("tif/L7_ETMs.tif", package = "stars")
x = rast(tif)

#Assign some fake names to the bands
names(x) <- c("RF_04.Apr.2022_LL", "RF_13.Dec.2021_LL", "RF_15.Feb.2022_LL", "RF_17.Dec.2020_LL", "RF_18.Nov.2021_LL", "RF_19.Feb.2021_LL")

#Plot it using tmap r package
tm_shape(x) +
  tm_raster(style="quantile")+
  tm_facets(nrow = 3) +
  tm_layout(panel.labels = names(x), 
            legend.outside=T, legend.outside.position = "right",
            legend.position= c("center", "center"),
            legend.text.size = 1,
            legend.format = list(digits = 2, text.separator = "-"))+
  tm_compass(position = c("LEFT", "BOTTOM"))+
  tm_scale_bar(breaks = c(0, 0.5), text.size = 1, position = c("LEFT", "BOTTOM"))

which returns me the following output enter image description here

But I want to have the facets in the following sequence (i.e. in chronological order)

"RF_17.Dec.2020_LL", "RF_19.Feb.2021_LL", "RF_18.Nov.2021_LL",
"RF_13.Dec.2021_LL", "RF_15.Feb.2022_LL", "RF_04.Apr.2022_LL"

How can I do it?


Solution

  • There seems to be some kind of an issue with layer names and tmap (v3) facets when changing SpatRaster layer order though subsetting. Here's a partial answer that might provide a workaround by first sorting filenames by encoded dates so layers in the resulting SpatRaster would be ordered chronologically, presumably fixing facet order:

    library(tidyverse)
    
    file_list <- c("RF_04.Apr.2022_LL", "RF_13.Dec.2021_LL", "RF_15.Feb.2022_LL", "RF_17.Dec.2020_LL", "RF_18.Nov.2021_LL", "RF_19.Feb.2021_LL")
    
    # extract dates, use file_list vector for names
    date_list <- 
      file_list |> 
      stringr::str_extract("(?<=_).*(?=_)") |> 
      lubridate::dmy() |>
      setNames(file_list)
    date_list
    #> RF_04.Apr.2022_LL RF_13.Dec.2021_LL RF_15.Feb.2022_LL RF_17.Dec.2020_LL 
    #>      "2022-04-04"      "2021-12-13"      "2022-02-15"      "2020-12-17" 
    #> RF_18.Nov.2021_LL RF_19.Feb.2021_LL 
    #>      "2021-11-18"      "2021-02-19"
    
    # sort by dates, extract names
    (file_list_sorted <- sort(date_list) |> names())
    #> [1] "RF_17.Dec.2020_LL" "RF_19.Feb.2021_LL" "RF_18.Nov.2021_LL"
    #> [4] "RF_13.Dec.2021_LL" "RF_15.Feb.2022_LL" "RF_04.Apr.2022_LL"
    
    # import rasters
    x = rast(file_list_sorted)
    
    # alter names to only keep date values, part between _ & _
    names(x) <- names(x) |> stringr::str_extract("(?<=_).*(?=_)")
    names(x)
    #> [1] "17.Dec.2020" "19.Feb.2021" "18.Nov.2021" "13.Dec.2021" "15.Feb.2022" "04.Apr.2022"
    
    
    # continue with tmap