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

如何使用代理图元图例修改matplotlib中FancyArrow的箭头宽度

解决方法

问题的核心是你自定义的图例箭头生成函数没有读取原始代理箭头的自定义属性,所有生成的图例箭头都使用了固定参数,自然无法体现宽度差异。只需要在make_legend_arrow函数中,从传入的orig_handle对象(也就是你提前定义的两个FancyArrow代理图元)读取预设的宽度、颜色等属性,即可实现不同箭头的差异化显示。

修改后的完整代码如下:

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerPatch
import matplotlib.patches as mpatches

def make_legend_arrow(legend, orig_handle,
                      xdescent, ydescent,
                      width, height, fontsize):
    # 从原始代理箭头读取预设属性
    arrow_width = orig_handle.width
    # 箭头头部宽度可按比例适配箭身宽度,也可自定义规则
    head_width = arrow_width * 1.5
    p = mpatches.FancyArrow(0,
                            0.5*height,
                            width * 0.8, # 适配图例区域的箭头长度
                            0,
                            width=arrow_width,
                            head_width=head_width,
                            head_length=head_width * 0.8,
                            fc=orig_handle.get_fc(), # 继承原始填充颜色
                            ec=orig_handle.get_ec() # 继承原始边框颜色
                           )
    return p

f = plt.figure()
arrows = [mpatches.FancyArrow(0, 0, 0, 0, fc='blue',
                              width=0.4), # 宽度适配图例显示比例,可按需调整
          mpatches.FancyArrow(0, 0, 0, 0, fc='red',
                              width=0.1)]

plt.legend(handles=arrows, 
           labels=['粗箭头','细箭头'], 
           handler_map={mpatches.FancyArrow : HandlerPatch(patch_func=make_legend_arrow),
                    })
plt.show()

注:原始代码中代理箭头的width参数设置过大,放在图例区域会超出显示范围,上述代码调整了width的取值比例,你可以根据实际显示需求自行调整数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:36:04