As shown in Getting Started With matplotlib
, there are two "magic" commands to prepare a Jupyter/IPython notebook for plotting.
The first one is:
%matplotlib
This enables interactive plotting mode and ensures smooth handling of the plotting window. Whenever you run a plotting command, the plotting window is opened (or updated). The plotting window allows interactive zooming.
The other command is:
%matplotlib inline
This doesn't open a plotting window, but instead shows the plot directly within the notebook.
This has the advantage that the plot is saved together with the notebook file and therefore is visible even if the IPython kernel is not running.
This is especially useful for showing plots on nbviewer.
This is actually the default behavior of Jupyter notebooks,
so you don't even have to explicitly write %matplotlib inline
.
However, it has the disadvantage that the plot is not interactive, i.e. zooming is not possible.
But there is a third "magic" command, which tries to get the best of both worlds:
%matplotlib notebook
This shows the plot within the notebook, but as long as the IPython kernel is running, zooming is still possible. Whenever you interact with the plot, the notebook forwards the interaction to the IPython kernel, which sends updated plotting information back to the notebook.
Let's try it:
import matplotlib.pyplot as plt
data = 4, 8, 15, 16, 23, 42
plt.plot(data);
When you look at this in an interactive IPython session, you'll see some buttons on the bottom of the plot, which allow you to zoom and pan the plot.
However, if you look at this as a static HTML page, e.g. on nbviewer, you will just see a static image.
This is a really nice feature, but since during interactions a lot of data has to be sent back and forth between notebook and IPython kernel, the interaction experience might be a bit choppy, especially if large amounts of data are plotted.
I still prefer the separate plotting window for interactive exploration and switching to "inline" mode for publishing plots together with their notebooks. In some cases, a separate plotting window is not possible, e.g. when using binder. In this case, the "notebook" backend is probably the only way to get interactive zooming.