Matplotlib is as simple as this!

  • 0
Imagine data you have a comma separated file (CSV) called data.csv:

'position', 'value'
1.00000000,19.0612177051
6.21052632,100.657317014
11.42105263,111.081064358
16.63157895,232.929497684
21.84210526,224.490699818
27.05263158,279.538416476
32.26315789,377.203193621
37.47368421,443.521259213
42.68421053,444.889816318
47.89473684,527.26112329
53.10526316,569.99383123
58.31578947,635.948010167
63.52631579,667.667229067
68.73684211,734.623416964
73.94736842,754.704089053
79.15789474,834.453817955
84.36842105,828.770429695
89.57894737,884.032674467
94.78947368,925.518393595
100.0,978.592947013

And you want to plot the data and do a linear fitting (polynomial fit of degree one). Matplotlib does it like this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

# read CSV as a numpy array
data = mlab.csv2rec('data.csv')

# print CSV file headers
print data.dtype.names

# load collumns as vectors
data_x = data['position']
data_y = data['value']

# plot raw data
plt.plot(data_x,data_y,'o')

# fit data with a polynomial of degree 1: ax+b=0
a,b = np.polyfit(data_x, data_y, 1)
data_y_fitted = np.polyval([a, b], data_x)

#plot fitted data
plt.plot(data_x,data_y_fitted,'-')

plt.show()


Here the resulting Plot:


Let's make it prettier:


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

# read CSV as a numpy array
filePath = 'data.csv'
data = mlab.csv2rec(filePath)

# print CSV file headers
print data.dtype.names

# load collumns as vectors
data_x = data['position']
data_y = data['value']

# figure
fig = plt.figure('.: MatPlotLib Example :.')
fig.suptitle('Plot for file '+filePath, fontsize=12, fontweight='bold')

# Add my axis (I only have one, but I could have two, e.g., mirrored Y)
ax = fig.add_subplot(111)

# plot raw data
# I'm going to add some labels to add a legend after
ax.plot(data_x,data_y,'o', label='Raw data')
ax.set_xlabel(data.dtype.names[0])

# Now I want to have X axis with some Latex:
from matplotlib import rc
rc('text', usetex=True)
ax.set_ylabel(data.dtype.names[1]+' ($\\AA^{-1}$)')
rc('text', usetex=False)

# fit data with a polynomial of degree 1: ax+b=0
a,b = np.polyfit(data_x, data_y, 1)
data_y_fitted = np.polyval([a, b], data_x)

#plot fitted data
ax.plot(data_x,data_y_fitted,'-', label='Fitted data')

# Let's add the legend to the lower right corner
ax.legend(loc= 'lower right')

plt.show()

Et voilĂ  the result:


Simple isn't it?

No comments:

Post a Comment