Search code examples
rspatialr-sftmap

How to move the compass arrow and scale bar off of the plot when using tmap in R?


I am using the tmap package to plot some data on a map. Because of the size of the datasets, you can download the needed ones here (they are public datasets). This code uses the .csv and .shp files in the drive.

I need to move the compass and the scale bar off of the image and below my legends. How can I do this? I haven't seen that the tm_compass command has an option to move it outside of the image, so is there another way of doing this?

Code:

#Load packages
library(pacman)
p_load(sf, tidyverse, ggspatial, tmap, ggplot2)

#Read data
boundary <- st_read('US_tract_2010.shp')
food <- read.csv('FoodAtlas.csv')

#Join data together
boundary$GEOID10 <- as.numeric(boundary$GEOID10)
foodleft <- left_join(boundary, food, by = c('GEOID10' = 'CensusTract'))


#Construct the graph
ks <- foodleft %>%
  select(State, County, TractLOWI, LAhalfand10) %>% 
  filter(State %in% c('Kansas'))

ks$LAhalfand10 <- as.factor(ks$LAhalfand10)

tmap_mode("plot")

qtm(ks, 
    fill = "LAhalfand10",
    fill.title = "LAhalfand10") +
  tm_bubbles("TractLOWI", col = "steelblue", title.size = "TractLOWI (Pop)") +
  tm_layout(legend.outside = TRUE, frame = FALSE) +
  tm_compass(size = 3, type = 'rose', position = c("right","top")) +
  tm_scale_bar(size = 0.5, position = c("RIGHT", "BOTTOM"))

The resulting graph is produced. However, I need to move the compass and the scale bar as indicated in the image below:

enter image description here


Solution

  • You can also use inner margins to place legends and attributes outside.

    example

    data(World)
    qtm(World, 
        fill = "economy") +
        tm_layout(inner.margins = c(0.02, 0.02, 0.02, 0.3)) +
        tm_compass(size = 3, type = 'rose') +
        tm_scale_bar(size = 0.5)
    

    (This will be different (easier) in tmap4)