Skip to content

Instantly share code, notes, and snippets.

@bleutner
Last active February 23, 2019 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bleutner/08fb0a5a893552b4413bbe02930f722d to your computer and use it in GitHub Desktop.
Save bleutner/08fb0a5a893552b4413bbe02930f722d to your computer and use it in GitHub Desktop.
Scalebar for ggplot2 spatial maps
##
## Example for an entirely non-smart scalebar, which can be added to a ggplot2 object
## Author: Benjamin Leutner (@bleutner)
##
ggScalebar <- function(origin, ## raster object or vector in the form of c(xmin, ymin)
breaks = seq(0, 10000, 1000), ## breaks for the scale bar
yoff = 1000, xoff = 1000, ## position offset from origin in x and y direction (in map units)
sdist = 1000, ## length of major ticks (in map units)
tdist = 1000, ## distance labels to ticks (in map units)
size = 1, ## linewidth of scalebar
alpha = 1, ## transparency of scalebar
distUnit = "km", ## unit label
scaleUnit = 1000, ## scale factor for units (i.e. if map units = m, a scaleUnit of 1000 will result in km )
kmsep=" ", ## character separating last digit and unit 5<kmsep>km
tsize = 3, ## size of labels
col = "black", ## color of scalebar and labels
tinyFact = 0.6, ## size of minor (non-labelled) ticks, relative to major (labelled) ticks
inherit.aes = FALSE ## do not use global aestetics (default=FALSE)
){
breaks <- sort(breaks)
if(inherits(origin, "Raster")){
x <- xmin(origin) + xoff
y <- ymin(origin) + yoff
} else {
x<-origin[1] + xoff
y<-origin[2] + yoff
}
xend <- x + max(breaks)
brx <- x + breaks
kPad = paste0(rep(" ", nchar(distUnit)), collapse = "")
line <- data.frame(x = c(x,xend), y=rep(y,2))
ticks <- data.frame(x = brx, xend = brx, y = c(y-sdist), yend = y)
text <- data.frame(x = brx, y = y - sdist - tdist, lab = paste0(c(rep("",
length(breaks)-1),kPad),
breaks/scaleUnit,
c(rep("", length(breaks)-1),
paste0(kmsep, distUnit))))
tinyticks <- data.frame(
x = ticks$x[-nrow(ticks)] + diff(ticks$x)/2,
xend = ticks$xend[-nrow(ticks)] + diff(ticks$xend)/2,
y = ticks$y[-1] + sdist*tinyFact ,
yend = y
)
list(geom_line(data = line, aes(x = x, y = y), inherit.aes=inherit.aes, alpha = alpha, colour = col, size = size) ,
geom_segment(data = ticks, aes(x = x, xend = xend, y = y, yend = yend),inherit.aes = inherit.aes, alpha = alpha, colour = col, size = size) ,
geom_segment(data = tinyticks, aes(x = x, xend = xend, y = y, yend = yend), inherit.aes = inherit.aes, alpha = alpha, colour = col, size = size) ,
geom_text(data = text, aes(x = x, y = y, label = lab), col = col, size = tsize,alpha = alpha, inherit.aes = inherit.aes))
}
## Example usage
library(RStoolbox)
data(lsat)
ggR(lsat, stretch = "lin") + ggScalebar(lsat, xoff=300, breaks = c(0,5000, 2500), tsize = 4,
sdist = 300, col = "yellow", tdist = 200, size = 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment