add_categorical_legend function

Add a categorical legend to a Mapbox GL map

Add a categorical legend to a Mapbox GL map

This function adds a categorical legend to a Mapbox GL map. It supports customizable colors, sizes, and shapes for legend items.

add_categorical_legend( map, legend_title, values, colors, circular_patches = FALSE, position = "top-left", unique_id = NULL, sizes = NULL, add = FALSE, width = NULL, layer_id = NULL, margin_top = NULL, margin_right = NULL, margin_bottom = NULL, margin_left = NULL )

Arguments

  • map: A map object created by the mapboxgl function.
  • legend_title: The title of the legend.
  • values: A vector of categories or values to be displayed in the legend.
  • colors: The corresponding colors for the values. Can be a vector of colors or a single color.
  • circular_patches: Logical, whether to use circular patches in the legend. Default is FALSE.
  • position: The position of the legend on the map. One of "top-left", "bottom-left", "top-right", "bottom-right". Default is "top-left".
  • unique_id: A unique ID for the legend container. If NULL, a random ID will be generated.
  • sizes: An optional numeric vector of sizes for the legend patches, or a single numeric value. If provided as a vector, it should have the same length as values. If circular_patches is FALSE (for square patches), sizes represent the width and height of the patch in pixels. If circular_patches is TRUE, sizes represent the radius of the circle.
  • add: Logical, whether to add this legend to existing legends (TRUE) or replace existing legends (FALSE). Default is FALSE.
  • width: The width of the legend. Can be specified in pixels (e.g., "250px") or as "auto". Default is NULL, which uses the built-in default.
  • layer_id: The ID of the layer that this legend is associated with. If provided, the legend will be shown/hidden when the layer visibility is toggled.
  • margin_top: Custom top margin in pixels, allowing for fine control over legend positioning. Default is NULL (uses standard positioning).
  • margin_right: Custom right margin in pixels. Default is NULL.
  • margin_bottom: Custom bottom margin in pixels. Default is NULL.
  • margin_left: Custom left margin in pixels. Default is NULL.

Returns

The updated map object with the legend added.

Examples

## Not run: library(mapboxgl) map <- mapboxgl( center = c(-96, 37.8), zoom = 3 ) map %>% add_categorical_legend( legend_title = "Population", values = c("Low", "Medium", "High"), colors = c("#FED976", "#FEB24C", "#FD8D3C"), circular_patches = TRUE, sizes = c(10, 15, 20), width = "300px" ) ## End(Not run)
  • Maintainer: Kyle Walker
  • License: MIT + file LICENSE
  • Last published: 2025-03-18