Python Scatter Plot with multiple Y values โ€‹โ€‹for each X

I am trying to use Python to create a scatter plot that contains two X categories "cat1" "cat2" and each category has multiple Y values. I can make this work if the number of Y values โ€‹โ€‹for each X value is the same using the following code:

import numpy as np import matplotlib.pyplot as plt y = [(1,1,2,3),(1,1,2,4)] x = [1,2] py.plot(x,y) plot.show() 

but as soon as the number of Y values โ€‹โ€‹for each X value does not match, I get an error. For example, this does not work:

  import numpy as np import matplotlib.pyplot as plt y = [(1,1,2,3,9),(1,1,2,4)] x = [1,2] plt.plot(x,y) plot.show() #note now there are five values for x=1 and only four for x=2. error 

How can I display different Y values โ€‹โ€‹for each X value and how to change the X axis from 1 and 2 to the text categories "cat1" and "cat2". I would really appreciate any help on this!

Here is an example image of the type of patch I'm trying to make:

http://s12.postimg.org/fa417oqt9/pic.png

+5
source share
1 answer

How can I display different y values โ€‹โ€‹for each x value

Just sketch each group separately:

 for xe, ye in zip(x, y): plt.scatter([xe] * len(ye), ye) 

and how can I change the X axis from the numbers 1 and 2 to the text categories "cat1" and "cat2".

Set tags and tag tags manually:

 plt.xticks([1, 2]) plt.axes().set_xticklabels(['cat1', 'cat2']) 

Full code:

 import matplotlib.pyplot as plt import numpy as np y = [(1,1,2,3,9),(1,1,2,4)] x = [1,2] for xe, ye in zip(x, y): plt.scatter([xe] * len(ye), ye) plt.xticks([1, 2]) plt.axes().set_xticklabels(['cat1', 'cat2']) plt.savefig('t.png') 

enter image description here

+12
source

Source: https://habr.com/ru/post/1238212/


All Articles