【问题标题】:Matplotlib legend for an arrow箭头的 Matplotlib 图例
【发布时间】:2021-04-24 00:06:03
【问题描述】:

我想知道如何标记arrow 并将其显示在情节图例中。

例如,如果我这样做

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

 legend()

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以将任意艺术家添加到图例命令中,如 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),
                        })
    

    【讨论】:

    • 谢谢,但这只是部分回答了我的问题。问题是我想要一个箭头作为标记。
    • 这很酷。如何在图例中同时注释向上和向下箭头?
    • 或者,是否可以在传递给函数的参数中从legend 或orig_handle 获取标签?我检查了.get_lablel(),但它返回空字符串,为什么?
    • 在这个例子中,一些 FacyArrow 参数似乎没有效果,例如 fc、ec、alpha:箭头总是以默认颜色显示。这是为什么呢?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多