# 如何在 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.