dani_anyman
dani_anyman

Reputation: 133

matplotlib - scatterplot, choose colours for y tuples

I am new to Python and I am trying to create a scatterplot showing several y values for each xtick. I found this question which helped me to come up with some kind of code: Python Scatter Plot with Multiple Y values for each X.

x = [1,2,3,4]
y = [(1,1,2,3,9),(1,1,2,4), (0.5,4), (0.1,2)]

for xe, ye in zip(x, y):
    plt.scatter([xe] * len(ye), ye, color=['blue', 'red'])

plt.xticks([1, 2, 3, 4])
plt.axes().set_xticklabels(['5', '10', '15', '25'])
plt.ylim(0, 1)

plt.show()

The problem is, that for instance, this code alternately prints the points of the 1st tuple in red and blue. However, I like to print all the points of the 1st tuple (e.g. (1,1,2,3,9)) in blue, all points of the next tuple (e.g. (1,1,2,4)) in red etc. Is there a way to specify the colour in such a way? I have not come across a similar question yet.

I really appreciate any hint or help!

Upvotes: 2

Views: 502

Answers (1)

BrenBarn
BrenBarn

Reputation: 251478

Use itertools.cycle to cycle your colors, and zip them with your tuples in the loop:

for (xe, ye), color in zip(zip(x, y), itertools.cycle(['blue', 'red'])):
    pyplot.scatter([xe] * len(ye), ye, color=color)

Upvotes: 2

Related Questions