如何在Matplotlib中将这20种随机颜色分配给20对随机的x,y对?

问题描述 投票:0回答:1

这将创建长度为20和20个RGB三连体的x和y。我想将每种颜色分配给一个点,并且从this answer开始,并回答了非常老的问题How to get different colored lines for different plots in a single figure?

但是我得到的是这个奇怪的输出,而不是二十个随机的颜色的随机点,这让我觉得我已经不懂了。

问题:如何将这20个随机颜色分配给20个随机的x,y对?

crazy plot

import numpy as np
import matplotlib.pyplot as plt

ran = np.random.random((5, 20))
x, y = ran[:2]
colors = ran[2:].T
print('colors.shape', colors.shape)
colors = [list(thing) for thing in colors] # removing this line doesn't affect the result

fig, ax = plt.subplots()
ax.plot(x, y, 'o', colors)   # ax.plot(x, y, 'o', color=colors) throws exception
plt.show()

注意:如果我改用ax.plot(x, y, 'o', color=colors),则会出现错误:

File "/path/to/matplotlib/colors.py", line 177, in to_rgba
rgba = _to_rgba_no_colorcycle(c, alpha)
File "/path/to/matplotlib/colors.py", line 240, in _to_rgba_no_colorcycle
raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
ValueError: Invalid RGBA argument:
python python-3.x matplotlib plot colors
1个回答
0
投票

尚不清楚为什么该图看起来像它的样子,但是OP 尝试尝试的内容现在显示为下面的“错误方式”。

解决方案是停止尝试在一行上为每个标记分配不同的颜色,而是制作一个散点图,这实际上是这样!

[wrong way right way

import numpy as np
import matplotlib.pyplot as plt

ran = np.random.random((6, 20))
x, y, s = ran[:3]
colors = ran[3:].T
print('colors.shape', colors.shape)
colors = [list(thing) for thing in colors]

fig, ax = plt.subplots()
ax.plot(x, y, 'o') 
for line, color in zip(ax.lines, colors):
        line.set_color(color)
ax.set_title('WRONG Way', fontsize=14)
plt.show()

fig, ax = plt.subplots()
ax.scatter(x, y, color=colors) 
ax.set_title('RIGHT Way', fontsize=14)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.