R/hotspot_map.R

Defines functions hotspot_map.hspt_s hotspot_map.hspt_ib hotspot_map.hspt_g hotspot_map.hspt_dk hotspot_map.hspt_d hotspot_map.hspt_c hotspot_map.hspt_k hotspot_map.hspt_n hotspot_map_autoplot hotspot_map.sf add_hotspot_caption reject_hotspot_mapping validate_sf_mapping validate_basemap_object hotspot_map

Documented in hotspot_map hotspot_map.hspt_c hotspot_map.hspt_d hotspot_map.hspt_dk hotspot_map.hspt_g hotspot_map.hspt_ib hotspot_map.hspt_k hotspot_map.hspt_n hotspot_map.hspt_s hotspot_map.sf

#' Create an automatic map
#'
#' `hotspot_map()` creates a map from an `sf` object or the result of an
#' sfhotspot analysis using reasonable defaults. Maps include an OpenStreetMap
#' base map by default and are returned as [ggplot2::ggplot] objects, so they
#' can be customised with ggplot2 layers, scales and themes.
#'
#' For an ordinary `sf` object, `mapping` supplies aesthetic mappings for the
#' feature layer and `...` supplies fixed values and other arguments to
#' [ggplot2::geom_sf()]. Hotspot-result objects determine their own aesthetic
#' mappings, so `mapping` cannot be supplied for those classes.
#'
#' @param object An `sf` object or an object returned by an sfhotspot analysis.
#' @param mapping An aesthetic mapping created by [ggplot2::aes()], or `NULL`
#'   for no aesthetic mappings. This argument can be used only for ordinary
#'   `sf` objects, not objects with an `hspt_*` class created by one of the
#'   `hotspot_*()` family of functions.
#' @param ... For ordinary `sf` objects, fixed aesthetics and other arguments
#'   passed to [ggplot2::geom_sf()]. For hotspot-result objects, arguments
#'   passed to the corresponding [ggplot2::autoplot()] method.
#' @param basemap_type A map type passed to the `type` argument of
#'   [ggspatial::annotation_map_tile()], or `"none"` for no base map.
#' @param basemap_zoom The zoom level passed to
#'   [ggspatial::annotation_map_tile()], or `NULL` to choose it automatically.
#' @param basemap_attribution Attribution for the tile provider, or `NULL` to
#'   use the statement known for `basemap_type`. A non-empty string is required
#'   for a custom or otherwise unknown map type.
#' @param caption Additional text to display in the map caption, or `NULL` for
#'   no additional text. Any explanatory caption generated by the plotting
#'   method is retained above this text and the base-map attribution is retained
#'   below it.
#' @param quiet If `TRUE` (the default), suppress progress bars and other
#'   messages. If `FALSE`, show tile-download progress and other messages.
#'
#' @return A [ggplot2::ggplot] object.
#' @examples
#' hotspot_map(memphis_robberies, basemap_type = "none")
#' hotspot_map(
#'   memphis_robberies,
#'   mapping = ggplot2::aes(colour = offense_type),
#'   basemap_type = "none",
#'   caption = "Memphis robberies"
#' )
#' @export
hotspot_map <- function(object, mapping = NULL, ...) {
  UseMethod("hotspot_map")
}

validate_basemap_object <- function(object) {
  validate_sf(object, label = "object", quiet = TRUE)
  bbox <- tryCatch(
    sf::st_bbox(object),
    error = function(cnd) {
      cli::cli_abort(
        c(
          "Cannot determine the bounding box of {.var object}.",
          "i" = "Check that its geometries and co-ordinate reference system are valid.",
          "i" = "Alternatively, use {.code basemap_type = \"none\"}.",
          "x" = conditionMessage(cnd)
        ),
        parent = cnd
      )
    }
  )
  if (
    length(bbox) != 4 ||
      any(!is.finite(bbox)) ||
      bbox[["xmin"]] > bbox[["xmax"]] ||
      bbox[["ymin"]] > bbox[["ymax"]]
  ) {
    cli::cli_abort(c(
      "Cannot add a base map because {.var object} has an invalid bounding box.",
      "i" = "Check for missing, empty or invalid geometries.",
      "i" = "Alternatively, use {.code basemap_type = \"none\"}."
    ))
  }
  invisible(object)
}

validate_sf_mapping <- function(mapping) {
  if (!is.null(mapping) && !inherits(mapping, "uneval")) {
    cli::cli_abort(
      "{.arg mapping} must be created by {.fn ggplot2::aes} or be {.code NULL}."
    )
  }
  mapping
}

hotspot_result_functions <- c(
  hspt_n = "hotspot_count",
  hspt_k = "hotspot_kde",
  hspt_c = "hotspot_classify",
  hspt_d = "hotspot_change",
  hspt_dk = "hotspot_dual_kde",
  hspt_g = "hotspot_gistar",
  hspt_ib = "hotspot_isoband",
  hspt_s = "hotspot_dbscan"
)

reject_hotspot_mapping <- function(mapping, class) {
  if (!is.null(mapping)) {
    producer <- hotspot_result_functions[[class]]
    cli::cli_abort(
      "{.arg mapping} cannot be used when mapping an {.cls {class}} object such as produced by {.fn {producer}}."
    )
  }
  invisible(NULL)
}

add_hotspot_caption <- function(
  plot,
  caption,
  basemap_type,
  basemap_attribution
) {
  if (!is.null(caption)) {
    if (!rlang::is_string(caption) || !nzchar(caption)) {
      cli::cli_abort("{.arg caption} must be a single non-empty string or {.code NULL}.")
    }
    existing_caption <- plot$labels$caption
    attribution <- if (basemap_type == "none") {
      NULL
    } else {
      map_tile_attribution(basemap_type, basemap_attribution)
    }
    if (is.null(existing_caption)) {
      combined_caption <- caption
    } else if (identical(existing_caption, attribution)) {
      combined_caption <- paste(caption, attribution, sep = "\n")
    } else if (
      !is.null(attribution) &&
        endsWith(existing_caption, paste0("\n", attribution))
    ) {
      explanatory_caption <- substr(
        existing_caption,
        1,
        nchar(existing_caption) - nchar(attribution) - 1
      )
      combined_caption <- paste(
        explanatory_caption,
        caption,
        attribution,
        sep = "\n"
      )
    } else {
      combined_caption <- paste(existing_caption, caption, sep = "\n")
    }
    plot <- plot + ggplot2::labs(caption = combined_caption)
  }
  plot + ggplot2::theme(plot.caption = ggplot2::element_text(hjust = 0))
}

#' @rdname hotspot_map
#' @export
hotspot_map.sf <- function(
  object,
  mapping = NULL,
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  validate_sf(
    object,
    label = "object",
    require_crs = rlang::is_string(basemap_type) && basemap_type != "none",
    quiet = TRUE
  )
  mapping <- validate_sf_mapping(mapping)
  sf_layer <- function(object, ...) {
    ggplot2::geom_sf(
      data = object,
      mapping = mapping,
      inherit.aes = FALSE,
      ...
    )
  }
  plot <- build_autoplot(
    object,
    layer_args = list(...),
    basemap_type = basemap_type,
    basemap_zoom = basemap_zoom,
    basemap_attribution = basemap_attribution,
    quiet = quiet,
    layer_function = sf_layer
  ) +
    ggplot2::theme_void()
  add_hotspot_caption(plot, caption, basemap_type, basemap_attribution)
}

hotspot_map_autoplot <- function(
  object,
  mapping,
  class,
  args,
  basemap_type,
  basemap_zoom,
  basemap_attribution,
  caption,
  quiet
) {
  reject_hotspot_mapping(mapping, class)
  plot <- do.call(
    autoplot,
    c(
      list(object),
      args,
      list(
        basemap_type = basemap_type,
        basemap_zoom = basemap_zoom,
        basemap_attribution = basemap_attribution,
        quiet = quiet
      )
    )
  )
  add_hotspot_caption(plot, caption, basemap_type, basemap_attribution)
}

#' @describeIn autoplot.hspt_n Create an automatic map of grid counts.
#' @export
hotspot_map.hspt_n <- function(
  object,
  mapping = NULL,
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_n",
    list(...),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

#' @describeIn autoplot.hspt_k Create an automatic map of kernel-density values.
#' @export
hotspot_map.hspt_k <- function(
  object,
  mapping = NULL,
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_k",
    list(...),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

#' @describeIn autoplot.hspt_c Create an automatic map of hotspot classifications.
#' @export
hotspot_map.hspt_c <- function(
  object,
  mapping = NULL,
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_c",
    list(...),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

#' @describeIn autoplot.hspt_d Create an automatic map of changes in grid counts.
#' @export
hotspot_map.hspt_d <- function(
  object,
  mapping = NULL,
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_d",
    list(...),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

#' @describeIn autoplot.hspt_dk Create an automatic map of dual density values.
#' @export
hotspot_map.hspt_dk <- function(
  object,
  mapping = NULL,
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_dk",
    list(...),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

#' @describeIn autoplot.hspt_g Create an automatic map of Getis-Ord Gi* results.
#' @export
hotspot_map.hspt_g <- function(
  object,
  mapping = NULL,
  critical_p = 0.05,
  sign = c("both", "hot", "cold"),
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_g",
    c(list(critical_p = critical_p, sign = sign), list(...)),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

#' @describeIn autoplot.hspt_ib Create an automatic map of isobands.
#' @export
hotspot_map.hspt_ib <- function(
  object,
  mapping = NULL,
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_ib",
    list(...),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

#' @describeIn autoplot.hspt_s Create an automatic map of DBSCAN clusters.
#' @export
hotspot_map.hspt_s <- function(
  object,
  mapping = NULL,
  col_fill = c("n", "prop", "rank", "none"),
  col_label = "none",
  ...,
  basemap_type = "osm",
  basemap_zoom = NULL,
  basemap_attribution = NULL,
  caption = NULL,
  quiet = TRUE
) {
  hotspot_map_autoplot(
    object,
    mapping,
    "hspt_s",
    c(list(col_fill = col_fill, col_label = col_label), list(...)),
    basemap_type,
    basemap_zoom,
    basemap_attribution,
    caption,
    quiet
  )
}

Try the sfhotspot package in your browser

Any scripts or data that you put into this service are public.

sfhotspot documentation built on Oct. 1, 2026, 1:06 a.m.