0

This creates x and y of length 20 and 20 RGB triplets. I'd like to assign each color to one point and have started from this answer and answers to the very old question How to get different colored lines for different plots in a single figure?.

But instead of twenty random dots of random colors I get this weird output, which makes me think that I don't understand anything anymore.

Question: How can I assign these 20 random colors to the 20 random x, y pairs?

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

Note: If instead I try ax.plot(x, y, 'o', color=colors) I get errors:

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:
William Miller
  • 9,839
  • 3
  • 25
  • 46
uhoh
  • 3,713
  • 6
  • 42
  • 95

1 Answers1

0

It's not clear why that plot looks the way it does, but what the OP meant to try is now shown as the "wrong way" below.

The solution is to stop trying to assign a different color to each marker on a single line, but instead to make a scatter plot which is what this really is!

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()
uhoh
  • 3,713
  • 6
  • 42
  • 95