# 如何在 Matplotlib 中用线连接散点图点

Suraj Joshi 2023年1月30日

## 在调用 scatter()和 plot()之后调用 show()

`matplotlib.pyplot.scatter(x, y)`，其中 `x` 是 x 坐标序列，而 `y` 是 y 坐标序列会创建点的散点图。要按顺序连接这些散点图的点，请调用 `matplotlib.pyplot.plot(x, y)`，使 `x``y` 与传递给 `scatter()` 函数的点相同。

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

x = np.linspace(0, 5, 50)
y = np.sin(2 * np.pi * x)

plt.scatter(x, y)
plt.plot(x, y)
plt.title("Connected Scatterplot points with line")
plt.xlabel("x")
plt.ylabel("sinx")
plt.show()
figure.tight_layout()
``````

## 具有线型属性的 `matplotlib.pyplot.plot()` 函数

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

x = np.linspace(0, 5, 50)
y = np.sin(2 * np.pi * x)

plt.plot(x, y, linestyle="solid", color="blue")
plt.title("Connected Scatterplot points with line")
plt.xlabel("x")
plt.ylabel("sinx")
plt.show()
figure.tight_layout()
``````

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

x = np.linspace(0, 5, 50)
y = np.sin(2 * np.pi * x)

plt.plot(x, y, "xb-")
plt.title("Connected Scatterplot points with line")
plt.xlabel("x")
plt.ylabel("sinx")
plt.show()
``````

## 关键字 `zorder` 更改 Matplotlib 绘图顺序

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

x = np.linspace(0, 5, 50)
y = np.sin(2 * np.pi * x)

plt.scatter(x, y, color="r", zorder=1)
plt.plot(x, y, color="b", zorder=2)

plt.title("Connected Scatterplot points with line")
plt.xlabel("x")
plt.ylabel("sinx")

plt.show()
``````

plot()的顺序为 2，大于 scatter()的顺序，因此，散点图位于线图的顶部。

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

x = np.linspace(0, 5, 50)
y = np.sin(2 * np.pi * x)

plt.scatter(x, y, color="r", zorder=2)
plt.plot(x, y, color="b", zorder=1)

plt.title("Connected Scatterplot points with line")
plt.xlabel("x")
plt.ylabel("sinx")

plt.show()
``````

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