代码之家  ›  专栏  ›  技术社区  ›  Tom de Geus

使用一个“plot”调用绘制多条曲线时的一个图例项

  •  0
  • Tom de Geus  · 技术社区  · 6 年前

    我创建了一个网格绘制几个曲线使用一个 plot 呼叫方式:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    
    x = np.array([[0,1], [0,1], [0,1]])
    y = np.array([[0,0], [1,1], [2,2]])
    
    ax.plot([0,1],[0,2], label='foo', color='b')
    
    ax.plot(x.T, y.T, label='bar', color='k')
    
    ax.legend()
    
    plt.show()
    

    结果图例中的“条形”条目与曲线的数量相同(见下文)。我希望每个项目只有一个图例

    我希望这样我可以有其他的绘图命令(例如,一个绘制'foo'曲线),其曲线是 自动

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  6
  •   ImportanceOfBeingErnest    6 年前

    这里有一个可能的解决方案:您可以使用下划线不生成图例项这一事实。所以除了第一个标签 "_" 抑制那些出现在图例中的。

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots()
    
    x = np.array([[0,1], [0,1], [0,1]])
    y = np.array([[0,0], [1,1], [2,2]])
    
    ax.plot([0,1],[0,2], label='foo', color='b')
    
    lines = ax.plot(x.T, y.T, label='bar', color='k')
    plt.setp(lines[1:], label="_")
    ax.legend()
    
    plt.show()
    

    enter image description here

        2
  •  3
  •   Sheldore    6 年前

    下面是使用现有图例句柄和标签的一种方法。你先得到三个 handles, labels 另外 给你一个控制 不仅如此 论把手的摆放顺序 而且 在情节上显示什么。

    ax.plot(x.T, y.T,  label='bar', color='k')
    handles, labels = ax.get_legend_handles_labels()
    ax.legend([handles[0]], [labels[0]], loc='best')
    

    enter image description here

    从特定的地块(一组线)中提取-- ax1 在这种情况下

    ax1 = ax.plot(x.T, y.T,  label='bar', color='k')
    plt.legend(handles=[ax1[0]], loc='best')
    

    用两个数字把它扩展到你的问题上

    ax1 = ax.plot([0,1],[0,2], label='foo', color='b')
    ax2 = ax.plot(x.T, y.T,  label='bar', color='k')
    plt.legend(handles=[ax1[0], ax2[1]], loc='best')
    

    @SpghttCd建议使用for循环的另一种替代方法

    for i in range(len(x)):
        ax.plot(x[i], y[i], label=('' if i==0 else '_') + 'bar', color='k')
    
    ax.legend()
    

    enter image description here