Learn R Programming

insetplot (version 1.4.0)

insetplot-package: insetplot: Compose ggplot2 maps with insets

Description

insetplot lets you create ggplot2 maps with inset maps easily and flexibly. It handles spatial configuration, aspect ratios, and plot composition automatically.

Arguments

Core workflow

  1. Build a configuration with config_insetmap and inset_spec by specifying necessary parameters (position and size).

  2. Pass your ggplot object to with_inset to generate the composed figure.

  3. Save the final plot with ggsave_inset to maintain correct aspect ratio.

Main functions

  • inset_spec: Define bbox, position (loc or loc_left/loc_bottom), and size (prefer scale_factor; or provide one of width/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 from with_inset, with optional ratio_scale for 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( bbox = st_bbox(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( bbox = st_bbox(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]

See Also

inset_spec, config_insetmap, with_inset, ggsave_inset, map_border, last_insetcfg