252

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

如何从情节中删除图例?

(我最接近的方法是运行legend([])以从数据中清空图例。但这会在右上角留下一个难看的白色矩形。)

4

9 回答 9

352

matplotlibv1.4.0rc4开始,一个remove方法已添加到图例对象中。

用法:

ax.get_legend().remove()

或者

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

请参阅此处以了解引入此内容的提交。

于 2014-11-10T14:21:42.400 回答
137

如果要绘制 Pandas 数据框并删除图例,请将 legend=None 作为参数添加到 plot 命令。

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()
于 2014-11-13T15:41:19.143 回答
98

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

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

这是基于提供给我的回答,以回答我前段时间在这里遇到的类似问题

(感谢 Jouni 的回答 - 很抱歉我无法将问题标记为已回答......也许有权限的人可以为我这样做?)

于 2011-04-25T20:47:18.637 回答
18

您必须添加以下代码行:

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

gca() 返回当前坐标区句柄,并具有该属性 legend_

于 2011-04-20T18:58:40.323 回答
13

如果你打电话pyplotplt

frameon=False就是去掉图例周围的边框

和 '' 传递的信息是图例中不应包含任何变量

import matplotlib.pyplot as plt
plt.legend('',frameon=False)
于 2020-02-27T17:18:22.673 回答
10

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

import matplotlib.pyplot as plt

# do plot specifics
plt.legend('')
plt.show()
于 2019-05-23T09:52:34.350 回答
8

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

  1. 我创建了一个matplotlib.Axes对象seaborn.scatterplot()
  2. ax.get_legend()返回一个matplotlib.legned.Legend实例。
  3. 最后,您调用.remove()函数从绘图中删除图例。
ax = sns.scatterplot(......)
_lg = ax.get_legend()
_lg.remove()

如果您查看matplotlib.legned.LegendAPI 文档,您将看不到该.remove()功能。

原因是matplotlib.legned.Legend继承了matplotlib.artist.Artist. 因此,当您调用时ax.get_legend().remove(),基本上调用matplotlib.artist.Artist.remove().

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

ax = sns.scatterplot(......)
ax.get_legend().remove()
于 2020-07-02T02:31:23.803 回答
2

我通过将它添加到图形而不是轴(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()
于 2018-10-16T15:39:02.753 回答
0

如果您使用的是 seaborn,则可以使用参数legend。即使您在同一个图中多次绘制。一些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)
于 2021-06-11T23:43:49.340 回答