53

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]]
KT12
  • 549
  • 11
  • 24
goofd
  • 2,028
  • 2
  • 21
  • 33

1 Answers1

1

To plot the choropleth OP needed to keep only those keys in the geojson which were also in the 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]]
0x263A
  • 1,807
  • 9
  • 22
  • 1
    @goofd I was looking at the unaswered questions in the Python tag and this was the top question. I found it a bit silly for the top unanswered question to have an answer that was added in 2016 so I looked [at the meta](https://meta.stackoverflow.com/a/267439/16450169) and followed their advice by simply adding your answer as a community answer. – 0x263A Dec 15 '21 at 20:06