add.inset.R 1.96 KB
Newer Older
Grelot Frederic's avatar
Grelot Frederic committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#' @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)
}