如何为GeoPandas绘制的多shapefile图层添加对应图例
手动为多Shapefile图层添加匹配图例的实现方案
问题场景
使用geopandas结合shapefile开展地理绘图时,已为每个shapefile图层单独指定绘制颜色,需要添加对应图例区分不同图层。
现有代码
data = gpd.GeoDataFrame(data, geometry=gpd.points_from_xy(data.INTPTLON, data.INTPTLAT)) fig, ax = plt.subplots(figsize=(10, 10)) DC_BLK.plot(ax=ax,edgecolor = "black" ,facecolor = "None") DC_BG.plot(ax=ax, edgecolor = "lightblue",facecolor = "None") DC_CT.plot(ax=ax,edgecolor = "purple",facecolor = "None") data.plot(ax=ax , marker = '.') ax.set_title('Washington DC - 7x pop') plt.show()
代码要素说明
data.plot:绘制经纬度坐标对应的3个点位DC_BLK:华盛顿哥伦比亚特区(DC)街区数据shapefile图层DC_BG:华盛顿哥伦比亚特区(DC)街区组数据shapefile图层DC_CT:华盛顿哥伦比亚特区(DC)人口普查区数据shapefile图层
实现方法
geopandas仅在通过column参数绑定字段做分类/分级配色时会自动生成图例,手动给图层指定固定颜色时,需要手动构造和图层样式匹配的图例句柄。由于当前所有面图层都设置为无填充、仅显示边界,用线元素构造图例和展示效果最匹配,修改后可运行代码如下:
from matplotlib.lines import Line2D import geopandas as gpd import matplotlib.pyplot as plt # 构造点矢量图层 data = gpd.GeoDataFrame(data, geometry=gpd.points_from_xy(data.INTPTLON, data.INTPTLAT)) fig, ax = plt.subplots(figsize=(10, 10)) # 逐个绘制图层 DC_BLK.plot(ax=ax, edgecolor="black", facecolor="None") DC_BG.plot(ax=ax, edgecolor="lightblue", facecolor="None") DC_CT.plot(ax=ax, edgecolor="purple", facecolor="None") # 点图层如果需要自定义颜色可以加color参数,和图例配置保持一致即可 data.plot(ax=ax, marker='.', color="#1f77b4") # 构造和图层样式一一对应的图例句柄 legend_handles = [ Line2D([0], [0], color="black", lw=1, label="DC街区"), Line2D([0], [0], color="lightblue", lw=1, label="DC街区组"), Line2D([0], [0], color="purple", lw=1, label="DC人口普查区"), Line2D([0], [0], marker=".", color="#1f77b4", lw=0, markersize=10, label="观测点位") ] # 添加图例,可根据绘图需求调整位置、标题等参数 ax.legend(handles=legend_handles, loc="upper right", title="图层分类") ax.set_title('Washington DC - 7x pop') plt.show()
调整提示:如果后续修改了某个图层的颜色、线宽、点大小等样式,同步修改
legend_handles里对应元素的参数即可保证图例和图层显示完全一致。
内容的提问来源于stack exchange,提问作者voyme
相关产品推荐
相关产品推荐

