Scatter plots

Points, size, color, and alpha.

scatter draws one marker per point. Size and color can be arrays, so a third variable can ride along.

Goal

Plot a cloud, vary size and color, and set alpha so overlaps show.

A noisy line

rng = np.random.default_rng(0)
x = rng.normal(size=50)
y = 0.8 * x + rng.normal(scale=0.35, size=50)
fig, ax = plt.subplots()
ax.scatter(x, y, alpha=0.75)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Scatter")
plt.show()

Size and color

rng = np.random.default_rng(1)
x = rng.uniform(0, 10, size=40)
y = rng.uniform(0, 10, size=40)
sizes = 20 + 8 * y
fig, ax = plt.subplots()
pts = ax.scatter(x, y, s=sizes, c=y, cmap="viridis", alpha=0.85)
fig.colorbar(pts, ax=ax, label="y")
ax.set_title("Size and color track y")
plt.show()

Compare two cities

nairobi = np.array([50, 40, 80, 150], dtype=float)
mombasa = np.array([20, 15, 30, 90], dtype=float)
fig, ax = plt.subplots()
ax.scatter(nairobi, mombasa, s=80)
for i, month in enumerate(["Jan", "Feb", "Mar", "Apr"]):
    ax.annotate(month, (nairobi[i], mombasa[i]), textcoords="offset points", xytext=(6, 4))
ax.set_xlabel("Nairobi mm")
ax.set_ylabel("Mombasa mm")
ax.set_title("Monthly rain")
plt.show()
Tip

plot(..., marker="o", linestyle="none") is a scatter-like line plot. Prefer scatter when size or color varies per point.