R/plot_map.R

Defines functions plot_map

Documented in plot_map

# Generated by fusen: do not edit by hand


#' Plot map
#'
#' This fonction allows to plot the map created with the extract_map function. It is nessary to use the map_obj, a sf dataframe, contaning at least, a column density_km. The title and the legend can be personnalized.
#' @param map_obj Dataframe. Sf map to plot.
#' @param title Character. Title.
#' @param legend Character. Legend for the color gradient.
#'
#' @importFrom ggplot2 ggplot geom_sf aes coord_sf scale_fill_gradientn geom_point scale_size labs theme element_text element_blank theme_set theme_bw unit
#' @importFrom ggspatial annotation_scale annotation_north_arrow north_arrow_fancy_orienteering
#' @importFrom viridisLite viridis
#' @importFrom sp bbox
#' @importFrom sf as_Spatial
#' @importFrom assertthat assert_that
#'
#' @return ggplot object. The study area with the gradient of density (ind/km2).
#' @export 


#' @examples
#' 
#' data(dataset_density)
#' 
#' map <- extract_map(density_obj = dataset_density,
#'                    N = 500,
#'                    crs = 2154)
#' 
#' plot_map(map_obj = map)
#' 
plot_map <- function(map_obj, legend = "Density (ind/km2)", title = ""){
  
  # Function checks
  
  
  assert_that(inherits(map_obj, "sf"))
  if (!all(c("density_km") %in% names(map_obj))) {stop("map_obj must contain `density_km` column. Verify your column names.")}
  assert_that(is.numeric(map_obj$density_km))
  
  
  # Function 
  
  theme_set(theme_bw())
  
  xlim <- bbox(as_Spatial(map_obj))[1, ]
  ylim <- bbox(as_Spatial(map_obj))[2, ]
  
  ggplot() +
    geom_sf(data = map_obj, aes(fill = density_km), color = NA) +
    scale_size(name = "Nb ind", breaks = 0:3) +
    coord_sf(xlim = xlim, ylim = ylim) +
    annotation_scale(location = "br", width_hint = 0.5) +
    annotation_north_arrow(location = "tr",
                           which_north = "true",
                           height = unit(0.8, "cm"),
                           width = unit(0.8, "cm"),
                           pad_x = unit(0.2, "cm"),
                           pad_y = unit(0.1, "cm"),
                           style = north_arrow_fancy_orienteering) +
    scale_fill_gradientn(name = legend,
                         colors = viridis(256)) +
    theme(legend.position = "right",
          legend.key.width = unit(0.5, "cm"),
          plot.title = element_text(lineheight = 0.8, face = "bold"),
          axis.text = element_text(size = 6),
          axis.title.x = element_blank(),
          axis.title.y = element_blank())
}
maudqueroue/intercali documentation built on Oct. 8, 2022, 2:09 p.m.