#292 Choropleth map with Folium

Here is an example of a choropleth map made using the Folium library. This example comes directly from the (awesome) documentation of this library. Note that you need 2 elements to build a chloropleth map. i/ A shape file in the geojson format: it gives the boundaries of every zone that you want to represent. ii/ A data frame that gives the values of each zone. You can file the 2 files used to build this example here.

Code



# Import libraries
import pandas as pd
import folium

# Load the shape of the zone (US states)
# Find the original file here: https://github.com/python-visualization/folium/tree/master/examples/data
# You have to download this file and set the directory where you saved it
state_geo = os.path.join('/Users/y.holtz/Desktop/', 'us-states.json')

# Load the unemployment value of each state
# Find the original file here: https://github.com/python-visualization/folium/tree/master/examples/data
state_unemployment = os.path.join('/Users/y.holtz/Desktop/', 'US_Unemployment_Oct2012.csv')
state_data = pd.read_csv(state_unemployment)

# Initialize the map:
m = folium.Map(location=[37, -102], zoom_start=5)

# Add the color for the chloropleth:
m.choropleth(
 geo_data=state_geo,
 name='choropleth',
 data=state_data,
 columns=['State', 'Unemployment'],
 key_on='feature.id',
 fill_color='YlGn',
 fill_opacity=0.7,
 line_opacity=0.2,
 legend_name='Unemployment Rate (%)'
)
folium.LayerControl().add_to(m)

# Save to html
m.save('#292_folium_chloropleth_USA1.html')

 

  • Sponsors

  • 3 comments

    • Pingback: Part 3 – numbers.coffee – Medium | Coding Videos

    • When executing the same code with the same values in jupyter notebook there is no color appears in the map all of the sates are dark grey what could be the possible reason ?

      Reply
      • Hey Ugur, your issue may be in the key_on parameter. Try using feature.properties.”key_on_name” for the argument. For example, I am using a column “NAME” for building a map of county level data where “NAME” is the county. The argument is passed using “key_on = ‘feature.properties.NAME’. This cleared the issue on my map.

        Reply

    Leave a Reply

    Your email address will not be published.