Plotting in notebooks

There are lots of different backends for plotting matplotlib figures in notebooks:

In [1]:
%matplotlib --list
Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'wx', 'qt4', 'qt5', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']

We use notebook for interactive notebooks, but inline is better suited for static output.

In [2]:
%matplotlib notebook
#%matplotlib inline

After choosing a backend there are a range of different choices for image format if you use inline:

In [3]:
# The InlineBackend only appears *after* matplotlib magic
%config InlineBackend
InlineBackend options
-------------------
InlineBackend.close_figures=<Bool>
    Current: True
    Close all figures at the end of each cell.
    When True, ensures that each cell starts with no active figures, but it also
    means that one must keep track of references in order to edit or redraw
    figures in subsequent cells. This mode is ideal for the notebook, where
    residual plots from other cells might be surprising.
    When False, one must call figure() to create new figures. This means that
    gcf() and getfigs() can reference figures created in other cells, and the
    active figure can continue to be edited with pylab/pyplot methods that
    reference the current active figure. This mode facilitates iterative editing
    of figures, and behaves most consistently with other matplotlib backends,
    but figure barriers between cells must be explicit.
InlineBackend.figure_format=<Unicode>
    Current: ''
    The figure format to enable (deprecated use `figure_formats` instead)
InlineBackend.figure_formats=<Set>
    Current: {'png'}
    A set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
InlineBackend.print_figure_kwargs=<Dict>
    Current: {'bbox_inches': 'tight'}
    Extra kwargs to be passed to fig.canvas.print_figure.
    Logical examples include: bbox_inches, quality (for jpeg figures), etc.
InlineBackend.rc=<Dict>
    Current: {'figure.figsize': (6.0, 4.0), 'figure.facecolor': (1, 1, 1, 0), 'figure.edgecolor': (1, 1, 1, 0), 'font.size': 10, 'figure.dpi': 72, 'figure.subplot.bottom': 0.125}
    Subset of matplotlib rcParams that should be different for the inline
    backend.

Normally a vector format like svg or pdf is preferred over a raster format. Otherwise lossless compression using png is preferred over the lossy jpeg format.

In [4]:
%config InlineBackend.figure_format = 'svg'

We import numpy and matplotlib to plot a simple figure:

In [5]:
import numpy as np
import matplotlib.pyplot as plt

After doing so we can change the canvas size, which inconveniently is only expressible in absolute units (inches!?). Ideally we would set this to be the width of the text, for this notebook we guessed.

If a raster format was chosen, the dpi (dots/pixels per inch, yes still inches...) parameter can be changed to producing higher resolution figures. This also has the effect inside a notbook of increasing the figure size too.

In [6]:
plt.rcParams['figure.figsize'] = (8,6)
plt.rcParams['figure.dpi'] = 120

We can now produce a plot in our notebook. Notice that we are using matplotlib's "object oriented" interface as opposed to the "state machine" interface. This is very powerful and well worth learning how to use, if you are not already familiar.

In [7]:
# Do a "Regular" plot
fig, ax = plt.subplots(1, 1)

α = 0
ω = 1
t = np.linspace(0, 2*np.pi, 200)
ax.plot(t, (t**α)*np.sin(ω*t))

ax.set_xlabel('$t$')
ax.set_ylabel('$f$')
ax.set_title(r"$\alpha$ = {}, $\omega$ = {}".format(α, ω))

plt.show()