The world’s leading publication for data science, AI, and ML professionals.

Simplifying subplots creation in Matplotlib

Infusing Mosaic Magic into Your Plots

Photo by charlesdeluvio on Unsplash
Photo by charlesdeluvio on Unsplash

Recently, I was working on a project that required creating subplots using the Matplotlib library in Python. If you’ve ever used the Matplotlib library, there’s a high chance you’ve also utilized its subplot functionality. Subplots are an effective tool for generating multiple plots simultaneously, which can be advantageous when comparing results or when multiple plots share identical axes. However, at times the subplot syntax in Matplotlib can be anything but straightforward for many of us, myself included. Achieving the desired layout for the subplots can seem like a game of trial and error, shifting the focus from our actual project.

Hiding in plain sight, really !!

Hiding in plain sight | Image by Pixabay
Hiding in plain sight | Image by Pixabay

I am aware that the patchwork library in R is adept at handling the creation of subplots. However, I was surprised to discover that Matplotlib had this functionality all along, serving as a potent reminder to read the documentation thoroughly. Intrigued, I decided to delve deeper to broaden my understanding of this feature and relay my experiences and insights to others via a blog post.


Subplots in Matplotlib

Matplotlib, a widely-used plotting library, provides two approaches for creating subplots: Figure.subplots() and Figure.subplot_mosaic(). While both these methods serve the same purpose, using the latter method has some inherent advantages. Let’s explore their differences, highlighting the simplicity and flexibility offered by Figure.subplot_mosaic() over Figure.subplots().

Understanding the Figure.subplots method

The subplots method in Matplotlib allows us to create subplots in a grid-like structure. It takes parameters specifying the number of rows and columns in the subplot grid and returns a Figure object and an array of Axes objects representing the individual subplots.

Let’s consider a toy example where we want to create a figure with four subplots in a 2X2 manner. Let’s use the [Figure.subplots()](http://Figure.subplots) method to achieve this task.

Figure (1): Creating subplots in Matplotlib using the [Figure.subplots](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.subplots) method | Image by the Author
Figure (1): Creating subplots in Matplotlib using the [Figure.subplots](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.subplots) method | Image by the Author

As seen in Figure (1), although the Figure.subplots method provides a straightforward way to create subplots by specifying the number of rows and columns; it falls short under the following scenarios:

  • Manual Indexing Errors

The user must manually specify the indexing for each subplot. This process can be error-prone, especially when dealing with complex subplot arrangements or when an indexing mistake leads to misplaced or omitted subplots.

  • Limited Layout Flexibility

The method relies on a fixed grid structure, making creating irregular or custom layouts challenging. If the desired arrangement does not fit the specified grid, it can result in visual inconsistencies or distorted plots.

  • Adjustment Challenges

Making changes to the subplot arrangement or adding/removing subplots can be cumbersome. Adjusting the indexing or resizing the grid requires careful manual adjustments, increasing the risk of introducing errors.


A better alternative – Figure.subplot_mosaic method

The [Figure.subplot_mosaic](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.subplot_mosaic) method is a powerful alternative introduced in Matplotlib version 3.4.0, designed to simplify the creation and arrangement of subplots. It provides a more intuitive approach, defining subplots using a dictionary-like structure, where keys represent subplot labels and values define their positions within a grid. With this method, you can easily create complex subplot layouts by specifying the relative position of each subplot.

Let’s compare the previous approach to the Figure.subplot_mosaic() approach below.

Figure (2): Creating subplots in Matplotlib using the [Figure.subplot_mosaic](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.subplot_mosaic) method | Image by the Author
Figure (2): Creating subplots in Matplotlib using the [Figure.subplot_mosaic](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.subplot_mosaic) method | Image by the Author

As is evident from Figure(2), while we obtain the same results, the process is a lot more simple and intuitive. Additionally, we also have the following advantages:

  1. Intuitive syntax

The dictionary-like structure used by Figure.subplot_mosaic() provides a clear and concise way to specify the arrangement of subplots. This approach eliminates the need for manual calculation and indexing required in fig.subplots(). We have already seen in the code above how to specify the order of the subplots. However, we can further simplify the process by limiting the axes labels to individual characters as follows:

ax_dict

--------------------------------

{'a': <AxesSubplot: label='a'>,
 'b': <AxesSubplot: label='b'>,
 'd': <AxesSubplot: label='d'>,
 'c': <AxesSubplot: label='c'>}

2. Flexibility in arranging subplots:

Figure.subplot_mosaic() enables us to easily define complex subplot layouts, including irregular grids that span multiple rows or columns. This flexibility is particularly useful when dealing with datasets that require different visualizations side by side. Let’s consider two examples that showcase the desired arrangements for our subplots:

  • Firstly, we desire an axes that spans across multiple rows or columns. To be more precise, we are seeking something similar to the following example:
Image by Author
Image by Author

While arranging subplots using the [Figure.subplots](https://Matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.subplots) methods can be daunting, the Figure.subplot_mosaic() method simplifies the process to just re-arranging the axes labels.

Using Figure.subplot_mosaic() for Axes spanning multiple rows/columns | Image by Author
Using Figure.subplot_mosaic() for Axes spanning multiple rows/columns | Image by Author
  • Another scenario to consider is not populating all sections of the figure with axes but rather leaving certain grid spaces empty, as shown below:
Image by Author
Image by Author
Using Figure.subplot_mosaic() specifying some spaces in the grid to be blank

Using Figure.subplot_mosaic() specifying some spaces in the grid to be blank

In addition to the aforementioned benefits, we have the ability to control mosaic creation, manage subplot creation, and individually adjust parameters for each subplot, among other features. The documentation provides detailed examples that serve as an excellent resource for experimentation and exploration of this functionality.

Complex and semantic figure composition (subplot_mosaic) – Matplotlib 3.7.1 documentation


Conclusion

In this blog post, we explored the advantages of using Figure.subplot_mosaic() over fig.subplots() in Matplotlib. The former offers superior flexibility when it comes to organizing subplots, and its syntax for positioning them is notably intuitive, thereby empowering data scientists and visualization enthusiasts to create sophisticated and customized layouts effortlessly. This functionality reminds me of my initial exposure to Python’s f-strings. Before the introduction of f-strings, my go-to method for string formatting was predominantly the %-formatting and the str.format methods. Although these methods were functional, they weren’t exceptionally intuitive. However, since the introduction of f-strings, my coding experience has significantly improved – much like my experience with Figure.subplot_mosaic()👩 ‍💻😃



Related Articles