python - matplotlib scatter 失败并出现错误 : 'c' argument has n elements,,这对于大小为 n 的 'x'、大小为 n 的 'y' 来说是 Not Acceptable

标签 python matplotlib scatter-plot

我正在尝试使用 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' argument has 1134 elements, which is not acceptable for use with 'x' with size 1134, 'y' with size 1134


scatter documentation表示参数 c

c : color, sequence, or sequence of color, optional

The marker color. Possible values:

  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)

最佳答案

将颜色转换为 0 <= 颜色 <= 1 的浮点数组,它应该可以正常工作。
sc.scatter(np.arange(len(values)), values, c = colors/255)

关于python - matplotlib scatter 失败并出现错误 : 'c' argument has n elements,,这对于大小为 n 的 'x'、大小为 n 的 'y' 来说是 Not Acceptable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57113398/

相关文章:

python - 在倒排索引中搜索普通查询

python - 在 Pyspark 中将列类型从字符串更改为日期

python - Pyspark数据框架中的访问结构元素如何?

python - 是否有任何不是 float 但可以在 MySQL 中接受为 float 的对象?

css - 使用 CSS 或 Canvas 的 Web 3D 散点图 (XYZ/RGB)

java - 3D散点图JavaFX : How to show legend and measures near axis

python - matplotlib Axis 值未排序

python - vtk 中是否有可用的颜色映射预设?

python - 带有 pandas 和 Jupyter notebook 的交互式箱线图

python - 如何在 matplotlib 中绘制 3D 补丁集合?