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

删除seaborn lineplot图例标题

  •  13
  • Daniel  · 技术社区  · 6 年前

    我想把这个标题从我的海岸线图传说中删除。我试着用 this answer 无济于事:

    import matplotlib.pyplot as plt
    import seaborn as sns; sns.set()
    fmri = sns.load_dataset("fmri")
    fig, ax = plt.subplots()
    g = sns.lineplot(x="timepoint", y="signal", hue="event", data=fmri, ax=ax)
    ax.legend().set_title('')
    

    Seaborn lineplot still with 'event' title

    如果我试着将标题设置为 None . 有趣的是,将标题设置为其他的东西似乎与现有的标题不一致:

    ax.legend().set_title('Something else')
    

    Seaborn lineplot still with prepend title

    看起来seaborn把这个头衔当成了一个隐藏的传说条目。我该怎么解决?

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

    实际上,seaborn误用了一个图例标签作为(子组)标题。因此,我们可以删除这个标签,或者用自定义文本替换它。

    替换为自定义文本:

    legend = ax.legend()
    legend.texts[0].set_text("Whatever else")
    

    enter image description here

    移除标签:

    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles=handles[1:], labels=labels[1:])
    

    enter image description here

    移除标签后,您当然还可以设置另一个(真实的)标题:

    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles=handles[1:], labels=labels[1:], title="Whatever else")
    

    enter image description here

        2
  •  2
  •   badluck    5 年前

    扩展重要的最新答案:

    我也遇到了同样的问题,但是“删除标签”的例子从实际的图例中删除了标题和第一项。

    handles, labels = ax.get_legend_handles_labels() ax.legend(handles=handles[1:], labels=labels[1:])

    所以这只删除了传说的标题

    ax.legend(handles=handles[0:], labels=labels[0:])

    (我不能评论,所以把这个作为答案)