代码优先:
library(tmap)
library(tmaptools)
data("Europe")
# subset just three countries for illustration
threeC <- Europe[Europe$sovereignt %in% c("Germany", "Poland", "Ukraine"), ]
tm_shape(threeC) +
tm_polygons() +
tm_shape(threeC) +
tm_borders() +
tm_fill("pop_est",
palette = get_brewer_pal("YlGnBu"),
legend.show = F,
style = "order") +
tm_text("sovereignt", size = .8) +
tm_shape(threeC) +
tm_text("pop_est", size = .8, auto.placement = .1)
问题1:是否可以通过在tm_text()函数中使用某个公式来显示地图中的“pop_est”数字,数字为2位小数,如:82.32m,38.48m,45.70m(即,不创建另一个数据框中的自定义列,然后使用它而不是“pop_est”)?
问题2:显示国家/地区名称的文本颜色为黑色或白色(此处“德国”以白色打印,其他两个国家/地区名称以黑色打印),具体取决于填充颜色,这极大地帮助了大型地图的可见性。但是显示“pop_est”数字的附加文字的颜色总是黑色的。如何使它也是黑色或白色取决于填充颜色,以帮助可见性?
答案 0 :(得分:0)
答案1:经过一些实验后,如果事先没有创建自定义列,似乎无法做到这一点:
threeC$pop_est.m <- (threeC$pop_est/1e6) %>% sprintf("%.2f", .) %>% paste0("m")
答案2:使用另一个tm_fill
函数和之前的所有选项,并通过alpha = 0
添加透明度。
因此修改后的代码将是:
library(tmap)
library(tmaptools)
data("Europe")
# subset just three countries for illustration
threeC <- Europe[Europe$sovereignt %in% c("Germany", "Poland", "Ukraine"), ]
threeC$pop_est.m <- (threeC$pop_est/1e6) %>% sprintf("%.2f", .) %>% paste0("m")
tm_shape(threeC) +
tm_polygons() +
tm_shape(threeC) +
tm_borders() +
tm_fill("pop_est",
palette = get_brewer_pal("YlGnBu"),
legend.show = F,
style = "order") +
tm_text("sovereignt", size = .8) +
tm_shape(threeC) +
tm_fill("pop_est",
palette = get_brewer_pal("YlGnBu"),
legend.show = F,
style = "order",
alpha = 0) + # make it transparent
tm_text("pop_est.m", size = .8, auto.placement = .1)