An error occurred while loading the file. Please try again.
-
Grelot Frederic authoredaa603638
#' @title Add an inset within a map
#'
#' @param x should be something of type polygon readable by terra::vect
#' @param scale numeric, how big should be the inset relative to the whole map
#' @param loc character, vwhere to put the inset
#' @param background character, color to be used for the background
#' @param ... some parameters that will be used by terra::plot
#'
#' @return polyVect transformed to be placed somewhere in the map
#'
#' @export
#'
#' @encoding UTF-8
#' @author This is an adaptation of the function inset of the terra package.
#'
#' @examples
#'
#' \dontrun{
#' # To be added (soon)
#' }
add.inset = function (x, scale = 0.2, loc = "", background = "white", ...)
{
e_usr = terra::ext(graphics::par("usr"))
x = try(terra::vect(x))
e = terra::ext(x)
r = (max(c(diff(e_usr[1:2]) / diff(e[1:2]), diff(e_usr[3:4]) / diff(e[3:4]))) * scale)^2
y = terra::rescale(x, f = r)
e = terra::ext(y)
if (loc != "") {
stopifnot(loc %in% c("bottomright", "bottom", "bottomleft",
"left", "topleft", "top", "topright", "right", "center"))
if (grepl("top", loc)) {
dy = e_usr[4] - e[4]
} else if (grepl("bottom", loc)) {
dy = e_usr[3] - e[3]
} else {
dy = (e_usr[3] + diff(e_usr[3:4])/2) - (e[3] + diff(e[3:4])/2)
}
if (grepl("left", loc)) {
dx = e_usr[1] - e[1]
} else if (grepl("right", loc)) {
dx = e_usr[2] - e[2]
} else {
dx = (e_usr[1] + diff(e_usr[1:2])/2) - (e[1] + diff(e[1:2])/2)
}
} else {
dx = e_usr[1] - e[1]
dy = e_usr[4] - e[4]
}
y = terra::shift(y, dx, dy)
e = terra::ext(y)
y = terra::rescale(y, f = .8)
if (!is.na(background)) {
terra::polys(
terra::rescale(terra::as.polygons(e), .9),
col = background,
lty = 1, lwd = 2, border = "lightgray")
}
terra::plot(y, ..., add = TRUE)
invisible(y)
}