In [3]:
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
# we need the following line to indicate that the plots should be shown inline with the iPython notebook.
%matplotlib inline
We will first create a simple plot of a mathematical function. We first create a numpy array of x-values. Then for each x-value we create the y-value, i.e. the function value. Plotting this function is as easy as giving it the x and y values.
In [4]:
X = np.linspace(-np.pi, np.pi, 100) # define a NumPy array with 100 points in the range -Pi to Pi
Y = np.sin(X) # define the curve Y by the sine of X
plt.plot(X,Y); # use matplotlib to plot the function
While creating such plots is perfectly fine when you are exploring data, in your final notebook the plot is hard to understand for the reader. With matplotlib it is very easy to add labels, a title and a legend. You can also change the limits of the plot, the style of the lines and much more.
The following could be seen as the bare minimum for a plot to be understood as part of reproducible research.
In [5]:
plt.figure()
plt.plot(X, Y, 'r--', linewidth=2)
plt.plot(X, Y/2, 'b-', linewidth=2)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Plot Title')
plt.xlim(-4, 4)
plt.ylim(-1.2, 1.2)
plt.legend(['red curve', 'blue curve'], loc='best');
Go to the documentation pages of matplotlib [http://matplotlib.org/contents.html] to find all the possible options for a plot and also to see more tutorials, videos and book chapters to help you along the way.
A few other nice tutorials:
In [11]:
plt.figure()
fig, ax = plt.subplots()
ax.plot(X, Y, 'r--', linewidth=2);
ax.plot(X, Y/2, 'b-', linewidth=2);
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_title('Plot Title')
ax.set_xlim(-4, 4)
ax.set_ylim(-1.2, 1.2)
ax.legend(['red curve', 'blue curve'], loc='best');
In [ ]:
In [ ]:
In [ ]: