in123321
in123321

Reputation: 103

Adding text labels to tmap plot

I'm trying to add some text labels a tmap plot.

library(tmap)
library(raster)

jnk <- getData("GADM",country="IND",level=2)

map_file <- tm_shape(jnk) +
  tm_polygons() +
  tm_text("NAME_1", remove.overlap = TRUE)

My problem is I'm getting duplicate text when I plot (can't post image since I'm new). I think I might have to group by some sort of geometry and NAME_1 combination but I'm unsure where to go from here.

Any advice would be great!

Upvotes: 10

Views: 8262

Answers (2)

Joke O.
Joke O.

Reputation: 609

The duplicates could be due to using labels that are at a different admin level. You are plotting at admin level 2 but naming them at level 1. That means all admin level 2 areas will have a NAME_1 label as is in the shapefile. One way around this is to download the level shapefile and use that strictly for labelling after plotting.

library(tmap)
library(raster)
## download Level 2 data
jnk <- getData("GADM",country="IND",level=2)
## download Level 1 data
jnk_L1 <- getData("GADM",country="IND",level=1)

map_file <- tm_shape(jnk) + 
tm_polygons(col="lightskyblue1",border.col = "gray70", lwd = 0.02, alpha=0.2) +
 tm_shape(jnk_L1)+tm_borders(col="gray40") + tm_text("NAME_1", remove.overlap = TRUE,size= 0.7) 

## Plot
map_file

Map of India with Level 1  labels

Upvotes: 0

Jindra Lacko
Jindra Lacko

Reputation: 8749

I am not certain what is your problem (as you were unable to post your image) but consider this code:

library(tmap)
library(raster)


jnk <- getData("GADM",country="IND",level=1)

tm_shape(jnk) + tm_polygons("NAME_1", legend.show = F) +
  tm_text("NAME_1", size = 1/2)

I have made some minor changes to your code:

  • downloaded level 1 detail instead of level 2 detail (districts were too numerous, states are OK)
  • removed legend from the tm_polygons() call
  • made the letters of tm_text() smaller (to fit the north-eastern states)

enter image description here

Upvotes: 16

Related Questions