Skip to content

Getting Started

Import the matplotlib.pyplot module under the name plt (the tidy way)

import matplotlib.pyplot as plt

You'll also need to use this line to see plots in the notebook:
%matplotlib inline

That line is only for jupyter notebooks, if you are using another editor, you'll use: plt.show() at the end of all your plotting commands to have the figure pop up in another window.

Functional Method for Plotting

There are two ways to build plots in matplotlib: (i) functional method, (ii) object oriented method. First we'll look at the functional method.

import numpy as np
x = np.linspace(0,5,11)
y = x**2
plt.plot(x,y)

Graph Graph

We can now dress up our plot by adding labels.

plt.plot(x,y)
plt.xlabel('X label')
plt.ylabel('Y label')
plt.title('Title')

Graph Graph

Subplot

To plot multiple plots on the same canvas use the subplot method. This takes arguments: nrows, ncols, plot_number, where the plots are placed in a 2-D array on the screen.

plt.subplot(1,2,1)
plt.plot(x,y,'r')

plt.subplot(1,2,2)
plt.plot(y,x,'b')

Graph Graph

This is opposed to placing both plots on the same coordinate axes:

plt.plot(x,y,'r')
plt.plot(y,x,'b')

Graph Graph

Add Subplot