如何在 Matplotlib 中删除图例
Suraj Joshi
2023年1月30日
Matplotlib
Matplotlib Legend
-
matplotlib.axes.Axes.get_legend().remove() -
matplotlib.axes.Axes.get_legend().set_visible() -
matplotlib.axes.Axes.plot()方法中的label=_nolegend_参数 -
将
axis对象的legend_属性设置为 None
我们可以使用图例对象的 remove() 和 set_visible() 方法从 Matplotlib 中的图形中删除图例。我们还可以通过以下方式从 Matplotlib 中的图形中删除图例:将 plot() 方法中的 label 设置为 _nolegend_,将 axes.legend 设置为 None 以及将 figure.legends 设置为空列表。
matplotlib.axes.Axes.get_legend().remove()
我们可以使用 matplotlib.axes.Axes.get_legend().remove() 方法从 Matplotlib 中的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 100)
y1 = np.exp(x)
y2 = 3 * x + 2
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, y1, c="r", label="expoential")
ax.plot(x, y2, c="g", label="Straight line")
leg = plt.legend()
ax.get_legend().remove()
plt.show()
输出:

matplotlib.axes.Axes.get_legend().set_visible()
如果我们将 False 作为参数传递给 matplotlib.axes.Axes.get_legend().set_visible() 方法,则可以从 Matplotlib 中的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 100)
y1 = np.exp(x)
y2 = 3 * x + 2
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, y1, c="r", label="expoential")
ax.plot(x, y2, c="g", label="Straight line")
leg = plt.legend()
ax.get_legend().set_visible(False)
plt.show()
输出:

此方法实际上将图例设置为不可见,但不会删除图例。
matplotlib.axes.Axes.plot() 方法中的 label=_nolegend_ 参数
在 matplotlib.axes.Axes.plot()方法中将 label=_nolegend_ 作为参数传递也会从 Matplotlib 的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 100)
y1 = np.exp(x)
y2 = 3 * x + 2
fig, ax = plt.subplots(figsize=(8, 6))
leg = plt.legend()
ax.plot(x, y1, c="r", label="_nolegend_")
ax.plot(x, y2, c="g", label="_nolegend_")
plt.show()
输出:

将 axis 对象的 legend_ 属性设置为 None
将 axis 对象的 legend_ 属性设置为 None 可以从 Matplotlib 中的图形中删除图例。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 100)
y1 = np.exp(x)
y2 = 3 * x + 2
fig, ax = plt.subplots(figsize=(8, 6))
leg = plt.legend()
ax.plot(x, y1, c="r", label="expoential")
ax.plot(x, y2, c="g", label="Straight line")
plt.gca.legend_ = None
plt.show()
输出:

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj Joshi
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn