Remove the legend on a matplotlib figure

后端 未结 8 1143
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 19:01

To add a legend to a matplotlib plot, one simply runs legend().

How to remove a legend from a plot?

(The closest I came to this

8条回答
  •  Happy的楠姐
    2020-11-30 19:16

    According to the information from @naitsirhc, I wanted to find the official API documentation. Here are my finding and some sample code.

    1. I created a matplotlib.Axes object by seaborn.scatterplot().
    2. The ax.get_legend() will return a matplotlib.legned.Legend instance.
    3. Finally, you call .remove() function to remove the legend from your plot.
    ax = sns.scatterplot(......)
    _lg = ax.get_legend()
    _lg.remove()
    

    If you check the matplotlib.legned.Legend API document, you won't see the .remove() function.

    The reason is that the matplotlib.legned.Legend inherited the matplotlib.artist.Artist. Therefore, when you call ax.get_legend().remove() that basically call matplotlib.artist.Artist.remove().

    In the end, you could even simplify the code into two lines.

    ax = sns.scatterplot(......)
    ax.get_legend().remove()
    

提交回复
热议问题