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