Python:从 Shapefile 到彩色 cartopy 地图的 Dataframe 中的多边形迭代

Python: Iteration over Polygon in Dataframe from Shapefile to color cartopy map

我正在根据某些值在 cartopy 地图上为国家着色。我正在使用 geopandas 和 shapefile 来自:https://www.naturalearthdata.com/

在遍历数据框 df 以获取某些国家/地区的几何形状时,我遇到了问题。我可以获得具有多边形几何形状的国家/地区的几何形状,但我无法获得具有多边形几何形状的国家/地区的几何形状,例如比利时或奥地利。

这是我的代码:

#imports
import matplotlib.pyplot as plt
import matplotlib
import cartopy
from cartopy.io import shapereader
import cartopy.crs as ccrs
import geopandas
import numpy as np

# get natural earth data (http://www.naturalearthdata.com/)
# get country borders
resolution = '10m'
category = 'cultural'
name = 'admin_0_countries'
shpfilename = shapereader.natural_earth(resolution, category, name)

# read the shapefile using geopandas
df = geopandas.read_file(shpfilename)


# Set up the canvas
fig = plt.figure(figsize=(20, 20))
central_lon, central_lat = 0, 45
extent = [-10, 28, 35, 65]
ax = plt.axes(projection=cartopy.crs.Orthographic(central_lon, central_lat))
ax.set_extent(extent)
ax.gridlines()

# Add natural earth features and borders
ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=0.8)
ax.add_feature(cartopy.feature.OCEAN, facecolor=("lightblue"))
ax.add_feature(cartopy.feature.LAND, facecolor=("lightgreen"), alpha=0.35)
ax.coastlines(resolution='10m')

# Countries and value
countries = ['Sweden', 'Netherlands', 'Ireland', 'Denmark', 'Germany', 'Greece', 'France', 'Spain', 'Portugal', 'Italy', 'United Kingdom', 'Austria']
value = [47.44, 32.75, 27.53, 23.21, 20.08, 18.08, 17.23, 13.59, 12.13, 5.66, 22.43, 7]

# Normalise values
value_norm = (value-np.nanmin(value))/(np.nanmax(value) - np.nanmin(value))

# Colourmap
cmap = matplotlib.cm.get_cmap('YlOrBr')


for country, value_norm in zip(countries, value_norm):
    # read the borders of the country in this loop
    poly = df.loc[df['ADMIN'] == country]['geometry'].values[0]
    # get the color for this country
    rgba = cmap(value_norm)
    # plot the country on a map
    ax.add_geometries(poly, crs=ccrs.PlateCarree(), facecolor=rgba, edgecolor='none', zorder=1)

# Add a scatter plot of the original data so the colorbar has the correct numbers
dummy_scat = ax.scatter(value, value, c=value, cmap=cmap, zorder=0)
fig.colorbar(mappable=dummy_scat, label='Percentage of Do and Dont`s [%]', orientation='horizontal', shrink=0.8)

plt.show()
fig.savefig("Länderübersicht.jpg")

我如何遍历这些国家或为这些国家着色,或者我是否必须获取另一个 shapefile? 谢谢!

从错误代码 TypeError: 'Polygon' object is not iterable 中获得灵感,我从假设我们需要某种可迭代对象开始,例如多边形列表。从 this answer 我发现函数 shapely.geometry.MultiPolygon 可以完成这项工作。您只需将多边形列表传递给它即可。添加一点逻辑以仅在检测到 Polygon 而不是 MultiPolygon 时执行此操作,并且我们有:

poly = df.loc[df['ADMIN'] == country]['geometry'].values[0]
if type(poly) == shapely.geometry.polygon.Polygon:
    simple_poly = df.loc[df['ADMIN'] == country]['geometry'].values[0]
    list_polys = [poly, poly]
    poly = shapely.geometry.MultiPolygon(list_polygons)

这是一个相当老套的解决方案,它会打印两次多边形,所以如果您以后决定将其设为透明或其他方式,请注意。或者,您可以使用 [poly, some_other_poly_outside_map_area].

代替 [poly, poly]

命令ax.add_geometries() 要求提供几何图形列表,因此,单个几何图形会导致错误。要修复您的代码,您可以替换以下行:

ax.add_geometries(poly, crs=ccrs.PlateCarree(), facecolor=rgba, edgecolor='none', zorder=1)

使用这些代码行:

# plot the country on a map
if poly.geom_type=='MultiPolygon':
    # `poly` is a list of geometries
    ax.add_geometries(poly, crs=ccrs.PlateCarree(), facecolor=rgba, edgecolor='none', zorder=1)
elif poly.geom_type=='Polygon': 
    # `poly` is a geometry
    # Austria, Belgium
    # Plot it `green` for checking purposes
    ax.add_geometries([poly], crs=ccrs.PlateCarree(), facecolor="green", edgecolor='none', zorder=1)
else:
    pass  #do not plot the geometry

请注意,如果 poly.geom_type 是 'Polygon',我只是用 [poly] 代替 poly