Plotting with matplotlib in Python

Effective plots are important to synthesize the information into relevant and persuasive information. The following tutorial details some of the common data plotting functions within Python.

Tutorial Source Code

import numpy as np
x = np.linspace(0,6,100)
y = np.sin(x)
z = np.cos(x)

import matplotlib.pyplot as plt
plt.plot(x,y,'r--',linewidth=3)
plt.plot(x,z,'k:',linewidth=2)
plt.legend(['y','z'])
plt.xlabel('x')
plt.ylabel('values')
plt.xlim([0, 3])
plt.ylim([-1.5, 1.5])
plt.savefig('myFigure.png')
plt.savefig('myFigure.eps')
plt.show()

If using the iPython notebook, exclude the command plt.show() and include %matplotlib inline before loading matplotlib.pyplot as shown below.

import numpy as np
x = np.linspace(0,6,100)
y = np.sin(x)
z = np.cos(x)

%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(x,y,'r--',linewidth=3)
plt.plot(x,z,'k:',linewidth=2)
plt.legend(['y','z'])
plt.xlabel('x')
plt.ylabel('values')
plt.xlim([0, 3])
plt.ylim([-1.5, 1.5])
plt.savefig('myFigure.png')
plt.savefig('myFigure.eps')