首页 > 解决方案 > 绘制多边形返回“'GeoSeries' 对象没有属性 '_geom'”

问题描述

我正在尝试使用 cartopy 在现有地图上绘制几个多边形作为叠加层。但是,我收到以下错误AttributeError: 'GeoSeries' object has no attribute '_geom'

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()

标签: geopandascartopy

解决方案


africa您刚刚创建的地理数据框有一个方法.plot()。这样您就可以使用一个选项来绘制它,该选项ax=ax指示渲染器使用您创建的轴在其上绘制。

import cartopy.crs as ccrs
from cartopy.feature import ShapelyFeature
from matplotlib import pyplot as plt

import geopandas as gpd

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
africa = world[(world['continent'] == 'Africa')]

proj = ccrs.PlateCarree()
ax = plt.axes(projection=proj)

africa.plot(ax=ax)

# Bad code
#shape_feature = ShapelyFeature([africa.geometry], ccrs.PlateCarree(), facecolor="lime", edgecolor='black', lw=1)
#ax.add_feature(shape_feature)

plt.show()

非洲

回答更新的问题

新版代码:-

import cartopy
import cartopy.crs as ccrs
from cartopy.feature import ShapelyFeature
from matplotlib import pyplot as plt

import geopandas as gpd

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
africa = world[(world['continent'] == 'Africa')]

latlon_proj = ccrs.PlateCarree()
axis_proj = ccrs.Mollweide()

ax = plt.axes(projection=axis_proj)
ax.stock_img()

for ea in africa['geometry']:
    feat = cartopy.feature.ShapelyFeature([ea], latlon_proj, facecolor="lime", edgecolor='black', lw=0.2)
    ax.add_feature(feat)

#ax.add_feature(cartopy.feature.COASTLINE)

plt.show()

输出图:

非洲4


推荐阅读