【发布时间】:2020-06-22 20:35:47
【问题描述】:
我正在尝试使用 Matplotlib 绘制散点图,但在设置颜色时遇到了麻烦。
这是我的代码:
colors = [(141, 0, 248, 0.4) if x >= 150 and x < 200 else
(0, 244, 248, 0.4) if x >= 200 and x < 400 else
(255, 255, 0, 0.7) if x >= 400 and x < 600 else
(255, 140, 0, 0.8) if x >= 600 else (255, 0, 0, 0.8) for x in MyData.Qty]
print(len(colors))
ax1.scatter(MyData.Date, MyData.Rate, s=20, c=colors, marker='_')
基本上,我的数据框上有一个名为Qty 的列,并根据该值选择颜色。例如,如果数量大于 x,颜色将为红色等。
前面的代码会给我以下错误:
'c' argument has 2460 elements, which is inconsistent with 'x' and 'y' with size 615.
我不知道为什么会这样,因为如果我尝试以下代码,它将毫无问题地工作:
colors = ['red' if x >= 150 and x < 200 else
'yellow' if x >= 200 and x < 400 else
'green' if x >= 400 and x < 600 else
'blue' if x >= 600 else 'purple' for x in MyData.Qty]
这是我的数据示例:
Date Rate Qty
0 18 140 207.435145
0 18 141 155.019884
0 18 178 1222.215201
0 18 230 256.010358
0 19 9450 1211.310384
以下内容也可以:
colors = [(1,1,0,0.8) if x>1000 else (1,0,0,0.4) for x in MyData.Qty]
【问题讨论】:
-
但我使用的是二维数组,请参阅代码末尾的编辑。出于某种原因,如果我将颜色设置为 (1,1,0,0.8),它将起作用
标签: python python-3.x matplotlib