Archives de catégorie : R-EN

Blog posts in english

The mapsf package

 mapsf has just landed on CRAN.

mapsf helps to design various cartographic representations such as proportional symbols, choropleth or typology maps. It also offers several functions to display layout elements that improve the graphic presentation of maps (e.g. scale bar, north arrow, title, labels). mapsf maps sf objects on base graphics.

This package has a website  and a vignette.

Ce post est disponible en français ici.

Continuer la lecture de The mapsf package

The potential package

The potential package provides functions to compute potential models as defined by John Q. Stewart. Several options are available to customize the models, for example it is possible to refine the distance friction functions or to use custom distance matrices. Some functions use parallelization to improve their efficiency.

The aim of potential is to replace potential-related functions of the SpatialPosition package. SpatialPosition was built to compute 3 spatial position models (Stewart potentials, Reilly catchment areas, Huff catchment areas) in a time where sf was not published yet (May 2015).  potential functions use a simplified interface and are more efficient than their counterpart in SpatialPostion. My recommendation to SpatialPositon users is thus to switch to potential for the computation of potentials.  

A didactic vignette describing the methodology and functions is provided as well as a website.

The maptiles package

To create maps from tiles, maptiles downloads, composes and displays tiles from a large number of providers (e.g. OpenStreetMap, Stamen, Esri, CARTO, or Thunderforest).


You can install the released version of maptiles from CRAN with:


You can install the development version of maptiles from GitHub with:

# install.packages("remotes")

Note: maptiles uses terra which requires a recent version of GDAL (>= 3.0.4).


This is a basic example which shows you how to dowload and display OpenStreetMap tiles over North Carolina:

# import North Carolina counties
nc <- st_read(system.file("shape/nc.shp", package="sf"), 
              quiet = TRUE)
# dowload tiles and compose raster (SpatRaster)
nc_osm <- get_tiles(nc, crop = TRUE)
# display map
# add Norh Carolina counties
plot(st_geometry(nc), col = NA, add = TRUE)
# add credit
mtext(text = get_credit("OpenStreetMap"), 
      side = 1, line = -1, adj = 1, cex = .9, 
      font = 3)

maptiles gives access to a lot of tiles servers, but it is possible to add others. The following example demonstrates the setting of a map tiles server and how to cache the original tiles for future use:

# define the query
fullserver <- paste(
  sep = "/"
# define the tile server parameter
esri <-  list(
  src = 'esri',
  q = fullserver,
  sub = NA,
  cit = 'Tiles: Esri; Copyright: 2012 DeLorme'
# dowload tiles and compose raster (SpatRaster)
nc_esri <- get_tiles(x = nc, provider = esri, crop = TRUE, 
                     cachedir = tempdir(), verbose = TRUE)
# display map
# display credits
mtext(text = esri$cit, side = 1, line = -1, 
      adj = 1, cex = .9, font = 3)

The following figure shows mini maps for most of the tiles providers available:

Attribution of map tiles

All maps available through maptiles are offered freely by various providers. The only counterpart from the user is to properly display an attribution text on the maps. get_credit() displays a short credit text to add on each map using the downloaded tiles.


Most of maptilescode comes from getTiles() and tilesLayer() functions in cartography. It appears useful to me to have a package focused on the download and display of map tiles only. On the technical side, it uses terra instead of raster for managing raster data.


There are many alternative packages that pursue the same objective as maptiles. Some focus on a specific map tiles provider (e.g. mapbox, google, OpenStreetMap) or on a specific graphics device (ggplot2). The goal of maptiles is to be flexible enough to allow the use of different providers and to have a minimal number of robust and modern dependencies. However, depending on the use case, one of following packages may better suit your needs:


Not to be confused with tilemaps, that “implements an algorithm for generating maps, known as tile maps, in which each region is represented by a single tile of the same shape and size.”

New version of cartography

A new version of the cartography package (v2.4.0) has arrived on CRAN.

New Features

  • waffleLayer() plots a “waffle map”. This kind of representation allows to plot several quantities on the same map.
  • ghostLayer() is a short function that plot an invisible layer with the extent of a spatial object. This function is useful to initiate a map with a specific extent.
mtq <- st_read(system.file("gpkg/mtq.gpkg",
package="cartography")) target <- mtq[30, ] ghostLayer(target) plot(st_geometry(mtq), col = "gold2", add = TRUE)

These 3 functions are well described by their creator, Diego Hernangómez, on his blog.


getTiles() gets map tiles from various tile servers.

  •  The function has gained caching capacities (through cachedir and forceDownload arguments). Users can now cache tiles in a folder and reuse them across R sessions.
  • More than 50 tile servers have been included and other can be added by users.
  •  It is possible to use Thunderforest tiles with an API key.
click here to see the figure in a better resolution

The barscale() function plots a scale bar on a map, a new unit argument has been added to plot the scale bar in meters, kilometers or miles.

Under the Hood

cartography does not use rosm anymore to import map tiles. The package is working great but its maintainer, Dewey Dunnington, suggests that it will not evolve much and that other package will appear to replace it. Thus we have decided to use slippymath and internal code to download tiles. A (positive) side effect of this replacement is a decrease in the indirect dependancies of cartography.

cartography appears to be robust to the changes introduced by the last sf version (v0.9). This version takes into account the new representation of coordinate reference systems proposed by GDAL and PROJ. More information on this here.

How to interactively position legends and layout elements on a map with cartography

In cartography several functions have a pos or legend.pos argument. These arguments can take the following values: “topleft”, “top”, “topright”, “right”, “bottomright”, “bottom”, “bottomleft”, “bottomleftextra”, “left” or a vector of two coordinates in map units (c(x, y)).

The posibility to use a vector of coordinates is useful for placing an element at a precise location: Continuer la lecture de How to interactively position legends and layout elements on a map with cartography

The popcircle package

The popcircle package has been released on GitHub. This one-function package computes circles with areas scaled to a variable and displays them using a compact layout (higher values in the center, lower values at the periphery). Original polygons are scaled to fit inside these circles (size are roughly proportional, not strictly).

The circles creation relies on packcircles, spatial data manipulation relies on sf.

Continuer la lecture de The popcircle package

The tanaka package

The tanaka package has been released on CRAN. This package is a simplified implementation of the Tanaka method.
Also called “relief contours method”, “illuminated contour method” or “shaded contour lines method”, the Tanaka method enhances the representation of topography on a map using shaded contour lines.
North-west white contours represent illuminated topography and south-east black contours represent shaded topography.

The contour lines creation relies on isoband, spatial data manipulation and display rely on sf.

tanaka is a small package with only two functions:

  • tanaka() uses a raster object and displays the map directly;
  • tanaka_contour() builds the isopleth polygon layer.

This is a typical example of the package usage based on the dataset shipped with the package.

ras <- raster(system.file("grd/elev.grd", 
                          package = "tanaka"))
tanaka(x = ras, breaks = seq(80,400,20), 
       legend.pos = "topright", 
       legend.title = "Elevation\n(meters)")

In the second example, the elevatr package is used to download an elevation raster on a specific area. Then the tanaka_contour() function is used to create an isopleth layer and finally the tanaka()function is used to to display the map with a custom color palette.

# use elevatr to get elevation data
ras <- get_elev_raster(
  locations = data.frame(
    x = c(6.7, 7), y = c(45.8,46)
  z = 10, prj = "+init=epsg:4326", 
  clip = "locations"
# create the isopleth layer
iso <- tanaka_contour(
  x = ras, 
  breaks = seq(500,4800,250)
# display the isopleth layer
# create a custom color palette
pal <- colorRampPalette(colors = c("#F9D3A1", "#1E315B"))
# display the map
tanaka(iso, col = pal(nrow(iso)))

The last example illustrates the use of tanaka with non-topographical data. This map is based on the Global Human Settlement Population Grid (1km).

Code for this figure

Shaded contour lines or Tanaka method with R

[edit]The tanaka package, released after this post, facilitates the creation of such maps[/edit].

The following post, Tanaka method or how to make shaded contour lines on blog, explains clearly and thoroughly what shaded contour lines are and how to draw them with QGIS.
How hard would it be to implement this method with R?


Continuer la lecture de Shaded contour lines or Tanaka method with R

Cartographic Explorations of the OpenStreetMap Database with R

This post exposes some cartographic explorations of the OpenStreetMap (OSM) database with R.
These explorations begin with the downloading and the cleaning of OSM data. Then I propose a set of map visualizations of the spatial distributions of bars and restaurants in Paris. Of course, these examples could be adapted to other spatial contexts and thematics (e.g. pharmacies in Roma, bike parkings in Dublin…).

This reproducible analysis is hosted on GitHub (code + data + walk-through).

Continuer la lecture de Cartographic Explorations of the OpenStreetMap Database with R

New version of the cartography package

A new version of the cartography package (v2.0.1) has arrived on CRAN.

cartography allows various cartographic representations such as proportional symbols, chroropleth, typology, flows or discontinuities maps. It also offers several features enhancing the graphic presentation of maps like cartographic palettes, layout elements (scale, north arrow, title…), labels, legends or access to some cartographic APIs.

Up to version 1.4.2 cartography was mainly based on sp and rgeos for its spatial data management and geoprocessing operations. These dependencies have been as much as possible replaced by sf functions since version 2.0.0.
Most functions are kept unchanged except for the addition of an x argument used to take sf objects as inputs.
See the NEWS file for the full list of changes and see sf README in case of installation problems with sf.
Continuer la lecture de New version of the cartography package

Create and integrate maps in your R workflow with the cartography package

The cartography package allows various cartographic representations such as proportional symbols, chroropleth, typology, flows or discontinuities. In addition it also proposes some useful features like cartographic palettes, layout (scale, north arrow, title…), labels, legends or access to cartographic API to ease the graphic presentation of maps. Continuer la lecture de Create and integrate maps in your R workflow with the cartography package