Organise scripts and figures easily with Jupyter Notebooks

Keeping track of scripts used to generate figures is difficult. Before realising that Jupyter Notebooks could solve most of my problems, I would have directories with dozens of scripts with filenames of varying levels of ambiguity. Names that probably meant something to me at the time, but are hardly descriptive months or years later. Names like  ISW_plume_plots.m, new_ISW_model_plots.m, and plot_model_behaviour.m. A certain PhD comic springs to mind.

Regardless of whether its Python, R, Julia, Matlab, or pretty much any other type of code, Jupyter Notebooks solve the problem. For example, I use a single notebook to archive the code for all figures in a paper and, more importantly, I can associate each set of code with the figure it generates. Rather than trying to remember what file I want, I need only remember which figure I want. (I say archive because I much prefer to do the bulk of my exploratory analysis in an editor. Alternatively, JupyterLab may work better for you.)

By default, Jupyter Notebooks come with the ability to unite figures and code. This post demonstrates a few tweaks to make things even better.

Let me use my latest paper in preparation as an example. As the gif below shows, each figure has a descriptive header, the figure itself, and the code that generates the figure.


To avoid having to scroll through hundreds of lines of code to get to a figure, the code itself is folded away until I need it. To enable this requires the Collapsible Headings extension. I recommend installing it via the Jupyter Nbextensions Configurator. (The Configurator provides countless other gems that you never knew you wanted.)

Although it’s possible to keep a static plot below the code, a preferable alternative is to place the figure right beneath the heading with a link. Indeed, this is necessary if using Collapsible Headings. I export figures to the svg format, but png or jpg files also work. Unfortunately, PDF files are not accepted.

A header and figure link in a Markdown cell will look something like

# Figure description

Relative paths are necessary, so I recommend keeping the notebook in the same directory as the figures.

Finally, you’ll notice that the Notebook’s appearance is far from the default. The easiest method I’ve come across to change the look is to use jupyterthemes. I use the Grade3 theme.

Author: Ken Hughes

Post-doctoral research scientist in physical oceanography

One thought on “Organise scripts and figures easily with Jupyter Notebooks”

Comments are closed.

%d bloggers like this: