You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绘制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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 02:50:06