ADS-DV

Plotting basic parts of a chart

Summary

This assignment first shows you how to produce a simple plot using the Matplolib API and then asks you to recreate that plot using the alternative API, that you will often use later when you have multiple plots per graph (subplots).

Matplotlib

First, we import the required libraries, using standard conventions. We first import numpy for all our mathematical needs, then the Matplotlib as plotting library and pyplot which gives an ease API to create plots with matplotlib.


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:

Assignment

Recreate the above plot starting with the following lines. You will need to use this form a lot when you have plots that contains multiple subplots. Hint: you now need to change properties of the 'ax' object. Look on the internet for documentation.


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');


<matplotlib.figure.Figure at 0x2200089a518>

In [ ]:


In [ ]:


In [ ]: