python - 带有图例的 geopandas 充满了斜线

标签 python pandas matplotlib geopandas

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

我知道这行不通,但我尝试了 Line2D([0],[0],color='white',hatch='\\',lw=4,label= 'Centre County'),并收到类似“hatch is not an attribute”之类的错误。

%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')

enter image description here

最佳答案

当您创建多边形时,属性 facecolor 定义填充颜色。要为多边形要素创建正确的图例,需要 mpatches.Patch

下面是演示如何使用 facecolormpatches.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()

输出图如下所示:

enter image description here

关于python - 带有图例的 geopandas 充满了斜线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57067623/

相关文章:

python - 如何使用 XlsxWriter 将多种格式应用于一列

python - [Pandas]根据if语句分配新列的方式

python - 在 matplotlib 中更改刻度标签行间距

python-3.x - 如何用两条不同颜色的线绘制xlabel?

python - python中矩形的颜色

python - 我可以简化我的代码,这样我就不会单独写出字母表中的每个字母吗?

python - 使用 urllib 而不是 twitter api 爬取 twitter

pandas - 如果数据框列值匹配字典键,检查不同的列是否匹配字典值

python - 字典在 python 3 中不可订购?

python - 将字符串解析为字典