首页 > 解决方案 > R ::tmap 在图例中绘制并显示 NA 值

问题描述

我想将点数据与鸟类计数结果进行映射。点的大小应根据计算的鸟类数量进行缩放。如果一个区域没有被计算,一个 x 应该显示为 NA 值。我如何绘制这些数据并使用 tmap 包获得一个漂亮的图例?

这是一个类似的例子:

rm(list=ls(all=TRUE)) 
library(tmap)
data(World, metro) 

# put population size pop2020 to NA for some cities
metro$pop2020[10:300] <- NA 

# add column with code for the shape of the symbol (21 for data available, 4 for NA)
metro$shape_symbol <- 21 
metro[is.na(metro$pop2020), ]$shape_symbol <- 4

tm_shape(World) + tm_fill()+
  tm_shape(metro) + 
  tm_symbols(
    size = "pop2020",
    col = "black",
    shape = "shape_symbol", # use column shape_symbol in metro for the symbol 
  #  shapeNA = "4", # should plot NA as cross by default -  didn´t work for me 
    title.size = "subtitle", 
    legend.size.is.portrait=TRUE) +
tm_layout(legend.bg.color = "gray", 
          legend.frame = "black")

这给出了这个输出。为什么不显示 NA 值?以及如何获得漂亮的图例输出?

在此处输入图像描述

我的目标是达到这个目标:

在此处输入图像描述

鸟类的名称应以粗体图例标题给出,并为下面的图例符号附加标签“Anzahl”。理想情况下,NA 的符号 x 应该像这样放置。我可以使用 title.size 从循环中粘贴(i)作为图例标题,但是如何在图例中获得第二个标题。附加问题:我可以将点的大小设置为某个范围吗?所以非常小的数字在地图中具有最小尺寸?

标签: rlegendsymbolsnatmap

解决方案


我自己使用解决方法解决了这个问题:

我添加了一个额外的层,只选择了缺失值的数据。然后我使用 tm_add_legend 添加了一个额外的图例元素。

data(World, metro) 

# put population size pop2020 to NA for some cities
metro$pop2020[10:300] <- NA 

tm_shape(World) + tm_fill()+
  tm_shape(metro) + 
  tm_symbols(
    size = "pop2020",
    col = "black",
    title.size = "subtitle", 
    legend.size.is.portrait=TRUE) +
  tm_shape(metro[is.na(metro$pop2020),]) +
                 tm_dots(shape=4, size = 0.5, border.lwd = 0.5) +
  tm_layout(legend.bg.color = "gray", 
            legend.frame = "black") + 
    tm_add_legend(type="symbol", shape =4, labels = "not available", size = 0.5, border.lwd = 0.5, col = "black") 

推荐阅读