# 如何在 Matplotlib 中删除图例

Suraj Joshi 2023年1月30日

## `matplotlib.axes.Axes.get_legend().remove()`

``````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()`

``````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_` 参数

``````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()
``````

Suraj Joshi is a backend software engineer at Matrice.ai.