The first thing you need to do is tell the kernel that you would like to use matplotlib to make plots.
You do this using the magic invocation:
%matplotlib inline
The inline
option means that plots will appear directly in the output cell
of the notebook. Later in this notebook we'll try other options.
In [1]:
%matplotlib inline
Next we'll draw a plot using the standard matplotlib commands. We'll
use the pyplot
module which has a similar interface to MATLAB and Octave
for plotting.
See the official matplotlib page for documentation on matplotlib and examples.
In [2]:
from matplotlib import pyplot as plt
x = [1, 2, 3]
y = [2, 4, 3]
plt.plot(x, y);
Matplotlib has many options for making pretty plots. Here is an example
of a simulated damped oscillator. In this example we're using numpy
to generate and keep track of the numerical data.
Demo source: http://matplotlib.org/users/screenshots.html
In [3]:
"""
Simple demo with multiple subplots.
"""
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'yo-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)
plt.plot(x2, y2, 'r.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
In [4]:
"""
Tiny cosine plot.
"""
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0, 10)
y = np.cos(x)
plt.figure(figsize=(2, 2))
plt.plot(x, y);
In [5]:
"""
Large cosine plot.
"""
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0, 10)
y = np.cos(x)
plt.figure(figsize=(10, 10))
plt.plot(x, y);
Large inline plots are scaled down to fit the notebook width. Plots smaller than the width are not resized.
In [1]:
"""
Windowed cosine plot.
"""
%matplotlib osx
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0, 10)
y = np.cos(x)
#plt.figure(figsize=(10, 10))
plt.plot(x, y);
Note that plot windows are not saved as part of the notebook like inline plots are. You will have to execute your code again to regenerate the plot when loading the notebook.