matplotlib scatter fails with error: 'c' argument has n elments, which is not acceptable for use with 'x' with size n, 'y' with size n

依然范特西╮ 提交于 2020-01-10 05:10:08

问题


I am trying to create a scatter plot using matplotlib where each point has a specific color value.

I scale the values and then apply alpha blending between a 'left' and a 'right' color.

# 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)

However the last line gives the error:

'c' argument has 1134 elements, which is not acceptable for use with 'x' with size 1134, 'y' with size 1134

The scatter documentation says for paramter 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.

Where i want to use the last option with RGB values.

I replaced the check values here comment with some print statements:

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

wich gave the results:

[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)

回答1:


Convert colors to a float array with 0 <= colors <= 1 and it should work fine.

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



来源:https://stackoverflow.com/questions/57113398/matplotlib-scatter-fails-with-error-c-argument-has-n-elments-which-is-not-ac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!