删除 matplotlib 图上的图例

发布于 2024-11-02 17:07:21 字数 170 浏览 5 评论 0原文

要向 matplotlib 绘图添加图例,只需运行 legend() 即可。

如何从图中删除图例?

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

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 is to run legend([]) in order to empty the legend from data. But that leaves an ugly white rectangle in the upper right corner.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

别挽留 2024-11-09 17:07:21

matplotlib v1.4.0rc4 ,一个 remove 方法已添加到图例对象中。

用法:

ax.get_legend().remove()

或者

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

请参阅此处了解引入此功能的提交。

As of matplotlib v1.4.0rc4, a remove method has been added to the legend object.

Usage:

ax.get_legend().remove()

or

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

See here for the commit where this was introduced.

与风相奔跑 2024-11-09 17:07:21

如果要绘制 Pandas 数据框并删除图例,请将 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=False)
plt.show()

If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.

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

df2 = pd.DataFrame(np.random.randn(10, 5))
df2.plot(legend=False)
plt.show()
阳光下慵懒的猫 2024-11-09 17:07:21

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

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

这是基于我为回答我不久前遇到的类似问题而提供的答案此处

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

You could use the legend's set_visible method:

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

This is based on a answer provided to me in response to a similar question I had some time ago here

(Thanks for that answer Jouni - I'm sorry I was unable to mark the question as answered... perhaps someone who has the authority can do so for me?)

琉璃繁缕 2024-11-09 17:07:21

如果您将 pyplot 调用为 plt

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

,并且 '' 正在传递不应有任何变量的信息传说中

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

if you call pyplot as plt

frameon=False is to remove the border around the legend

and '' is passing the information that no variable should be in the legend

import matplotlib.pyplot as plt
plt.legend('',frameon=False)
孤凫 2024-11-09 17:07:21

您必须添加以下代码行:

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

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

you have to add the following lines of code:

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

gca() returns the current axes handle, and has that property legend_

烟燃烟灭 2024-11-09 17:07:21

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

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

如果您检查 matplotlib.legend.LegendAPI 文档中,您不会看到 .remove() 函数。

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

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

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

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.legend.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.legend.Legend API document, you won't see the .remove() function.

The reason is that the matplotlib.legend.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()
指尖上得阳光 2024-11-09 17:07:21

我通过将其添加到图形而不是轴(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()

I made a legend by adding it to the figure, not to an axis (matplotlib 2.2.2). To remove it, I set the legends attribute of the figure to an empty list:

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()
清旖 2024-11-09 17:07:21

如果您不使用无花果和斧头图对象,您可以这样做:

import matplotlib.pyplot as plt

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

If you are not using fig and ax plot objects you can do it like so:

import matplotlib.pyplot as plt

# do plot specifics
plt.legend('')
plt.show() 
空城仅有旧梦在 2024-11-09 17:07:21

以下是使用 matplotlibseaborn 处理子图的图例删除和操作的更复杂示例:

从 seaborn 中获取由 Axes 创建的 Axes 对象code>sns.() 并按照 @naitsirhc。下面的示例还展示了如何将图例放在一边,以及如何处理子图的上下文。

# imports
import seaborn as sns
import matplotlib.pyplot as plt

# get data
sns.set()
sns.set_theme(style="darkgrid")
tips = sns.load_dataset("tips")

# subplots
fig, axes = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12,6)) 
fig.suptitle('Example of legend manipulations on subplots with seaborn')

g0 = sns.pointplot(ax=axes[0], data=tips, x="day", y="total_bill", hue="size")
g0.set(title="Pointplot with no legend")
g0.get_legend().remove() # <<< REMOVE LEGEND HERE 

g1 = sns.swarmplot(ax=axes[1], data=tips, x="day", y="total_bill", hue="size")
g1.set(title="Swarmplot with legend aside")
# change legend position: https://www.statology.org/seaborn-legend-position/
g1.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)

示例使用seaborn对子图进行图例操作

Here is a more complex example of legend removal and manipulation with matplotlib and seaborn dealing with subplots:

From seaborn, get the Axes object created by sns.<some_plot>() and do ax.get_legend().remove() as indicated by @naitsirhc. The following example also shows how to put the legend aside, and how to deal in a context of subplots.

# imports
import seaborn as sns
import matplotlib.pyplot as plt

# get data
sns.set()
sns.set_theme(style="darkgrid")
tips = sns.load_dataset("tips")

# subplots
fig, axes = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(12,6)) 
fig.suptitle('Example of legend manipulations on subplots with seaborn')

g0 = sns.pointplot(ax=axes[0], data=tips, x="day", y="total_bill", hue="size")
g0.set(title="Pointplot with no legend")
g0.get_legend().remove() # <<< REMOVE LEGEND HERE 

g1 = sns.swarmplot(ax=axes[1], data=tips, x="day", y="total_bill", hue="size")
g1.set(title="Swarmplot with legend aside")
# change legend position: https://www.statology.org/seaborn-legend-position/
g1.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)

Example of legend manipulations on subplots with seaborn

失与倦" 2024-11-09 17:07:21

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

If you are using seaborn you can use the parameter legend. Even if you are ploting more than once in the same figure. Example with some 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)
心头的小情儿 2024-11-09 17:07:21

你可以简单地这样做:

axs[n].legend(loc='upper left',ncol=2,labelspacing=0.01)

for i in [4,5,6,7,8 ,9,10,11,12,13,14,15,16,17,18,19]:
axs[i].legend([])

you could simply do:

axs[n].legend(loc='upper left',ncol=2,labelspacing=0.01)

for i in [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]:
axs[i].legend([])

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文