I have made a RGB composite image of a satellite image using ggRGB()
from the RStoolbox package. I would like to add a scale bar to the image, but I'm stumped as to how to do this. I would usually use scalebar()
from the ggsn package when working with ggmaps()
in R, but it doesn't look like it can handle a RasterBrick object as input like like is required for ggRGB()
.
Here is an example:
library(raster)
library(ggplot2)
library(RStoolbox)
data(lsat)
ggRGB(img = lsat,
r = 3,
g = 2,
b = 1,
stretch = 'hist') +
blank() # eliminate x and y axes
This produces the following image:
I would like to add a scale bar in the upper right corner. Here's what I tried:
ggRGB(img = lsat,
r = 3,
g = 2,
b = 1,
stretch = 'hist') +
blank() +
ggsn::scalebar(lsat, dist = 2, dist_unit = "km",
transform = TRUE, model = "WGS84", location = "upperright")
This returns an error: "Error in .local(x, ...) : invalid layer names"
Any help would be much appreciated. I'd like to stick with ggRGB()
if possible, but I'd be open to other plotting methods if I can place a scale bar on the image.
You could use package ggspatial
ggRGB(img = lsat,
r = 3,
g = 2,
b = 1,
stretch = 'hist') +
theme_void() +
ggspatial::annotation_scale(location = "tr", width_hint =0.5, pad_x = unit(0.7, "cm"))
If you want more fine control over the appearance, a slightly more verbose but highly customizable method is also given in this answer https://stackoverflow.com/a/39069955/2761575