python - 箭头的 Matplotlib 图例

标签 python matplotlib

我想知道如何标记 arrow 并在图的图例中显示它。

例如如果我这样做

 arrow(0,1,'dummy',label='My label')

 legend()

我在图例中没有看到任何内容。我希望在图例框中的标签旁边看到一个箭头。

最佳答案

您可以将任意艺术家添加到图例命令,如解释的那样here

import matplotlib.pyplot as plt

f = plt.figure()
arrow = plt.arrow(0, 0, 0.5, 0.6, 'dummy',label='My label')
plt.legend([arrow,], ['My label',])

箭头艺术家不允许使用标记参数,因此您需要进行一些额外的手动修改以替换图例中的标记。

编辑

要获得自定义标记,您需要定义自己的 handler_map。以下代码的灵感来自示例 here :

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

def make_legend_arrow(legend, orig_handle,
                      xdescent, ydescent,
                      width, height, fontsize):
    p = mpatches.FancyArrow(0, 0.5*height, width, 0, length_includes_head=True, head_width=0.75*height )
    return p

f = plt.figure(figsize=(10,6))
arrow = plt.arrow(0,0, 0.5, 0.6, 'dummy', label='My label', )
plt.legend([arrow], ['My label'], handler_map={mpatches.FancyArrow : HandlerPatch(patch_func=make_legend_arrow),
                    })

关于python - 箭头的 Matplotlib 图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22348229/

相关文章:

python - 在 TKinter 中显示 ASCII 艺术

python - 根据周围字符忽略正则表达式分割中的大小写

python - Celery - 以编程方式列出 worker

python - 如何使用 matplotlib 箭袋刻度

python - 使用 rcparams/mplstyle 隐藏上/右刻度线

python - 在 Plotly 中更改标题字体大小

python - 在 Z3 中使用 SMT 约束时是否可以获得合法范围信息

python - 在特定位置设置 xticks 标签的最简洁方法

python - 如何在进入事件循环之前获取matplotlib图形窗口的宽度?

python - Win 7 32 matplotlib 日期工具