Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column labels in tmap plot with facets grid

Tags:

r

tmap

Consider the following example:

library(tmap)

mydf <- NLD_muni %>% filter(province %in% c("Drenthe", "Flevoland"))

tm_shape(mydf) +
  tm_polygons(
    fill = c("employment_rate", "dwelling_value")) +
tm_facets_grid(columns = "province") +
  tm_layout(
    panel.labels = c("Employment Rate", "Dwelling Value"),
    legend.show = FALSE
  )

enter image description here

How can I insert labels for left and right columns on top of the plot?

For example I would like to label them "province 1" and "province 2".

like image 667
robertspierre Avatar asked Oct 30 '25 18:10

robertspierre


1 Answers

Not sure if this is exactly what you're looking for, but my preference is always to just create all the necessary labels in the dataframe ahead of plotting. In that vein, this solution does what you're aiming for:

library(tmap)
library(dplyr)

mydf <- NLD_muni %>% 
  filter(province %in% c("Drenthe", "Flevoland")) %>%
  mutate(
    province_label = case_when(
      province == "Drenthe" ~ "province 1",
      province == "Flevoland" ~ "province 2"
    )
  ) |>
  rename(
    "Employment Rate" = employment_rate,
    "Dwelling Value" = dwelling_value
  )

tm_shape(mydf) +
  tm_polygons(
    fill = c("Employment Rate", "Dwelling Value")
  ) +
  tm_facets_grid(columns = "province_label") +
  tm_layout(legend.show = FALSE)

enter image description here

It seems that overriding the default panel labels with the panel.labels argument is what caused the issue.

like image 126
Daniel Molitor Avatar answered Nov 01 '25 08:11

Daniel Molitor