Sytze Andringa
Sytze Andringa

Reputation: 423

pyplot, plotting from left to right

I have some data I want to plot, x and y is in the same format as this small piece of example code.

    import matplotlib.pyplot as plt

    y = [1,1,3,4]
    x = [1,4,2,3]
    plt.plot(x,y,'-o')
    plt.show()

This results in quite a weird graph. wrong graph

What pyplot does is drawing a line from the first point inserted to the second, then to the third etc. I want it to draw a line from low-x to high-x, but I can seem to find a nice way to do this. I want my line to be like this.

correct graph

What is the easiest way to achieve this, given my x and y data is in the same format but more complex than this example?

Upvotes: 0

Views: 1766

Answers (2)

Eular
Eular

Reputation: 1807

you can sort your x list with simultaneously changing the y,

import matplotlib.pyplot as plt

y = [1,1,3,4]
x = [1,4,2,3]



for i in range(len(x)):
    for k in range( len( x ) - 1, i, -1 ):
        if ( x[k] < x[k - 1] ):
            x[k-1],x[k]=x[k],x[k-1] 
            y[k-1],y[k]= y[k],y[k-1]


print x,y
plt.plot(x,y,'-o')
plt.show()

Upvotes: 0

dnit13
dnit13

Reputation: 2496

To get the graph as you mentioned, you need to have values in x in sorted order, which you can achieve like this:

z = sorted(zip(x,y))
x=[i[0] for i in z]
y=[i[1] for i in z]

and now using x and y for ploting (not tested).

Upvotes: 3

Related Questions