# 如何在 Matplotlib 中設定散點圖的標記大小

Suraj Joshi 2023年1月30日

Matplotlib 中散點圖中標記的大小由函式 `scatter()``s` 關鍵字引數控制，其中 `s` 是標量或陣列。

## 函式 `scatter()` 的 `s` 關鍵字引數

``````matplotlib.pyplot.scatter(
x,
y,
s=None,
c="b",
marker="o",
cmap=None,
norm=None,
vmin=None,
vmax=None,
alpha=None,
linewidths=None,
faceted=True,
verts=None,
hold=None,
**kwargs
)
``````

### 為所有點設定相同的標記大小

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

x = [1, 2, 3, 4, 5]
y = np.sin(x)

plt.scatter(x, y, s=500, c="magenta")

plt.title("Scatter plot of sinx")
plt.xlabel("x")
plt.ylabel("sinx")
plt.xlim(0, 6)
plt.ylim(-2, 2)
plt.show()
``````

### 不一致地增加點的標記大小

#### 標記寬度加倍

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

x = [1, 2, 3, 4, 5]
y = [a ** 2 for a in x]
s = [10 * 4 ** n for n in range(len(x))]
plt.scatter(x, y, s=s)
plt.title("Doubling width of marker in scatter plot")
plt.xlabel("x")
plt.ylabel("x**2")
plt.xlim(0, 6)
plt.ylim(0, 30)
plt.show()
``````

#### 標記面積加倍

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

x = [1, 2, 3, 4, 5]
y = [a ** 2 for a in x]
s = [10 * 2 ** n for n in range(len(x))]
plt.scatter(x, y, s=s)
plt.title("Doubling area of marker in scatter plot")
plt.xlabel("x")
plt.ylabel("x**2")
plt.xlim(0, 6)
plt.ylim(0, 30)
plt.show()
``````

## Matplotlib `plot` 方法中用 `markersize` 引數以控制大小

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

x = [1, 2, 3, 4, 5]
y = [0] * len(x)

plt.plot(x, y, "bo", markersize=10)
plt.show()
``````

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