How to do a choropleth map with the leaflet library.


0 – Introduction

This page aims to describe how to realise an interactive chloropleth map with the leaflet library of R. Note that you can zoom and hover country to have more information.

First we need to to load the shape file of the world map to know the border position of every country. See graph #168 to have a complete description of this step. We can summarize this step with these 4 lines of code:


The world_spdf object contains the coordinates of the countries borders. It also contains the population size in 2005. You can see it in the world_spdf@data dataframe. With these 2 information we can draw a first basic choropleth map.


1 – Default chloropleth

With these information we can draw a first basic chloropleth map. We first need to create a color palette, and then use addPolygons() to add the shape of all country, with a color representing the number of people in the country. The result is quite disappointing! Since China and India have extremely high population, all the variation between countries is absorbed.. We need to fix that.


And here is the histogram of the population per country. It is a good practice to check this distribution when you make a chloropleth. It helps to understand how your color palette should be implemented.


2 – Change color scale

There are several ways to pass from a numerical variable to palette of color. Leaflet proposes 3 possibilities that are described below: Numerical, Bins and Quantiles.


3 – Custom the chloropleth map

In order to get a quality chloropleth map, there are several improvements we need to apply:

  • Add a legend
  • Find a smart colorscale + use a nice color palette
  • Add a tooltip. When you hover a specific region, a box appears with custom text. This is very handy to add additional information to your map.

And here is the result and the code:





Leave a Reply

Be the First to Comment!

Notify of