# 在 Matplotlib 中为散点图设置颜色

Suraj Joshi 2024年2月15日

## 在 Scatterplot 中设置标记的颜色

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

x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 1, 4, 7, 4, 3, 2]

plt.scatter(x, y, c="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Simple Scatter Plot")
plt.show()
``````

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

x = [1, 2, 3, 4, 5, 6, 7]
y1 = [2, 1, 4, 7, 4, 3, 2]
y2 = [4, 4, 5, 3, 8, 9, 6]

plt.scatter(x, y1, c="red")
plt.scatter(x, y2, c="green")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Scatter Plot of two different datasets")
plt.show()
``````

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

x = np.array([1, 2, 3, 4, 5])
y = np.random.random((10, 5))

colors = cm.rainbow(np.linspace(0, 1, y.shape[0]))
for dataset, color in zip(y, colors):
plt.scatter(x, dataset, color=color)

plt.xlabel("X")
plt.ylabel("Y")
plt.show()
``````

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

x = np.array([1, 2, 3, 4, 5])
y = np.random.random((10, 5))

color_cycle = itertools.cycle(
["orange", "pink", "blue", "brown", "red", "grey", "yellow", "green"]
)

for row in y:
plt.scatter(x, row, color=next(color_cycle))

plt.xlabel("X")
plt.ylabel("Y")
plt.show()
``````

`itertools.cycle()` 方法将从给定的颜色集中创建一个循环列表，每一行都从循环列表中挑选一种颜色来绘制散点图。

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