Physics 251 - python tutorial

Eugeniy E. Mikhailov

Michael Kordosky

Plotting unsorted data

Often the data is taken in an arbitrary order. If you try to plot such data connected with lines, you would get a messy plot like shown below.

Plot of unsorted data

A better strategy is to presort the data. As shown in the script below.

import matplotlib.pyplot as plt
import numpy as np

x=np.array([0, 5, 2, 1, 6])
y=np.array([0, 25, 4, 1, 36])

# Often data is taken in arbitrary order, but it makes ugly plots
# since the points are plotted and joined in the order of appearance
plt.plot(x,y, 'o-')
plt.title('Unsorted data connected with lines')
plt.savefig('unsorted_plot.svg')

# A better way to have index which list data in a sorted way
ind=np.argsort(x)
# now we plot according to the sort order
plt.clf()
plt.plot(x[ind], y[ind], 'o-')
plt.title('Sorted data connected with lines')

plt.savefig('sorted_plot.svg')
Plot of sorted data