# 在 Matplotlib 中為散點圖設定顏色

Suraj Joshi 2020年11月24日

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