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