使用cartopy绘制多边形报'GeoSeries'无'_geom'属性错误如何解决
报错原因及解决方案
错误根源
你给ShapelyFeature构造函数传入的第一个参数格式不符合要求。africa.geometry本身是GeoPandas的GeoSeries类型,你将其包裹在列表中后,实际传入的是[GeoSeries对象],而ShapelyFeature要求第一个参数为单个Shapely几何对象组成的可迭代序列,遍历到GeoSeries对象时尝试读取_geom属性失败,因此抛出对应报错。
修复方案
方案1:修改原代码传参格式
仅需要调整ShapelyFeature的第一个参数,直接传入africa.geometry即可(GeoSeries本身是可迭代对象,每个元素都是单个Shapely几何对象),修复后完整代码如下:
import cartopy.crs as ccrs from cartopy.feature import ShapelyFeature from matplotlib import pyplot as plt import geopandas as gpd ax = plt.axes(projection=ccrs.Mollweide()) ax.stock_img() world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[(world['continent'] == 'Africa')] # 仅修改此行,移除多余的列表包裹 shape_feature = ShapelyFeature(africa.geometry, ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1) ax.add_feature(shape_feature) plt.show()
方案2:使用GeoPandas内置plot接口(更简便)
不需要手动构造ShapelyFeature,直接调用GeoDataFrame的plot方法指定绘图轴和坐标系即可,代码更简洁:
import cartopy.crs as ccrs from matplotlib import pyplot as plt import geopandas as gpd ax = plt.axes(projection=ccrs.Mollweide()) ax.stock_img() world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) africa = world[(world['continent'] == 'Africa')] africa.plot(ax=ax, transform=ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1) plt.show()
内容的提问来源于stack exchange,提问作者Stücke
相关产品推荐
相关产品推荐

