3

How do I fix vertical space issues in tmap legends, like the ones shown in the linked base R example? (Vertical spaces in legend; y.intersp is not a recognized parameter by tmap_add_legend())

Basic tmap code:

library(sf)
library(tmap)
tm_shape(st_read(system.file('shape/nc.shp', package = 'sf'))) + 
  tm_polygons() + 
  tm_add_legend(
    type = 'symbol', 
    labels = c('Variable A', 'Variable B', 'Variable C', 'Variable D', 'Variable E'), 
    col = c('#832424FF', 'rosybrown4', 'red', 'red', '#4F8DC2'),
    shape = c(19, 19, 4, 5, 15)
  ) 
Kim
  • 4,080
  • 2
  • 30
  • 51
dad
  • 1,335
  • 9
  • 28

1 Answers1

3

I couldn't quite find the legend-item padding as you requested, but if it serves your purpose, you can adjust size and legend.text.size a bit.

If you want to put padding between the words but don't mind the legend icons looking bigger/still close together,

s <- st_read(system.file('shape/nc.shp', package = 'sf'))
tm_shape(s) + 
tm_polygons() + 
tm_add_legend(
    type = 'symbol', 
    labels = c('Variable A', 'Variable B', 'Variable C', 'Variable D', 'Variable E'), 
    col = c('#832424FF', 'rosybrown4', 'red', 'red', '#4F8DC2'),
    shape = c(19, 19, 4, 5, 15), 
    size = 1.2
) + 
tm_layout(legend.text.size = 0.8)

If you want to put padding between legend icons but distance between text labels are okay,

tm_shape(s) + 
tm_polygons() + 
tm_add_legend(
    type = 'symbol', 
    labels = c('Variable A', 'Variable B', 'Variable C', 'Variable D', 'Variable E'), 
    col = c('#832424FF', 'rosybrown4', 'red', 'red', '#4F8DC2'),
    shape = c(19, 19, 4, 5, 15), 
    size = 0.5
) + 
tm_layout(legend.text.size = 1.0)

I hope somebody finds a better option that can adjust both paddings, but this may serve your purpose in the meantime.

Kim
  • 4,080
  • 2
  • 30
  • 51