Remove seaborn lineplot legend title

前端 未结 3 522
无人共我
无人共我 2020-12-02 15:43

I would like to remove the title from my seaborn lineplot legend. I tried using this answer to no avail:

import matplotlib.pyplot as plt
import seaborn as sn         


        
相关标签:
3条回答
  • 2020-12-02 16:06

    Important: This answer is about the case when a hue is used that appears as a legend title. In all other cases, the question itself already contains the usual way to get rid of a title.

    Indeed, seaborn is misusing a legend label as a (subgroup-)title. Hence the idea can be to either remove this label, or replace it with custom text.

    Replacing with custom text:

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

    Removing the label:

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

    After having removed the label you may of course still set another (real) title:

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

    0 讨论(0)
  • 2020-12-02 16:11
    import seaborn as sns
    g = sns.lineplot(x="myXs", y="myYs", hue="myHue", data=mydf)
    g.legend_.set_title(None)
    
    0 讨论(0)
  • 2020-12-02 16:18

    Extending ImportanceOfBeingErnest's answer:

    I had the same problem, but the 'Removing the label' example removed the title and first item from the actual legend.

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

    So, this removes just the legend title:

    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles=handles, labels=labels)
    
    0 讨论(0)
提交回复
热议问题