'change location of scalebar of ggsn package in ggplot

I wanna move scalebar in my plot in r. scalebar(location=bottomright) allows to control the position, but I need to move it from top right to a little upper place. is there any way to do it? scalebar is loaded from ggsn package in r



Solution 1:[1]

You can control the exact position of the scale bar using the anchor argument. By default, when you select location = "topright", the top right hand corner of the scale bar is placed at the top right corner of the map's bounding box. You can specify the exact x and y co-ordinates of the top-right corner of the scale bar in a vector passed to anchor.

If we use an example from the ggsn package:

library(sf)
#> Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE
library(ggsn)
#> Loading required package: ggplot2
#> Loading required package: grid

data(domestic_violence)

domestic_violence <- st_transform(domestic_violence, 4326)

p <- ggplot(domestic_violence, aes(fill = Scaled)) +
  geom_sf() +
  blank() +
  scale_fill_continuous(low = "#fff7ec", high = "#7F0000")

Let us draw the scale bar at the top right:

p + scalebar(domestic_violence, dist = 4, dist_unit = "km",
             transform = TRUE, model = "WGS84",
             location = "topright")

enter image description here

If we want to move it a bit to the West, we simply do:

p + scalebar(domestic_violence, dist = 4, dist_unit = "km",
             transform = TRUE, model = "WGS84",
             location = "topright",
             anchor = c(x = -46.65, y = -23.3563))

enter image description here

Created on 2022-05-18 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Cameron