Thursday, January 26, 2017

Plotting in Python using Matplotlib

Matplotlib is a great plotting library when working in Python. Despite having used it several times, I usually end up searching online for a template to draw the first figure and associated customization details; especially if using it after a hiatus. So, in order to save time, I prepared a custom matplotlib boilerplate template (linked below) that contains my most frequently used functionality with parameters filled-in with typical default values.


There are two interfaces (APIs) to use matplotlib: a procedural (matlab-like) interface and an object oriented interface. An overview of matplotlib and its different interfaces can be found hereThe template provided below is of the latter type as it is more powerful and also happens to be my matplotlib interface of choice. At the end of the post is an example figure and the boilerplate code to draw it. As evident, this includes the code for the following: draw functions, scatterplot, heatmap, contours, quiverplot, labels, legends, adjusting axis ratio, set background color, updating a figure without blocking for input and writing to disk. Of course, this is still only a fraction of all the functionality provided by matplotlib! 

Lastly, if you are looking for more than just static images, a new generation of visualization tools is emerging that are based on matplotlib, and offer built-in support for advanced interactivity features such as: linking, brushing and highlighting, among others. Some examples of such tools are plotly, seaborn and mpld3.


Example figure generated by the following Matplotlib code.