Choropleth map using folium and pandas

goofd picture goofd · Jan 8, 2016 · Viewed 7.6k times · Source

I am using folium to create a choropleth map of a set of countries. I am following the documentation. However. for some reason the map doesn't show any shades. I am using the world geojson from natural earth (see the gist).

My dataframe looks like:

>>> spatial_scores.head()

Out[1]:
id  Country Score
PER Peru    2.810300
HND Honduras    2.734521
GUF French Guiana   2.730886
SLV El Salvador 2.473134
CRI Costa Rica  2.454963

The world geojson looks like:

>>> world_json['features'][0]['id']

Out [2]:
u'AFG'

The relevant portions of the choropleth codes are as below:

map1 = folium.Map(location=[-15., -60], zoom_start=4)

map1.geo_json(geo_path=world_json_path,
              data_out='data.json',
              data=spatial_scores,
              columns=['id', 'Score'],
              threshold_scale=[0, 1, 2, 3, 4],
              key_on='features.id',
              fill_color='BuPu', fill_opacity=0.7, line_opacity=0.5,
              legend_name='Score')

map1.create_map('./Scores.html')

However, am not getting any choropleth result and left with just the base country map as below Chorpleth Output

Is there something I am doing wrong?

[Edit]

I figured out the problem. To plot the choropleth I needed to keep only those keys in the geojson which were also in my data frame.

merged = gdf.merge(spatial_scores, left_on='name', right_on='Country')
spatial_gdf = gpd.GeoDataFrame(merged.iloc[:, [0, 1]])
data_df = merged.iloc[:, [2, 3, 4]]

Answer