如何在R中仅显示带有tm_文本的某些国家/地区名称

如何在R中仅显示带有tm_文本的某些国家/地区名称,r,tmap,R,Tmap,我用tmap在R中创建了一张非洲地图,显示了一些数值变量,但我只想显示数值变量不为0的国家的名称 因此,我创建了一个颜色向量,当数值大于0时包含值“黑色”,当数值等于0时包含值“NA”。对于许多函数,这将允许仅显示“黑色”标签,而不显示NA标签,但使用tm_文本,NA值在地图上以白色显示 我尝试使用了几个tm_文本选项,但都不起作用。如果我用一个有效的颜色名称更改NA,标签将以我指示的颜色显示,但NA不允许使标签消失 spdf_africa <- ne_countries(contine

我用tmap在R中创建了一张非洲地图,显示了一些数值变量,但我只想显示数值变量不为0的国家的名称

因此,我创建了一个颜色向量,当数值大于0时包含值“黑色”,当数值等于0时包含值“NA”。对于许多函数,这将允许仅显示“黑色”标签,而不显示NA标签,但使用tm_文本,NA值在地图上以白色显示

我尝试使用了几个tm_文本选项,但都不起作用。如果我用一个有效的颜色名称更改NA,标签将以我指示的颜色显示,但NA不允许使标签消失

spdf_africa <- ne_countries(continent = 'africa',type="map_units",scale = "medium", returnclass = "sf")

xx<-numeric(length=57)
xx[match(names(tole),spdf_africa$name)]<-tole
xxcol<-xx
xxcol[xx>0]<-"black"
xxcol[xx==0]<-NA

afric=spdf_africa
afric$studies<-xx
afric$studiesTF<-xxcol

tm_shape(afric)+tm_fill(col="studies",title="Nb",style="cat")+tm_text("iso_a3",col="studiesTF",size=0.8)+tm_borders()

spdf_africa像往常一样,有许多不同的解决方案。
您只需创建另一个非洲数据帧(sfc),只需具备所需的功能,即x>0和go

tm_shape(afric) + 
    tm_fill(col="studies",title="Nb",style="cat") + 
    tm_borders() + 
tm_shape(afric_selection) + 
    tm_text("iso_a3)
可复制示例

# load library
library(tmap)
# get world data set (sf)
data(World)
# create two shapes, one with border, one with selection (life expectancy bigger then 80 years) and only text
tm_shape(World) + tm_borders() +
  tm_shape(World[World$life_exp > 80, ]) + tm_text("iso_a3")
或者是整洁的方式

tm_shape(World) + 
    tm_borders() + 
tm_shape(World %>% filter(life_exp > 80)) + 
  tm_text("iso_a3")

和往常一样,有许多不同的解决方案。 您只需创建另一个非洲数据帧(sfc),只需具备所需的功能,即x>0和go

tm_shape(afric) + 
    tm_fill(col="studies",title="Nb",style="cat") + 
    tm_borders() + 
tm_shape(afric_selection) + 
    tm_text("iso_a3)
可复制示例

# load library
library(tmap)
# get world data set (sf)
data(World)
# create two shapes, one with border, one with selection (life expectancy bigger then 80 years) and only text
tm_shape(World) + tm_borders() +
  tm_shape(World[World$life_exp > 80, ]) + tm_text("iso_a3")
或者是整洁的方式

tm_shape(World) + 
    tm_borders() + 
tm_shape(World %>% filter(life_exp > 80)) + 
  tm_text("iso_a3")

太棒了,非常感谢!我按照建议创建了新的数据框架,它工作得非常好!非常感谢。不客气。你能把我的帖子标为“答案”吗?太棒了,非常感谢!我按照建议创建了新的数据框架,它工作得非常好!非常感谢。不客气。你能把我的帖子标上“答案”吗?