Matplotlib connecting wrong points in line plot

I am drawing two lists using the ppton matplotlib library. There are two arrays x and y that look like this when overlaid -

Click here for the plot (sorry you don't have enough reputation to post photos here)

The code used is -

import matplotlib.pyplot as plt
plt.plot(x,y,"bo")
plt.fill(x,y,'#99d8cp')

      

It displays the points, then connects the points using a string. But the problem is that it doesn't connect the dots correctly. Points 0 and 2 on the x-axis are not connected correctly, not 1 and 2. Similarly, at the other end, it connects points 17-19 instead of 18-19. I also tried to plot a simple line graph using -

plt.plot(x,y)

      

But then they also connected the points incorrectly. It would be very helpful if someone could point me in the right direction as to why this is happening and what can be done to resolve it.

Thank!!

+3


source to share


1 answer


Matplotlib lines assume the coordinates are ok, so you connect your points in a "weird" way (although just like you told matplotlib, for example (0,1) to (3,2)). You can fix this by simply sorting the data before printing. In the meantime, there is no need to know about it. ”

#! /usr/bin/env python
import matplotlib.pyplot as plt
x = [20, 21, 22, 23, 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16, 19, 18]
y = [ 1,  1,  1,  1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,  2,  2,  2,  2,  2,  2,  2,  2,  1,  1]

x2,y2 = zip(*sorted(zip(x,y),key=lambda x: x[0]))

plt.plot(x2,y2)
plt.show()

      



This should give you what you want, as shown below:

enter image description here

+3


source







All Articles