【问题标题】:Matplotlib error while setting colors on a scatter plot在散点图上设置颜色时出现 Matplotlib 错误
【发布时间】: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


【解决方案1】:

有人评论(然后删除)参考了文档,但这是他们所指的部分(来自plt.scatter):

请注意,c 不应是单个数字 RGB 或 RGBA 序列,因为它与要进行颜色映射的值数组无法区分。如果要为所有点指定相同的 RGB 或 RGBA 值,请使用具有单行的二维数组。否则,在大小与 x 和 y 匹配的情况下,值匹配将优先。

但似乎另外,从here 来看,matplotlib 期望 RGB 值是从 0 到 1,而不是 0 到 255。所以我只是在 a) 显式转换 colors 中添加了两行作为numpy 2D 数组和 b) 将 RGB 值除以 255(保持 alpha 值不变)。

import matplotlib.pyplot as plt
import numpy as np

fig1, ax1 = plt.subplots()

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']]

#addition to convert colors
colors = np.array(colors)
colors[:,:3] /= 255

ax1.scatter(MyData['Date'], MyData["Rate"], s=20, c=colors, marker='_')

删除缩放(但仍转换为 2D 数组),您将得到与最初遇到的相同的错误,所以我猜当它无法识别 0 到 1 缩放的 RGB 值时,它会尝试仅解释扁平数组你就会遇到 4x 值问题。

【讨论】:

    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 2014-09-10
    • 2013-12-06
    • 2020-12-17
    • 2011-08-29
    • 2014-03-13
    • 2019-01-02
    相关资源
    最近更新 更多