I'm starting to get acquainted with using R in mapping and I am currently working with the tmap
package. I am running into problems when subsetting the data. I can select various subsets using the tidyverse syntax without problems, but I am unable to remove the unused levels to ensure that the legends remain reasonable.
#// load library and data
library(tidyverse)
library(tmap)
data("World")
#// subset data to only include Africa
tm_africa <- filter(World, continent == "Africa")
tm_shape(tm_africa) + tm_polygons("name")
#> Warning: Number of levels of the variable "name" is 177, which is
#> larger than max.categories (which is 30), so levels are combined. Set
#> tmap_options(max.categories = 177) in the layer function to show all levels.
#> Some legend labels were too wide. These labels have been resized to 0.62, 0.45, 0.54, 0.59, 0.50, 0.62, 0.61, 0.62, 0.47, 0.46, 0.63. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.
#// remove unused levels for proper legends
#// output suggests levels are indeed dropped
forcats::fct_drop(tm_africa$name)
#> [1] Angola Burundi Benin
#> [4] Burkina Faso Botswana Central African Rep.
#> [7] Cote d'Ivoire Cameroon Dem. Rep. Congo
#> [10] Congo Djibouti Algeria
#> [13] Egypt Eritrea Ethiopia
#> [16] Gabon Ghana Guinea
#> [19] Gambia Guinea-Bissau Eq. Guinea
#> [22] Kenya Liberia Libya
#> [25] Lesotho Morocco Madagascar
#> [28] Mali Mozambique Mauritania
#> [31] Malawi Namibia Niger
#> [34] Nigeria Rwanda W. Sahara
#> [37] Sudan S. Sudan Senegal
#> [40] Sierra Leone Somaliland Somalia
#> [43] Swaziland Chad Togo
#> [46] Tunisia Tanzania Uganda
#> [49] South Africa Zambia Zimbabwe
#> 51 Levels: Algeria Angola Benin Botswana Burkina Faso Burundi ... Zimbabwe
#// check if levels are removed
#// still listing countries from outside Africa
head(levels(tm_africa$name))
#> [1] "Afghanistan" "Albania" "Algeria" "Angola" "Antarctica"
#> [6] "Argentina"
#// plot again to verify levels have not changed
tm_shape(tm_africa) + tm_polygons("name")
#> Warning: Number of levels of the variable "name" is 177, which is
#> larger than max.categories (which is 30), so levels are combined. Set
#> tmap_options(max.categories = 177) in the layer function to show all levels.
#> Some legend labels were too wide. These labels have been resized to 0.62, 0.45, 0.54, 0.59, 0.50, 0.62, 0.61, 0.62, 0.47, 0.46, 0.63. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.
Created on 2021-01-18 by the reprex package (v0.3.0)