Search code examples
pythonplotlyplotly-dashgeopandas

TypeError: 'MultiPolygon' object is not iterable


I am trying to run the below script from plotly: https://plotly.com/python/county-choropleth/

I'm receiving the error code right out the gate: TypeError: 'MultiPolygon' object is not iterable

I've looked up several posts where this is a similar issue, but I'm skeptical these are solutions for this particular issue. OPTION 2 seems like the more likely approach, but why would there be a workaround for simple coding that plotly is publishing? Seems I might be missing something in the way the code is written.

OPTION 1: 'Polygon' object is not iterable- iPython Cookbook

OPTION 2: Python: Iteration over Polygon in Dataframe from Shapefile to color cartopy map

import plotly.figure_factory as ff

import numpy as np
import pandas as pd

df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv')
df_sample_r = df_sample[df_sample['STNAME'] == 'Florida']

values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()

endpts = list(np.mgrid[min(values):max(values):4j])
colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0",
              "#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"]
fig = ff.create_choropleth(
    fips=fips, values=values, scope=['Florida'], show_state_data=True,
    colorscale=colorscale, binning_endpoints=endpts, round_legend_values=True,
    plot_bgcolor='rgb(229,229,229)',
    paper_bgcolor='rgb(229,229,229)',
    legend_title='Population by County',
    county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
    exponent_format=True,
)
fig.layout.template = None
fig.show()

Solution

  • I had the same error message recently and came across this post. I think the key is the migration of shapely to 2.x. You need to use the ".geoms" attribute now to make multi-part geometries iterable:

    https://shapely.readthedocs.io/en/stable/migration.html

    This resolved my issue.