要将图例添加到matplotlib图例中,只需运行legend()。

如何从一个情节中移除一个传说?

(我最接近这一点的是运行legend([]),以便从数据中清空传说。但这在右上角留下了一个丑陋的白色矩形。)


当前回答

根据@naitsirhc提供的信息,我想找到官方的API文档。下面是我的发现和一些示例代码。

我创建了一个matplotlib。通过seaborn.scatterplot()实现坐标轴对象。 ax.get_legend()将返回matplotlib. leged . legend实例。 最后,调用.remove()函数从图中删除图例。

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

如果你检查matplotlib.legned.Legend API文档,你不会看到.remove()函数。

原因是matplotlib. leged . legend继承了matplotlib.artist.Artist。因此,当你调用ax.get_legend().remove()时,基本上会调用matplotlib.artist.Artist.remove()。

最后,您甚至可以将代码简化为两行。

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

其他回答

如果你把pyplot称作PLT

frameon=False是删除图例周围的边框

“传递的信息是,图例中不应该有变量

import matplotlib.pyplot as plt
plt.legend('',frameon=False)

你必须添加以下几行代码:

ax = gca()
ax.legend_ = None
draw()

Gca()返回当前坐标轴句柄,并具有传奇_属性

从matplotlib v1.4.0rc4开始,删除方法已经添加到图例对象中。

用法:

ax.get_legend().remove()

or

legend = ax.legend(...)
...
legend.remove()

请参见这里介绍的提交。

如果你不使用fig和ax plot对象,你可以这样做:

import matplotlib.pyplot as plt

# do plot specifics
plt.legend('')
plt.show() 

我将图例添加到图形中,而不是添加到轴上(matplotlib 2.2.2)。为了移除它,我将图形的legends属性设置为一个空列表:

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.plot(range(10), range(10, 20), label='line 1')
ax2.plot(range(10), range(30, 20, -1), label='line 2')

fig.legend()

fig.legends = []

plt.show()