运行Plotly县级别Choropleth脚本遇TypeError: 'MultiPolygon'不可迭代错误
问题:运行Plotly县级别Choropleth脚本触发 TypeError: 'MultiPolygon' object is not iterable
问题详情
运行Plotly官方文档中的县级别Choropleth示例代码时,启动后立即报错:TypeError: 'MultiPolygon' object is not iterable。我查找了相关问题的解决方案,但不确定是否适配当前场景,其中某方案看似可行,但疑惑Plotly官方发布的基础代码为何需要变通处理,怀疑是自己代码写法存在疏漏。
运行代码
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()
原因分析与解决方案
这个报错本质是依赖库版本不兼容导致:新版本的geopandas(或其依赖的shapely库)对MultiPolygon对象的迭代逻辑做了调整,而Plotly的create_choropleth函数尚未适配这一变化,导致无法直接迭代MultiPolygon对象。
方案1:锁定兼容版本的依赖库
这是最直接的解决方式,无需修改代码:
- 将
plotly版本降级到5.15.0及以下 - 将
geopandas版本降级到0.13.2及以下 - 执行安装命令:
pip install plotly==5.15.0 geopandas==0.13.2
方案2:替换为兼容的绘图函数(无需降级)
如果不想修改依赖版本,可以使用plotly.express的choropleth_mapbox函数替代,该函数对新版本地理库兼容性更好:
import plotly.express as px 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'] # 使用plotly.express的choropleth_mapbox实现相同效果 fig = px.choropleth_mapbox(df_sample_r, geojson="https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json", locations='FIPS', color='TOT_POP', color_continuous_scale=["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0", "#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"], range_color=(df_sample_r['TOT_POP'].min(), df_sample_r['TOT_POP'].max()), mapbox_style="carto-positron", zoom=6, center = {"lat": 27.994402, "lon": -81.760254}, opacity=0.5, labels={'TOT_POP':'Population'} ) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.show()
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

