How to do a choropleth map with the leaflet library.


0 – Introduction

This page aims to describe how to realise an interactive choropleth 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 choropleth

With these information we can draw a first basic choropleth 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 choropleth. 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 offers 3 possibilities that are described below: Numerical, Bins and Quantiles.


3 – Custom the choropleth map

In order to get a quality choropleth 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

4 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
2 Comment authors
nsnrDi Deng Recent comment authors
newest oldest most voted
Notify of

In reply to the two mentions of the last paragraph not working (highlight function):
replace the line #14 (fillColor = ~mypalette(POP…) with
fillColor = ~mypalette(POP2005), weight=0.3, color=”white”, dashArray = “”, fillOpacity = 0.9, stroke = TRUE,
I’m new to R so I can’t explain why the dashArray needs to be present, but it works for me.


[…] was trying out the codes on R graph gallery. But the last section (the most important section) did not give me anything. Is there anything wrong […]

Di Deng
Di Deng

I don’t know what is wrong, but the last section does not work on my computer. It does not generate any map like shown above.