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

如何修改Geopandas GeoDataFrame绘图中图例标记的形状?

修改Geopandas分类地图的图例标记形状

默认情况下,Geopandas绘制分类地图(非连续变量)时,图例标记是实心圆。要改成带细黑边框的实心矩形,直接用plot的marker参数或legend_kwds无法实现,因为分类图例的标记属于matplotlib的Patch对象,需要手动替换:

实现代码

import geopandas as gpd
import matplotlib.patches as mpatches

# 加载数据并绘制基础地图
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
ax = world.plot(column='continent', legend=True, legend_kwds={'loc':'lower left'})

# 获取图例对象
legend = ax.get_legend()

# 遍历图例条目,替换标记为带黑边框的矩形
for idx, patch in enumerate(legend.get_patches()):
    # 创建新的矩形Patch,保留原颜色,添加黑边框
    rect_patch = mpatches.Rectangle(
        (patch.get_x(), patch.get_y()),
        patch.get_width(), patch.get_height(),
        facecolor=patch.get_facecolor(),
        edgecolor='black',
        linewidth=0.8
    )
    # 隐藏原圆形标记,替换为新矩形
    patch.set_visible(False)
    legend._legend_box._children[0]._children[idx]._children[0] = rect_patch

# 可选:移除图例外边框
legend.get_frame().set_linewidth(0)

关键说明

  • 分类图例的标记由matplotlib的Patch对象构成,而非普通绘图的marker,因此需要手动替换
  • 遍历图例中的每个圆形Patch,用Rectangle创建对应尺寸和颜色的矩形,设置黑色细边框
  • 通过图例内部的子元素结构,将新Patch替换到原有位置

内容的提问来源于stack exchange,提问作者Aaron Graybill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:42:11