The new Leaflet package for R is an excellent way to make interactive maps quickly; I’ve written about the package elsewhere. I’ve been experimenting with the package a little more, and I’d like to share a function I’ve written to create an interactive Leaflet choropleth map with data from the World Bank and boundary files from Natural Earth in RStudio - in one line of R code!
The script requires three packages to be installed: rgdal
, WDI
, and leaflet
. The first two can be installed from CRAN with install.packages
, and the third can be installed from GitHub with devtools::install_github("rstudio/leaflet")
.
To get started making your map, first source my script from GitHub with the following command:
source("https://raw.githubusercontent.com/walkerke/teaching-with-datavis/master/wdi-leaflet/wdi_leaflet.R")
Alternatively, download the script yourself from GitHub.
This will give you access to the wdi_leaflet
function that you can use to make your map. The function has five parameters:
indicator
(string, required): The World Bank code for the indicator you want to map; you can get this from http://data.worldbank.org.indicator_alias
(string, optional): Enter the text you want to display for the indicator in the popup. It defaults to “Value”.year
(numeric, optional): Enter the year for which you want to make your map. The default is 2012.classes
(numeric, optional): Enter the number of quantiles you want to use to bin your data. The function default is 5.colors
(string, optional): This parameter takes the ColorBrewer code for the color scheme you’d like to use. The default is “Blues”.As the function only has one required argument, we can run it as such. This command will create a map of countries shaded by the percent of their population that lives in urban areas; it will show in your RStudio viewer.
wdi_leaflet("SP.URB.TOTL.IN.ZS")
Simple as that! If you want, you can customize your map further by using some of the options. This will create a map of life expectancy by country in 1980, with more informative pop-ups, six classes, and a diverging color scheme.
wdi_leaflet("SP.DYN.LE00.IN", "Life expectancy at birth", 1980, 6, "RdYlGn")
Obviously, the maps need legends; the developers at RStudio are working on this and I’ll update the script once they do so. I’m also having some trouble exporting the map to a standalone HTML document - but I’ll post an update here when I get that figured out. For quick exploration of World Bank indicators in RStudio, however, this works great. If you have any comments or questions, contact me on Twitter.