如何解决无法删除 tmap 数据中的因素
我开始熟悉在映射中使用 R 并且我目前正在使用 tmap
包。对数据进行子集化时遇到问题。我可以使用 tidyverse 语法毫无问题地选择各种子集,但我无法删除未使用的级别以确保图例保持合理。
#// 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.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,0.63. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.
由 reprex package (v0.3.0) 于 2021 年 1 月 18 日创建
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。