R/map_ggplot2.R

Defines functions choropleth_ggplot2

Documented in choropleth_ggplot2

#' Map simple feature object using ggplot2
#'
#' @description Takes an object produced by \code{choropleth_sf()}, and creates the correspoding choropleth map.
#'
#' @param sf_object Simple features object. Note that shapefiles consist of more than one file, all with identical basename, which should reside in the same directory.
#' @param value Column to shade the polygons.
#' @param n Number of clusters. Default is 7.
#' @param dig.lab Number of digits in legend. Default is 2.
#' @param legend_title Title of legend.
#'
#' @return ggplot map
#' @export choropleth_ggplot2
#'
#' @import sf
#' @import ggplot2
#' @import viridis
#' @import classInt
#'
#' @author Martin Haringa
#'
#' @examples
#' test <- choropleth_sf(nl_postcode2, insurance, sum(amount, na.rm = TRUE))
#' choropleth_ggplot2(test)
choropleth_ggplot2 <- function(sf_object, value = output, n = 7, dig.lab = 2, legend_title = "Clustering"){

  value <- deparse(substitute(value))
  vector_value <- sf_object[[value]]

  suppressWarnings({
    cluster <- classIntervals(vector_value, n = n, style = 'fisher', intervalClosure = 'right')[[2]]
    sf_object$clustering <- cut(vector_value, breaks = cluster, include.lowest = TRUE, dig.lab = dig.lab)
  })

  output <- ggplot(sf_object) +
    geom_sf(aes(fill = clustering), size = .1, color = "grey85")  +
    coord_sf(datum = NA) +
    scale_fill_viridis_d() +
    theme_void() +
    labs(fill = legend_title)

  return(output)
}
MHaringa/nlmaps documentation built on May 19, 2019, 9:40 p.m.