Matplotlib 中箭头的图例
我想知道怎么给一个箭头
加标签,并把它显示在图表的图例里。
比如说,如果我这样做:
arrow(0,1,'dummy',label='My label')
legend()
我在图例里什么也看不见。我希望在图例框里能看到一个箭头,旁边有它的标签。
2 个回答
9
你可以把任何latex符号当作标记来使用。
比如说,如果你想要一个指向下方的箭头,你可以这样指定:
scatter( x ,y, c='purple',marker=r'$\downarrow$',s=20, label='arrow' )
16
你可以在图例命令中添加任意的艺术元素,具体的说明可以在这里找到。
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
。下面的代码灵感来源于这个例子:
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),
})