Background map in R





This is the background map section of the gallery. It explains how to build static and interactive maps based on different input data, but does not explain how to plot data on it. See other sections for that: choropleth, bubble map, connection map or cartogram. Note that this online course on geospatial data visualization might be helpful for a good overview.

Input format and Package overview

R is an great tool for geospatial data analysis. Heaps of dedicated packages exist. Building a map follows those 2 steps:

Find data, load it in R: region boundaries can be stored in shapefiles or geoJSON files. Some R libraries also provide the data for the most common places. It is also possible to use google map style backgrounds.

Manipulate and plot it: once geo data are loaded in R you get a geospatial object that has specific features. You can manipulate it and plot it with packages like sp or ggplot2

Overview of input data and packages for doing maps in R




The Leaflet package for interactive maps

The leaflet R package is a wrapper of the Javascript leaflet.js library. It allows to build stunning interactive maps in minutes with R. Maps can be exported and standalong html files, or be embeded in a R markdown file or a shiny application. This great online course is dedicated to leaflet.

Leaflet maps are interactive: try to zoom and drag.

See Code





The ggmap package for static maps with background tiles

The ggmap library makes it easy to retrieve raster map tiles from popular online mapping services like Google Maps, OpenStreetMap or Stamen Maps, and plot them using the ggplot2 framework. It produces static maps like these. Click on an image to get the related code snippet.







maps, mapdata and oz to get the most common boundaries

A few libraries provide the most common spatial objects. It avoids the struggle to find the information somewhere on the web. Maps library: Canada, France, Italy, USA and its regions, world cities, NZ. Mapdata library (China, Japan, NZ, World in High resolution) and the oz library (Australia).

See all countries





sf to read shapefiles and .geojson files

If you are not satisfied with the previous options, you can search the web to find the spatial object you need. This information will most likely be stored under one of these two following formats, and can be read with the sf package:







Geospatial data manipulation

Once you've got your geospatial data loaded into R, you are ready to manipulate it. Examples below show how to select a region, how to simplfy the boundaries to get a lighter object, how to compute the region centroids and more.

Related chart types


Map
Choropleth
Hexbin map
Cartogram
Connection
Bubble map