Plotting graphs with Matplotlib

Summary

Matplotlib is a plotting library for Python and the numerical mathematics extension NumPy. It is handy, ubiquitous, and simple to use for basic tasks. On the other hand, it can be quite difficult to use for consistently producing publication quality figures, and the interface lacks consistency.

Introduction to matplotlib

Matplotlib will help you to plot graphs from your data, and is a great starting point when you need to see if something is working or not. It can be used for complicated plots and figures for publication of your results. The default interface makes simple tasks trivial but is hard to extend when you need a more refined graph.

Matplotlib fully embraces the python object-oriented model, but for some tasks the design of the object hierarchy is a little bit counter-intuitive. It’s best to find a common pattern for building plots and stick to it.

In matplotlib, the figure is the top-level container for all the plot elements but it does little more than hold onto sets of axes which are the primary objects you will interact with.

To look at the rendered image we can either browse with the jupyterlab file browser or, if we are running in the browser, we can use the display function from the IPython.display module to display the image.

Examples

The figure is just used once in a typical, simple plotting routine. The axis / axes are used as a container for all of an individual graph’s information. The subplot arguments are rather typical of matplotlib - a 1960s, fortran-like parsing of a three digit integer (above) or three separate arguments that imply the same thing (below). Which of these is the better choice to use, and why ?

It’s not just plot that can add data to an axis, the style of the plot is largely controlled by the routine that add the data to a given axis. You can add multiple data to an axis and you can do this in multiple formats.

Here are some more examples that you can explore.