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

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

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


当前回答

如果你把pyplot称作PLT

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

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

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

其他回答

如果你想绘制一个Pandas数据帧,并且想要删除图例,在plot命令中添加legend=None作为参数。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df2 = pd.DataFrame(np.random.randn(10, 5))
df2.plot(legend=None)
plt.show()

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

用法:

ax.get_legend().remove()

or

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

请参见这里介绍的提交。

如果您使用seaborn,您可以使用参数图例。即使你在同一个数字上画了不止一次。使用一些df的例子

import seaborn as sns

# Will display legend
ax1 = sns.lineplot(x='cars', y='miles', hue='brand', data=df)

# No legend displayed
ax2 = sns.lineplot(x='cars', y='miles', hue='brand', data=df, legend=None)

你可以使用图例的set_visible方法:

ax.legend().set_visible(False)
draw()

这是基于一段时间前我在这里遇到的类似问题的答案

(谢谢你的回答,Jouni -我很抱歉我不能把问题标记为回答…也许有权威的人可以为我做这件事?)

根据@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()