Skip to content

Instantly share code, notes, and snippets.

@idshklein
Created November 5, 2020 07:21
Show Gist options
  • Save idshklein/c447204d113adeed3ec406544da3475b to your computer and use it in GitHub Desktop.
Save idshklein/c447204d113adeed3ec406544da3475b to your computer and use it in GitHub Desktop.
making map inset with ggplot
library(sf)
library(tidyverse)
library(patchwork)
nc = st_read(system.file("shape/nc.shp", package="sf"))
box <- nc %>% st_bbox()
minify_box <- function(bbox, ratio = 0.5){
if(class(bbox) != "bbox"){
stop("bbox must be a bbox object")
}
if(class(ratio) != "numeric" ){
stop("ratio must be numeric")
}
if(!(ratio > 0 & ratio < 1)){
stop("ratio must be between 0 and 1")
}
xrange = bbox[["xmax"]] - bbox[["xmin"]]
yrange = bbox[["ymax"]] - bbox[["ymin"]]
xportion = xrange*ratio
yportion = yrange*ratio
xoffset = (xrange - xportion)/2
yoffset = (yrange - yportion)/2
xmin = bbox[["xmin"]] + xoffset
xmax = bbox[["xmin"]] + xrange - xoffset
ymin = bbox[["ymin"]] + yoffset
ymax = bbox[["ymin"]] + yrange - yoffset
bbox[["xmin"]] = xmin
bbox[["xmax"]] = xmax
bbox[["ymin"]] = ymin
bbox[["ymax"]] = ymax
return(bbox)
}
minified_box <- minify_box(box,.1) %>% st_as_sfc()
p <- ggplot(nc) +
geom_sf()
pyrange = layer_scales(p)$y$range$range
yexpand = diff(pyrange) * 0.05
pxrange = layer_scales(p)$x$range$range
xexpand = diff(pxrange) * 0.05
bbox <- minified_box %>% st_bbox()
p1 <- p +
geom_sf(data = minified_box,fill = NA,color = "red") +
geom_segment(aes(x = bbox[["xmax"]],y = bbox[["ymin"]],xend = pxrange[2]+xexpand,yend = pyrange[1]-yexpand),color = "red") +
geom_segment(aes(x = bbox[["xmax"]],y = bbox[["ymax"]],xend = pxrange[2]+xexpand,yend = pyrange[2]+yexpand),color = "red") +
theme(plot.margin = margin(0,0,0,0)) +
coord_sf(xlim = pxrange,ylim = pyrange)
p2 <- p +
coord_sf(xlim = c(bbox[["xmin"]],bbox[["xmax"]]),ylim = c(bbox[["ymin"]],bbox[["ymax"]]),,label_graticule = "SE") +
theme(panel.border = element_rect(colour = "red", fill=NA, size=1),plot.margin = margin(0,0,0,0))
p1+p2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment