我想知道如何标记 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/