1

Could you please help me with this problem? I want to put a legend title on two lines, and control legend placement in a figure that meets font size and figure size requirements. I am mapping a count variable to political units. Here, hopefully, is a reproducible example, using:

Mac OS 10.14.6; RStudio vers. 2021.09.0, R vers. 4.1.2, tmap vers. 3.3-2

I tried the obvious within tm_fill(). I added a newline to the title text, but the exaggerated line height (space) between the lines of the title is distracting:

library(sf)
library(tmap)
library(tidyverse)
library(RColorBrewer)
set.seed(12345)
shp <- st_read(system.file("shape/nc.shp", package ="sf")) %>% 
  st_transform(shape, crs = 4326) %>%
  mutate(myvar = sample(1:50,100,replace=TRUE)) %>%
  select(myvar)

mymap <- tm_shape(shp) +
   tm_fill(col= "myvar",
            style = "fixed",
            breaks = c(1,10,20,30,40,50), 
            palette = "YlOrRd",
            title = "Number of\nPrograms")+
   tm_layout(legend.position=c("right","top"),inner.margins = c(rep(0.02,3),0.2))

tmap_save(mymap,filename= "NC1.png", width = 180, units="mm")

map 1

Several responses to similar questions regarding ggplot2 suggested using atop() and some additional functions, example.

mymap2 <- tm_shape(shp) +
   tm_fill(col= "myvar",
            style = "fixed",
            breaks = c(1,10,20,30,40,50), 
            palette = "YlOrRd",
            title = expression(atop(textstyle(" \n"),
                                  atop(textstyle("Number of"),
                                       atop(textstyle("Programs")))))) +
   tm_layout(legend.position=c("right","bottom"),legend.title.size = 1.5,inner.margins = c(rep(0.02,3),0.2))

tmap_save(mymap2,filename= "NC2.png", width = 80,units="mm")

map 2

The legend title line height is improved in the RStudio plot window, but not in .png or .pdf output. The new legend placement responds minimally to 'legend.position=' in tm_layout(). As noted in another post 'legend.title.size=' only moves the title higher above the legend, but does not change the title font size.

I also get these warning messages when saving the file:

Warning messages:
1: In grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  :
  font metrics unknown for character 0xa
2: In grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  :
  font metrics unknown for character 0xa
3: In grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  :
  font metrics unknown for character 0xa
4: In grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  :
  font metrics unknown for character 0xa

Could you please help me format this legend, correcting the line height and font size in the legend title, and placing the legend "right","top" in the map area?

Peter Pearman
  • 129
  • 1
  • 10

0 Answers0