insetplot lets you create ggplot2 maps with inset maps easily and flexibly. It handles spatial configuration, aspect ratios, and plot composition automatically.
Core workflow
Build a configuration with
config_insetmapandinset_specby specifying necessary parameters (position and size).Pass your
ggplotobject towith_insetto generate the composed figure.Save the final plot with
ggsave_insetto maintain correct aspect ratio.
Main functions
inset_spec: Define bbox, position (locorloc_left/loc_bottom), and size (preferscale_factor; or provide one ofwidth/height).config_insetmap: Create and store the configuration.with_inset: Crop each subplot, compose subplots and calculate sizes and positions automatically.ggsave_inset: Save with the correct aspect ratio derived fromwith_inset, with optionalratio_scalefor fine-tuning.
Example
library(sf)
library(ggplot2)
library(insetplot)
nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
# Approach 1: shared base plot for all subplots
config_insetmap(
data_list = list(nc),
specs = list(
inset_spec(main = TRUE),
inset_spec(
xmin = -84, xmax = -75, ymin = 33, ymax = 37,
loc = "left bottom", scale_factor = 0.5
)
)
)
base_map <- ggplot(nc, aes(fill = AREA)) +
geom_sf() +
scale_fill_viridis_c() +
guides(fill = "none") +
theme_void()
p <- with_inset(base_map)
# Approach 2: provide custom plots in each spec
config_insetmap(
data_list = list(nc),
specs = list(
inset_spec(main = TRUE, plot = base_map),
inset_spec(
xmin = -84, xmax = -75, ymin = 33, ymax = 37,
loc = "left bottom", scale_factor = 0.5,
plot = base_map + ggtitle("Detail")
)
)
)
p <- with_inset() # plot argument is optional here
# Save with the correct aspect ratio
ggsave_inset("map.png", p, width = 10)Author
Maintainer: Chao Kong kongchao1998@gmail.com (ORCID) [copyright holder]