绘制GeoDataFrame时如何正确显示图例?
GeoDataFrame绘图图例无法显示的解决方案
问题原因
gdf.plot() 返回的是matplotlib的Axes对象,而非图例能够识别的具体绘图元素(如Patch、Line2D等),直接将其作为图例的handles参数会触发警告,且无法生成有效图例。
解决方案一:使用代理艺术家(Proxy Artist)
这是单个要素场景下最直接的解决方法,手动创建一个与绘图样式匹配的代理对象用于生成图例:
import geopandas as gpd from shapely.geometry import box import matplotlib.pyplot as plt from matplotlib.patches import Patch fig, ax = plt.subplots() bounding_box = [9.454, 80.4, 12, 80.88] polygon = box(*bounding_box) gdf = gpd.GeoDataFrame(geometry=[polygon]) # 绘制多边形 gdf.plot(ax=ax, edgecolor='red', facecolor='none', linewidth=2) # 创建与绘图样式一致的代理Patch proxy_patch = Patch(facecolor='none', edgecolor='red', linewidth=2, label="user bbox query") # 通过代理对象添加图例 ax.legend(handles=[proxy_patch]) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.show()
解决方案二:利用GeoDataFrame属性列映射(多要素场景更适用)
如果需要绘制多个不同类别的要素,可以给GeoDataFrame添加分类列,让plot方法自动生成图例:
import geopandas as gpd from shapely.geometry import box import matplotlib.pyplot as plt fig, ax = plt.subplots() bounding_box = [9.454, 80.4, 12, 80.88] polygon = box(*bounding_box) # 添加用于图例映射的分类列 gdf = gpd.GeoDataFrame({'geometry': [polygon], 'category': ["user bbox query"]}) # 通过column参数指定映射列,自动生成图例 gdf.plot(ax=ax, edgecolor='red', facecolor='none', linewidth=2, column='category', legend=True) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.show()
内容的提问来源于stack exchange,提问作者Zorglub29
相关产品推荐
相关产品推荐

