# 如何在 Matplotlib 中指定圖形座標中的圖例位置

Suraj Joshi 2024年2月15日

## 示例：Matplotlib 在圖形座標中指定圖例位置

``````import matplotlib.pyplot as plt

x = [1, 2, 3]
y1 = [0.5 * i + 1 for i in x]
y2 = [2 * i + 1 for i in x]

fig, ax = plt.subplots(2, 1)

ax[0].plot(x, y1, "b-", label="0.5x+1")
ax[0].plot(x, y2, "g-", label="2x+1")
ax[0].legend(loc="best")

ax[1].plot(x, y1, "b-", label="0.5x+1")
ax[1].plot(x, y2, "g-", label="2x+1")
ax[1].legend(loc="lower left")

plt.tight_layout()
plt.show()
``````

`loc` 引數可以取以下任意一個值。

`best`
`upper right`
`upper left`
`lower left`
`lower right`
`right`
`center left`
`center right`
`lower center`
`upper center`
`center`

``````import matplotlib.pyplot as plt

x = [1, 2, 3]
y1 = [0.5 * i + 1 for i in x]
y2 = [2 * i + 1 for i in x]

fig, ax = plt.subplots(2, 1)

ax[0].plot(x, y1, "b-", label="Plot-1")
ax[0].plot(x, y2, "g-", label="Plot-2")
ax[0].legend(loc="upper left", bbox_to_anchor=(0.9, 0.75))
ax[0].scatter((0.9), (0.75), s=70, c="red", transform=ax[0].transAxes)

ax[1].plot(x, y1, "b-", label="Plot-1")
ax[1].plot(x, y2, "g-", label="Plot-2")
ax[1].legend(loc="center right", bbox_to_anchor=(0.6, 0.4))
ax[1].scatter((0.6), (0.4), s=70, c="red", transform=ax[1].transAxes)

plt.tight_layout()
plt.show()
``````

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