zadrozny
zadrozny

Reputation: 1731

Passing a geopandas data frame to `folium.Choropleth` (map renders gray)

I'm trying to make a Choropleth map from a GeoPandas data frame, rather than from a geojson file containing only geometry plus a pandas dataframe containing statistical data. Specifically, I would like to adapt this example, merging the shapefiles for US states with another dataset containing their respective unemployment numbers into a single GeoPandas data frame (merged), and then rendering it with folium.Choropleth.

enter image description here

The folium documentation says that the geo_data parameter can be a geopandas object. When I pass the geopandas_data_frame.geometry to it, the map renders. However, when I pass merged["Unemployment"] to the data parameter, each state renders in blue, despite the fact that the numbers vary.

m = folium.Map(location=[48, -102], zoom_start=3)

folium.Choropleth(
    geo_data=merged,
    name='choropleth',
    data=merged["Unemployment"],
    fill_color='YlGn',
    fill_opacity=0.7,
    line_opacity=1,
    legend_name='Unemployment Rate (%)'
).add_to(m)

folium.LayerControl().add_to(m)
m

Broken folium.Choropleth map

I have tried changing the data type of merged["Unemployment"] from float to int to str, as per this question.

Upvotes: 2

Views: 870

Answers (1)

rsanchezavalos
rsanchezavalos

Reputation: 71

Folium uses GeoJSON objects to plot the geometries (the geo_data param). You can use the geopandas but you'll have to convert it in the function call.

folium.Choropleth(geo_data=merged.to_json(),
                  name='choropleth',
                  data=merged,
                  columns=["id", "Unemployment"],
                  fill_color='YlGn',
                  fill_opacity=0.7,
                  line_opacity=1,
                  key_on="feature.properties.id",
                  legend_name='Unemployment Rate (%)').add_to(m)

The key_on parameter is the tricky one, it has to match the structure of the merged.to_json() file, just print it and check.

Upvotes: 3

Related Questions