【问题标题】:Add item to existing Matplotlib legend将项目添加到现有的 Matplotlib 图例
【发布时间】:2019-09-17 15:31:44
【问题描述】:

鉴于以下设置:

from matplotlib import pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2,3,4,5,6], label='linear')
ax.plot([0,1,4,9,16,25,36], label='square')
lgd = ax.legend(loc='lower right')

如果函数add_patch 仅接收lgd 作为参数,是否可以将自定义图例项添加到现有项之上的图例中,而不更改图例的其他属性?

我可以使用以下方法添加项目:

def add_patch(legend):
    from matplotlib.patches import Patch
    ax = legend.axes
    handles, labels = ax.get_legend_handles_labels()
    handles.append(Patch(facecolor='orange', edgecolor='r'))
    labels.append("Color Patch")
    ax.legend(handles=handles, labels=labels)

但这不会保留图例的属性,例如位置。如何在绘制线条后仅给定图例对象添加项目?

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

    原则上,图例并不意味着更新,而是重新创建。

    以下内容可以满足您的需求,但请注意,这是一种使用内部方法的 hack,因此不保证可以正常工作,并且可能会在未来的版本中中断。所以不要在生产代码中使用它。此外,如果您为图例设置了与默认字体(大小)不同的标题,则更新时它将丢失。此外,如果您通过markerfirst 操作了句柄和标签的顺序,则更新时会丢失。

    from matplotlib import pyplot as plt
    fig, ax = plt.subplots()
    ax.plot([0,1,2,3,4,5,6], label='linear')
    ax.plot([0,1,4,9,16,25,36], label='square')
    lgd = ax.legend(loc='lower right')
    
    def add_patch(legend):
        from matplotlib.patches import Patch
        ax = legend.axes
    
        handles, labels = ax.get_legend_handles_labels()
        handles.append(Patch(facecolor='orange', edgecolor='r'))
        labels.append("Color Patch")
    
        legend._legend_box = None
        legend._init_legend_box(handles, labels)
        legend._set_loc(legend._loc)
        legend.set_title(legend.get_title().get_text())
    
    
    add_patch(lgd)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      是否在绘制线条之后添加色块但在添加图例之前添加选项?

      import matplotlib.pyplot as plt
      from matplotlib.patches import Patch
      
      fig, ax = plt.subplots()
      line1 = ax.plot([0,1,2,3,4,5,6], label='linear')
      line2 = ax.plot([0,1,4,9,16,25,36], label='square')
      patch = Patch(facecolor='orange', edgecolor='r', label='Color patch')
      lgd = ax.legend(handles=[line1, line2, patch], loc='lower right')
      

      【讨论】:

      • 我收到 AttributeError: 'list' object has no attribute 'get_label' 错误。可能是因为line1 和line2 没有关联的get_label 方法。
      • 显然,ax.plot() 的行为现在已经改变,所以它返回一个列表(在这种情况下只有一个元素)。所以最后一行必须是lgd = ax.legend(handles=[line1[0], line2[0], patch], loc='lower right')
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2016-09-16
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2020-12-22
      • 2013-02-12
      相关资源
      最近更新 更多