geopandas - 绘制多边形返回“'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()
解决方案
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()
输出图:
推荐阅读
- mysql - 合计 1 列
- python - Pyspark - 另一个列列表中的列项
- python - 从 GIT 提取代码时运行 django 服务器的问题
- python - 如何降低时序复杂度?
- spring-boot - Keycloak:无法在 Spring Boot 应用程序中加载 URL
- c# - 在 vsto 加载项中使用 ActiveInlineResponse。修改 header 后发送 MailItem
- python - 通过旋转和平移将两个 PDF 文件合并为一页
- java - 为什么它没有得到任何数据?
- java - AWS Cognito 使用 spring security logoutSuccessHandler 注销
- javascript - 如何使用插值字符串作为 Javascript 关联数组中的键?