箭头的 Matplotlib 图例 [英] Matplotlib legend for an arrow

查看:63
本文介绍了箭头的 Matplotlib 图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何标记箭头并将其显示在图例中.

I would like to know how it is possible to label an arrow and show it in the legend of a plot.

例如如果我这样做

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

 legend()

我在图例中看不到任何东西.我想在图例框中的标签旁边看到一个箭头.

I do not see anything in the legend. I would like to see in the legend box an arrow next to its label.

推荐答案

您可以向图例命令添加任意艺术家,如此处

You can add arbitrary artists to the legend command, as explained 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',])

箭头美术师不允许使用标记参数,因此您需要做一些额外的手动修改,以替换图例中的标记.

The arrow artist does not allow a marker parameter, so you'll need to do some additional manual tinkering to replace the marker in the legend.

编辑

要获得自定义标记,您需要定义自己的handler_map.以下代码的灵感来自此处:

To get the custom marker you need to define your own handler_map. The following code is inspired in the example 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),
                    })

这篇关于箭头的 Matplotlib 图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆