2

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!

dani_anyman
  • 133
  • 5
  • The first tuple in `y` has 5 entries, but you only have 4 `x` values. What is the expected outcome of this? – ImportanceOfBeingErnest Jul 02 '17 at 21:38
  • @ImportanceOfBeingErnest I like to plot all several y values for each x (in my real code, every tuple includes 1000 numbers), so the first tuple is plotted over the first xtick, the next tuple is plotted over the next xtick etc. I had no problems with the different number of values. Do you see a mistake here? – dani_anyman Jul 03 '17 at 09:02

1 Answers1

2

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)
BrenBarn
  • 242,874
  • 37
  • 412
  • 384