Matplotlib图例概览

2024-04-25 05:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何标记一个arrow并在一个情节的传奇中显示它。

例如,如果我这样做

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

 legend()

我看不到传说中的任何东西。我想在图例框中看到标签旁边的箭头。


Tags: 标记my标签箭头label传奇dummy图例
2条回答

可以添加任何乳胶符号作为标记。 例如:对于向下的箭头,可以指定:

scatter( x ,y, c='purple',marker=r’$\downarrow$’,s=20, label='arrow' )

您可以向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),
                    })

相关问题 更多 >