Plotting graphs with Matplotlib
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.
Matplotlib Gallery
The gallery is a collection of examples that demonstrate the range ofcapabilities of matplotlib. Source code is provided for each example and they should all work here.
It is worth using the gallery as a starting point for the plots you want to create. The interface to matplotlib objects is powerful but not designed for everyday use - to do slightly complicated things may require very complicated code. But lots can be done and here are some cool examples.