python - 'Polygon' 对象不可迭代 - iPython Cookbook
问题描述
我正在使用 python 学习数据的可视化Cartopy
我有这个用于绘制非洲人口和 GDP 的代码。
def choropleth(ax, attr, cmap_name):
# We need to normalize the values before we can
# use the colormap.
values = [c.attributes[attr] for c in africa]
norm = Normalize(
vmin=min(values), vmax=max(values))
cmap = plt.cm.get_cmap(cmap_name)
for c in africa:
v = c.attributes[attr]
sp = ShapelyFeature(c.geometry, crs,
edgecolor='k',
facecolor=cmap(norm(v)))
ax.add_feature(sp)
fig, (ax1, ax2) = plt.subplots(
1, 2, figsize=(10, 16),
subplot_kw=dict(projection=crs))
draw_africa(ax1)
choropleth(ax1, 'POP_EST', 'Reds')
ax1.set_title('Population')
draw_africa(ax2)
choropleth(ax2, 'GDP_MD_EST', 'Blues')
ax2.set_title('GDP')
但我收到这样的错误 -
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-41-b443c58ecbd5> in <module>
3 subplot_kw=dict(projection=crs))
4 draw_africa(ax1)
----> 5 choropleth(ax1, 'POP_EST', 'Reds')
6 ax1.set_title('Population')
7
<ipython-input-40-161126226479> in choropleth(ax, attr, cmap_name)
8 for c in africa:
9 v = c.attributes[attr]
---> 10 sp = ShapelyFeature(c.geometry, crs,
11 edgecolor='k',
12 facecolor=cmap(norm(v)))
~/anaconda3/lib/python3.8/site-packages/cartopy/feature/__init__.py in __init__(self, geometries, crs, **kwargs)
219 """
220 super(ShapelyFeature, self).__init__(crs, **kwargs)
--> 221 self._geoms = tuple(geometries)
222
223 def geometries(self):
TypeError: 'Polygon' object is not iterable
我尝试在 github 上搜索此问题,但无济于事。谁能帮我解决这个问题?
这是供参考的网站。
解决方案
问题是代码试图将 shapely 传递给Polygon
期望的函数MultiPolygon
。swatchai 在这里https://stackoverflow.com/a/63812490/13208790的优雅解决方案是捕获Polygon
s 并将它们放在一个列表中,以便它们可以被视为MultiPolygon
s。
这是适合您的情况的代码:
for i, c in enumerate(africa):
v = c.attributes[attr]
print(i)
# swatchai's Polygon catch logic
if c.geometry.geom_type=='MultiPolygon':
# this is a list of geometries
sp = ShapelyFeature(c.geometry, crs,
edgecolor='k',
facecolor=cmap(norm(v)))
elif c.geometry.geom_type=='Polygon':
# this is a single geometry
sp = ShapelyFeature([c.geometry], crs,
edgecolor='k',
facecolor=cmap(norm(v)))
else:
pass #do not plot the geometry
推荐阅读
- android - 我得到“类型不匹配。必需:状态
使用 Jetpack compose 的 viewModel.observeAsState() 时发现:字符串 - html - html将html中的书籍列表显示为表格
- java - Java错误java:不兼容的类型:void无法转换为java.util.List
尝试使用 Collections.sort() 对列表进行排序时 - r - nnet 在 RStudio 中给我错误“NA/NaN/Inf in foreign function call (arg 2)”
- php - php 提交表单仅适用于本地主机
- c# - 在 C# 中使用从 c++ 函数返回的字符串数组
- c++ - 等到发布到 boost::asio::thread_pool 的作业(与所有作业完全相反)完成?
- django - Django:我有一个关于在 Django 中创建 API 的问题
- swiftui - 如何删除 Swiftui 中的切换按钮以及如何在 iPad 上显示侧边栏
- python - xlwings 0.23.2 - Run-time error '53': File not found