Reputation: 368
I want to display tm_text options based on a filter of a data. Take the following example:
tm_shape(World) +
tm_polygons("HPI") +
tm_text("name", size = "AREA")
This displays text for every feature. But let's say I only wanted to display text for countries with a value of, say, HPI greater than 30. I hoped there could be an argument within tm_text, something like tm_text(..., filter = "HPI" > 30), but I can't see any like that. The only way I can think to do this is by creating another layer:
tm_shape(World) +
tm_polygons("HPI") +
tm_shape(World %>% filter(HPI > 30)) +
tm_text("name", size = "AREA")
The syntax is nice and intuitive and the text is what I want apart from colour; notice how now the colour of the text is all black. In the first example it displayed white font on darker polygons. My only reasoning for this is that the second layer isn't "aware" of the colour of the polygons since they are in an other layer.
One other way I thought might work was to include a variable within the data based on the filter.
World <- World %>% mutate(FLAG = if_else(HPI > 30, 1, 0)
tm_shape(World) +
tm_polygons("HPI") +
tm_text("name", size = "FLAG")
The placement and colour is right here, but ignoring the fact that I don't want flag variable all over my data, the size is now incorrect since I'm using it as a hacky way of filtering. Please also ignore the fact some text is not visible when white; obviously I would change the background color, this is an example and in my map the text will bve visible over the bg).
So in summary, i'm asking if there is a way I can achieve the text size + placement from the second map, but colour from the first map (and if possible, without editing the data).
Upvotes: 0
Views: 1293
Reputation: 3472
In my opinion, the easiest solution is to modify the name
variable creating another variable which is equal to name if HPI >= 30
and empty character vector otherwise. For example:
# packages
library(tmap)
library(dplyr)
# data
data("World")
# modify name column according to HPI
World <- World %>%
mutate(new_name = ifelse(HPI >= 30, as.character(name), ""))
# plot
tm_shape(World) +
tm_polygons("HPI") +
tm_text("new_name", size = "AREA")
Created on 2020-05-14 by the reprex package (v0.3.0)
Upvotes: 1