【问题标题】:matplotlib scatter fails with error: 'c' argument has n elements, which is not acceptable for use with 'x' with size n, 'y' with size nmatplotlib scatter 失败并出现错误:'c' 参数有 n 个元素,不能与大小为 n 的'x'、大小为 n 的'y'一起使用
【发布时间】:2019-11-28 12:05:38
【问题描述】:

我正在尝试使用 matplotlib 创建一个散点图,其中每个点都有一个特定的颜色值。

我缩放这些值,然后在“左”和“右”颜色之间应用 Alpha 混合。

# initialization
from matplotlib import pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import numpy as np

values = np.random.rand(1134)

# actual code
colorLeft = np.array([112, 224, 112])
colorRight = np.array([224, 112, 112])
scaled = MinMaxScaler().fit_transform(values.reshape(-1, 1))
colors = np.array([a * colorRight + (1 - a) * colorLeft for a in scaled], dtype = np.int64)
# check values here
f, [sc, other] = plt.subplots(1, 2)
sc.scatter(np.arange(len(values)), values, c = colors)

但是最后一行给出了错误:

'c' 参数有 1134 个元素,不能与大小为 1134 的 'x' 和大小为 1134 的 'y' 一起使用

scatter documentation 表示参数 c

c : 颜色、序列或颜色序列,可选

标记颜色。可能的值:

  A single color format string.
  A sequence of color specifications of length n.
  A sequence of n numbers to be mapped to colors using cmap and norm.
  A 2-D array in which the rows are RGB or RGBA.

我想在哪里使用带有 RGB 值的最后一个选项。

我用一些打印语句替换了check values here 注释:

print(values)
print(colors)
print(values.shape)
print(colors.shape)

给出了结果:

[0.08333333 0.08333333 0.08333333 ... 1.         1.         1.08333333]
[[112 224 112]
 [112 224 112]
 [112 224 112]
 ...
 [214 121 112]
 [214 121 112]
 [224 111 112]]
(1134,)
(1134, 3)

【问题讨论】:

    标签: python matplotlib scatter-plot


    【解决方案1】:

    将颜色转换为具有 0

    sc.scatter(np.arange(len(values)), values, c = colors/255)

    【讨论】:

    • 如果我的生活是一部侦探小说,那错误信息将是一条红鲱鱼......
    • 你为什么将颜色除以 255?
    猜你喜欢
    • 2021-12-14
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多