I'm wondering if it is possible to put a box behind the entire scale including the text in ggspatial's annotation scale? I'm creating a series of maps which have some line polygons and the label often falls along or is cut by a line and it just looks messy.
Example below made using the default sf data. Obviously in this case I would be better off moving the scale to the bottom, but I just made this for illustration purposes, my actual data won't have a "safe" corner and I want to create a whole series of maps without having to individually choose the best location for the scale to be. This also means I don't want to be adding a box I need to manually change the width of depending how large the scales is (maps are a range of scales). For consistency with previous maps I would like to keep the scale within the map borders. Happy to deviate from ggspatial package but struggled to get ggsn to work either and haven't found many other options. Don't want to move away from ggplot.
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5
library(sf)
#> Warning: package 'sf' was built under R version 4.0.5
#> Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1
library(ggspatial)
#> Warning: package 'ggspatial' was built under R version 4.0.5
#default sf package data
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
plt <- ggplot(nc) +
geom_sf()+
coord_sf(crs = st_crs(nc), datum = sf::st_crs(nc),
xlim = c(-81.5,-79.5),
ylim = c(34,36.02) )+
annotation_scale(aes(width_hint = 0.3, location = "tl"))
plt
Created on 2022-07-01 by the reprex package (v0.3.0)
From the docs I have found no option to add something like a background rect to the scale bar. Hence, while that could be a nice feature it would require some effort to add this to
GeomBarScale
. But feel free to add it as a feature request on the package site.As a possible workaround you could add a background rect manually using
ggplot2::annotation_custom
andgrid::rectGrob
. This is not perfect and not sure wether this will work for all your maps. Easy part is to add a background rect for the scale bar. Tricky part is to extend the rect to cover the text label. While the code below works setting thewidth label
depends on the width of the label.Basically the default height of the scale bar is equal to .25cm plus a padding of .25cm, i.e. I choose a height for the rect of 3 * .25cm or
3 * unit(.25, "cm")
. The same for the width, which as far as I get it is by default equal tounit(width_hint, "npc")
plus a default padding of .25cm, i.e. a width ofunit(width_hint, "npc") + 2 * unit(.25, "cm")
. Additionally we have increase the width of the rect to cover the label. To this end I computed the strwidth in inches for a label"60 km"
using the default cex of .7 which I add to rect width. For the cases I tried e.g. I tried also for awidth_hint
of.2
that worked fine. But it will depend on the width of the label.