标有斜线的图例绘制的大熊猫(geopandas)

时间:2019-07-17 02:09:50

标签: python pandas matplotlib 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')

enter image description here

1 个答案:

答案 0 :(得分:2)

创建多边形时,属性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