Lucie
Lucie

Reputation: 13

How to display only some country names with tm_text in R

I have created a map of Africa in R, using tmap, showing some numerical variables, but I would like to show the name of the countries only for the countries where the numerical variable is not 0.

So I have created a colour vector containing the value 'black' when the numeric was >0 and NA when it was =0. For a lot of functions, this will allow to display only the 'black' labels and not the NA ones, but with tm_text the NA values are shown in white on the map.

Map image

I tried to use several of the tm_text options, but nothing worked. If I change the NA with a colour name it works, the labels are displayed in the colour I indicated, but NA doesn't allow to make the labels disappear.

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()

Of course I could use the pale yellow as label colour for the countries I don't want to display but these labels would still be visible when they overlap with borders or neighbouring countries.

Is there a way to do that more elegantly?

Thank you

Upvotes: 1

Views: 1614

Answers (1)

Gregor
Gregor

Reputation: 180

There are, as usual, many different solutions. You could just create another africa data frame (sfc), only with the features that you need, i.e. x>0 and go

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

Reproducible Example

# 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")

Or the tidyverse way

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

Upvotes: 3

Related Questions