GOAL
Learn how to create an interactive choropleth map using Leaflet.
RESULT
A reactive map, made with Leaflet, that displays Japan’s population distribution and other statistics in a presentable format.
The main purpose of this project was to remember how to use Leaflet in R. I had remembered that I started this project about 2 years ago and could not figure out, for the life of me, how to create an interactive choropleth map.
For some background, I had done static maps before using ggplot2, but I wanted to learn something new and that’s when I stumbled upon Leaflet. In all honesty, the most difficult piece was finding the data to draw the borders of a given area, which I now know is hosted by UC Davis.
If only I knew that a couple of years ago…
Read in the Population Data:
This dataset comes from Japan’s Bureau of Statistics.
It contains data from 2005 and sometimes up to 2020 (depending on what was collected).
The website has a handy search tool to find data somebody might be interested in.
Read in Japan’s geojson data:
This is a relatively new format that was found on the UC Davis website.
It’s basically the coordinates needed to construct borders around Japan’s prefectures.
I’m not entirely sure how the extension works, but it’s like JSON, but for shape files.
Code
OGR data source with driver: GeoJSON
Source: "https://raw.githubusercontent.com/N3uralN3twork/R-Projects/master/Map%20Making/Japan/japanGeoData.geojson", layer: "japanGeoData"
with 47 features
It has 3 fields
[1] "nam" "nam_ja" "id"
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
The first goal is to create an informative popup for each of the prefectures:
Joining together the disparate datasets:
At this point in the notebook, we have two objects:
A borders dataset (geojson)
A population dataset (dataframe)
We need to combine/join them in order to plot anything meaningful.
[1] "id" "Kanji" "Prefecture"
[4] "TotalPop2010" "TotalPop2015" "TotalPop2019"
[7] "TotalPopMale2010" "TotalPopMale2015" "TotalPopMale2019"
[10] "TotalPopFemale2010" "TotalPopFemale2015" "TotalPopFemale2019"
[13] "popup"
This step combines the original borders (geojson) to the data at hand (dataframe).
Creating Japan’s Population Density Map:
The following is based on the Leaflet package, a port of the famous Javascript library.
Code
pal <- colorNumeric("RdYlBu", domain = log10(dfJapan$TotalPop2019), reverse = TRUE)
leaflet(dfJapan) %>%
addTiles() %>%
addPolygons(
fillColor = ~pal(log10(TotalPop2019)),
weight = 2,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 1,
popup = ~popup) %>%
addLegend(pal = pal, values = ~log10(TotalPop2019), opacity = 1.0,
labFormat = labelFormat(transform = function(x) round(10^x)), title = "2019 Tot. Pop. (Log10)")