简体   繁体   中英

Matplotlib scatter plot with 2 y-points per x-point

I want to create a Scatter plot using Matplotlib.

I have an array of IDs for the x-axis. It looks something like this:

x = [1, 2, 3, ...]
#Length = 418

For the y-axis, I have an array of tupples. It looks something like this:

y = [(1, 1), (1, 0), (0, 0), (0, 1), ...]
#Length = 418

I would like to plot this in a scatter plot so that for each ID (on the x-axis) it shows a red dot for the first value of the corresponding tupple and a blue dot for the second value of the correspond tuple.

I tried this code:

plt.plot(x, y, 'o')
plt.xlim(xmin=900, xmax=1300)
plt.ylim(ymin=-1, ymax=2)
plt.yticks(np.arange(2), ('Class 0', 'Class 1'))
plt.xlabel('ID')
plt.ylabel('Class')
plt.show()

It shows this result:

my_plot

How can I make this plot more clear?

Also, when I zoom in, I notice that the points are offset? How can I place them directly above each other?

zoomed_plot

You'll need to massage your data so that you have flat lists I think.

The most intuitive way to do this I think to define two lists, y1 , y2 and loop through your original y appending the correct values to them:

y1 = []
y2 = []

for i, j in y:
    y1.append(i)
    y2.append(j)

Then you can just plot the red and blue scatter graph with two calls to plt.scatter

plt.scatter(x, y1, c = 'r')
plt.scatter(x, y2, c = 'b')

hope that helps!

You need to store your data in two lists/tuples instead of one list of two-item tuples, because this is what plt.plot needs as input. The best way would be to reorganize your data like this, but if you are stuck with this list of tuples (or you need this data format for other reasons), you can create lists on the go:

plt.plot(x, [i for (i,j) in y], 'ro')
plt.plot(x, [j for (i,j) in y], 'bo')

Note that if you want two different data lines with two different colors, you will need two plt.plot(..) lines.

To avoid your markers overlapping each other, either you can change their shape or size (or both):

plt.plot(x, [i for (i,j) in y], 'rs', markersize = 12 )
plt.plot(x, [j for (i,j) in y], 'bo', markeresize = 8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM