Choropleth map is an extremely effective way to exhibit geospatial information, usually uses color to express the intensity of that information. In this notebook, we are going to show you three Python libraries that can help you make beautiful Choropleth map.
#We first import some basis libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
import re
In this project, we use Taiwan as the geographical target along with population data acquired from Taiwanese goverment. The 2020 data shows the population distribution by age group and total population of administrative division in Taiwan. We will first clean and transform this dataset so that we can use it in later process. You can find the dataset in this website.
def clean_county(text):
"""
This function transformed two similar Chinese characters into consistent one
Input: Original text
Output: Transformed text
"""
text = ''.join(text.split(' '))
if '臺' in text:
text = re.sub('臺','台',text)
return text
def clean_population(text):
"""
This function cleans the population column and turn it into numerical column
Input: Text containing population information
Output: Transformed numerical information of population
"""
text = int(''.join(text.strip().split(',')))
return text
#First read the original dataset
Dataset = pd.read_csv("POPULATION.csv",encoding='Big5')
Dataset = Dataset.iloc[6:,0:3]
Dataset.columns = ['City/County','Group',"Population"]
Dataset = Dataset[Dataset['Group'] == ' 計 ']
#Rearrange dataframe (Due to original dataset problem)
for i in range(Dataset.shape[0]):
if i != Dataset.shape[0]-1:
Dataset.iloc[i, 0] = Dataset.iloc[i+1, 0]
else:
Dataset.iloc[i, 0] = '連江縣'
#Apply cleaning function on columns
Dataset['City/County'] = Dataset['City/County'].map(clean_county)
Dataset["Population"] = Dataset["Population"].map(clean_population)
#Get rid of useless data
Dataset = Dataset[Dataset['City/County'] != '台灣省']
Dataset = Dataset.drop(columns = ['Group'])
Dataset
Geojson is essential for the plotting Choropleth map because it records the actual outline of specific area. Therefore, you can manipulation the map using information you wish to convey. This step show how I retrieve Geojson data from Github. You can try to search your location of interest on the internet.
#Import modules for acquiring geojson
from urllib.request import urlopen
import json
#Import geojson from Github
with urlopen('https://raw.githubusercontent.com/g0v/twgeojson/master/json/twCounty2010.geo.json') as response:
geo_taiwan = json.load(response) #Collect geojson data from Github
#Update current administrative division information
for i in range(len(geo_taiwan['features'])):
if geo_taiwan['features'][i]['properties']['COUNTYNAME'] == "桃園縣":
geo_taiwan['features'][i]['properties']['COUNTYNAME'] = "桃園市"
geo_taiwan['features'][i]['properties']['name'] = "桃園市"
#import folium
import folium
#Creaate a map object for choropleth map
#Set location to your location of interest (latitude and longitude )
map0 = folium.Map(location=[23.9,121.52], zoom_start=7)
#Create choropleth map object with key on TOWNNAME
folium.Choropleth(geo_data = geo_taiwan,#Assign geo_data to your geojson file
name = "choropleth",
data = Dataset,#Assign dataset of interest
columns = ["City/County","Population"],#Assign columns in the dataset for plotting
key_on = 'feature.properties.name',#Assign the key that geojson uses to connect with dataset
fill_color = 'YlOrRd',
fill_opacity = 0.7,
line_opacity = 0.5,
legend_name = 'Taiwan').add_to(map0)
#Create style_function
style_function = lambda x: {'fillColor': '#ffffff',
'color':'#000000',
'fillOpacity': 0.1,
'weight': 0.1}
#Create highlight_function
highlight_function = lambda x: {'fillColor': '#000000',
'color':'#000000',
'fillOpacity': 0.50,
'weight': 0.1}
#Create popup tooltip object
NIL = folium.features.GeoJson(
geo_taiwan,
style_function=style_function,
control=False,
highlight_function=highlight_function,
tooltip=folium.features.GeoJsonTooltip(
fields=['COUNTYNAME'],
aliases=['City/County'],
style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;")))
#Add tooltip object to the map
map0.add_child(NIL)
map0.keep_in_front(NIL)
folium.LayerControl().add_to(map0)
map0