r-tmap / tmap

R package for thematic maps
https://r-tmap.github.io/tmap
GNU General Public License v3.0
868 stars 121 forks source link

nrows/ncols do not work in tm_facets in tmap v4 #713

Open Nowosad opened 1 year ago

Nowosad commented 1 year ago
library(tmap)
library(spData)
library(dplyr)
library(sf)
tmap_mode("plot")
#> tmap mode set to 'plot'
# prep data
regions = aggregate(x = us_states[, "total_pop_15"], by = list(us_states$REGION),
                    FUN = sum, na.rm = TRUE)
us_states_facet = select(us_states, REGION, total_pop_15) |>
  mutate(Level = "State")
regions_facet = dplyr::rename(regions, REGION = Group.1) |>
  mutate(Level = "Region")
us_facet = rbind(us_states_facet, regions_facet) |>
  mutate(Level = factor(Level, levels = c("State", "Region"))) |>
  st_cast("MULTIPOLYGON")

# plot
tm_shape(us_facet) +
  tm_polygons("total_pop_15", fill.legend = tm_legend("Total population:")) +
  tm_facets(by = "Level", nrows = 1, drop.units = TRUE)

Nowosad commented 2 weeks ago

tm_facets_wrap() reacts to the nrow argument, but tm_facets() does not:

library(tmap)
library(spData)
library(dplyr)
library(sf)
tmap_mode("plot")
#> ℹ tmap mode set to "plot".

# prep data
regions = aggregate(x = us_states[, "total_pop_15"], by = list(us_states$REGION),
                    FUN = sum, na.rm = TRUE)
us_states_facet = select(us_states, REGION, total_pop_15) |>
  mutate(Level = "State")
regions_facet = dplyr::rename(regions, REGION = Group.1) |>
  mutate(Level = "Region")
us_facet = rbind(us_states_facet, regions_facet) |>
  mutate(Level = factor(Level, levels = c("State", "Region"))) |>
  st_cast("MULTIPOLYGON")

# 2 rows (nrow not working)
tm_shape(us_facet) +
  tm_polygons("total_pop_15", fill.legend = tm_legend("Total population:")) +
  tm_facets(by = "Level", nrow = 1, drop.units = TRUE)


# 1 row (as expected)
tm_shape(us_facet) +
  tm_polygons("total_pop_15", fill.legend = tm_legend("Total population:")) +
  tm_facets_wrap(by = "Level", nrow = 1, drop.units = TRUE)