代码之家  ›  专栏  ›  技术社区  ›  Venkatachalam

更改matplotlib图例中标签的格式

  •  1
  • Venkatachalam  · 技术社区  · 6 年前

    我想定制Matplotlib中的传说。

    我想水平订购图例内的标签,并移除手柄。标签的颜色必须与线条颜色相同。

    目前我已将句柄设置为不可见,但无法更改标签的顺序。

    期待专家的建议。

    预期输出:

    enter image description here

    到目前为止,我所取得的成就是:

    import numpy as np
    import matplotlib.pyplot as plt
    x = np.linspace(0, 20, 1000)
    y1 = np.sin(x)
    y2 = np.cos(x)
    
    plt.figure(figsize=(10,7))
    lines=[]
    lines.append(plt.plot(x, y1, '-b', label='sine')[0])
    lines.append(plt.plot(x, y2, '-r', label='cosine')[0])
    plt.legend(loc='upper left')
    plt.ylim(-1.5, 2.0)
    for item_legend,handle,line in zip(plt.legend().get_texts(),plt.gca().get_legend().legendHandles,lines):
        plt.setp(item_legend, color=line.get_color(),size=30)
        handle.set_visible(False)
    
    plt.show()
    

    输出:

    enter image description here

    谢谢。

    编辑: 如果我设置

    plt.legend(loc='upper left', ncols=2)
    

    标签在一行中对齐,但所有以前的格式都将被删除。

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

    这就是你能做到的。左对齐的关键是使用 handletextpad=0 handlelength=0 . 这个 columnspacing 此处控制图例两列之间的水平间距。将句柄长度设置为0只会显示图例文本。然后,您可以根据各自的曲线最终调整图例文本的颜色。

    l = plt.legend(loc='upper left', ncol=2, handlelength=0, handletextpad=0, columnspacing=0.5, fontsize=36)
    
    handles = plt.gca().get_legend().legendHandles
    
    for i, text in enumerate(l.get_texts()):
        text.set_color(lines[i].get_color())    
    

    编辑 (根据评论)

    您可以使用 lines 作为 ncol 将图例定义为

    l = plt.legend(loc='upper left',ncol=len(lines), handlelength=-0.2, columnspacing=-0.2, fontsize=36)
    

    还可以使用透明度参数删除/隐藏句柄。 alpha 通过将其设置为0

    handles[i].set_alpha(0)
    

    或者把它藏起来

    handles[i].set_visible(False)
    

    enter image description here