![](/img/trans.png)
[英]Matplotlib: How to give color to scatterplot circles based on column values
[英]How to color scatterplot in matplotlib based on the values of y axis
大家好,我根據兩個列表做了一個分散的 plot。 現在我想根據 y 軸值為散點 plot 着色。 例如,如果 y 軸上的值大於 30000,我想將其塗成紅色,而 rest 所有值都為藍色? 最好的方法是什么
如果您使用的是 Numpy 的 ndarrays,那就更簡單了
import numpy as np
import matplotlib.pyplot as plt
# test data
y = np.random.randint(2800, 3100, size=(100,))
x = np.arange(0, 100)
# create a Boolean array (a mask), possibly negate it using the "~" unary operator
ygt3000 = y>3000
plt.scatter(x[~ygt3000], y[~ygt3000], color='blue')
plt.scatter(x[ygt3000], y[ygt3000], color='red')
如果您使用的是真實列表,它會稍微復雜一些,但可以使用列表推導來完成
x = x.tolist()
y = y.tolist()
ygt3000 = [val>3000 for val in y]
plt.scatter([xv for xv, ygt in zip(x, ygt3000) if not ygt],
[yv for yv, ygt in zip(y, ygt3000) if not ygt], color='blue')
plt.scatter([xv for xv, ygt in zip(x, ygt3000) if ygt],
[yv for yv, ygt in zip(y, ygt3000) if ygt], color='red')
這是上面代碼應用於兩個隨機數序列時的結果。
2021 年 8 月,因為 Trenton McKinney 做了一個漂亮的編輯(謝謝 Trenton)這篇文章再次引起了我的注意,我看到了曙光
plt.scatter(x, y, c=['r' if v>3000 else 'b' for v in y])
僅僅一天后,我意識到 Numpy 可以使用類似的壯舉,利用高級索引
plt.scatter(x, y, c=np.array(('b','r'))[(y>3000).astype(int)])
但老實說,我更喜歡我以前使用過的兩遍方法,因為它更切中要害,傳達了更多的意義。 或者,換句話說,后者看起來是混淆代碼......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.