# 如何在 Matplotlib 中制作散点图的图例

Suraj Joshi 2023年1月30日

## 在 Maptlotlib `2D` 散点图中添加图例

``````import numpy as np
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

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

plt.scatter(x, y1, marker="x", color="r", label="x**2")
plt.scatter(x, y2, marker="o", color="b", label="2*x+1")
plt.legend()
plt.show()
``````

``````import numpy as np
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

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

plt.scatter(x, y1, marker="x", color="r")
plt.scatter(x, y2, marker="o", color="b")
plt.legend(("x**2", "2*x+1"), loc="center left")
plt.show()
``````

## 在 Matplotlib `3D` 散点图上添加图例

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

x = [1, 2, 3, 4, 5]
y = [2, 1, 4, 5, 6]

z1 = [i + j for (i, j) in zip(x, y)]
z2 = [3 * i - j for (i, j) in zip(x, y)]

axes = plt.subplot(111, projection="3d")
axes.plot(x, y, z1, "x", label="x+y")
axes.plot(x, y, z2, "o", label="3*x-y")

plt.legend(loc="upper left")
plt.show()
``````

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