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

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

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


当前回答

如果您使用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)

其他回答

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

用法:

ax.get_legend().remove()

or

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

请参见这里介绍的提交。

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

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

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

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

如果您使用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)

你可以简单地这样做:

中心——axs [n]。传奇(loc =“左上”,ncol = 2, labelspacing = 0.01)

(我的4、5、6,7,8,9,10,11,12日,13日,14日,15日,16日,17日,18日19): 中心——axs[我].legend ([])

我将图例添加到图形中,而不是添加到轴上(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()