geopandas 绘制的图例填充了斜线

Neo*_*Neo 4 python matplotlib pandas geopandas

我使用不同的颜色和图案在 PA 地图上显示三个县。中心县由斜线表示,使用hatch='\\'. 但是我很难在图例上显示这种模式。

我有点知道这行不通,但我尝试过Line2D([0],[0],color='white',hatch='\\',lw=4,label='Centre County'),但遇到了诸如“舱口不是属性”之类的错误。

%matplotlib inline

import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

fig, ax = plt.subplots(1,figsize=(8,8))

pa.plot(ax=ax,color='white',edgecolor='grey')
centre.plot(ax=ax,color='white',hatch='\\\\\\\\',edgecolor='black')
pike.plot(ax=ax,color='grey')
perry.plot(ax=ax,color='red')

LegendElement = [
                 Line2D([0],[0],color='red',lw=4,label='Perry County'),
                 Line2D([0],[0],color='grey',lw=4,label='Pike County'),
                 Line2D([0],[0],color='white',lw=4,label='Centre County')
                ]
ax.legend(handles=LegendElement,loc='upper right')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

swa*_*hai 8

创建多边形时,该属性facecolor定义填充颜色。并且需要为多边形特征创建正确的图例mpatches.Patch

这是演示如何使用facecolor, 和的代码mpatches.Patch

import geopandas as gpd
import matplotlib.pyplot as plt
#from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
from cartopy import crs as ccrs

#fig, ax = plt.subplots(1,figsize=(8,8))
fig, ax = plt.subplots(figsize=(9,9), subplot_kw={'projection': ccrs.PlateCarree()})

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# cities = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))

asia = world[(world.continent == "Asia")]  #take Asia countries
asia.plot(ax=ax, color="lightgreen")

china = asia[(asia.name == "China")]
india = asia[(asia.name == "India")]
saudi = asia[(asia.name == "Saudi Arabia")]


ax.add_geometries(china['geometry'], crs=ccrs.PlateCarree(), \
                      facecolor='w', hatch='\\\\\\\\', edgecolor='k', label='China')
ax.add_geometries(india['geometry'], crs=ccrs.PlateCarree(), \
                      color='grey', label='India')
ax.add_geometries(saudi['geometry'], crs=ccrs.PlateCarree(), \
                      color='red', label='Saudi Arabia')

LegendElement = [
                 mpatches.Patch(facecolor='w', hatch='\\\\\\\\', edgecolor='k', label='China'),
                 mpatches.Patch(color='grey', label='India'),
                 mpatches.Patch(color='red', label='Saudi Arabia')
                ]
ax.legend(handles = LegendElement, loc='upper right')
plt.show()
Run Code Online (Sandbox Code Playgroud)

输出图如下所示:

在此处输入图片说明