bmuory bmuory
bmuory bmuory

Reputation: 23

points to be plotted are not in order

Few data points have been obtained from an expt,but they are not in order ,so the lines between plots are not correct, I need to plot them in say, increasing order in Xaxis

C=[0.5,4,2,1,3,8,6,10]
D=[20,2,2,10,0.3,2.5,0.8,1]
%matplotlib inline
import matplotlib.pyplot as plt
#plot obtained from given data points
plt.plot(C,D)


## required plot 
A=[0.5, 1, 2, 3, 4, 6, 8, 10]
B=[20, 10, 2, 0.5, 2, 0.8, 2.5, 1]
plt.plot(A,B)

Upvotes: 0

Views: 1220

Answers (2)

Sheldore
Sheldore

Reputation: 39072

Your C is not sorted and hence by default the points which are joined by a continuous line seems like a mess in your output of plot(C,D). I personally would make use of the np.argsort function to get the sorted indices of C and use them to plot C and D as follows (showing only relevant lines added):

import numpy as np
C = np.array([0.5,4,2,1,3,8,6,10])
D = np.array([20,2,2,10,0.3,2.5,0.8,1])
plt.plot(sorted(C), D[np.argsort(C)], 'b')

Output

enter image description here

Upvotes: 1

Denziloe
Denziloe

Reputation: 8162

Solution using pandas. I recommend using DataFrames in future for plotting tasks.

from matplotlib import pyplot as plt
import pandas as pd

C= [0.5, 4, 2, 1, 3, 8, 6, 10]
D= [20, 2, 2, 10, 0.3, 2.5, 0.8, 1]

xy = pd.DataFrame({'x': C, 'y': D})
xy.sort_values('x', inplace=True)

plt.plot(xy['x'], xy['y'])
plt.show()

enter image description here

Upvotes: 1

Related Questions