Labelling Subplots With Matplotlib

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Matplotlib is a widely used data visualization library in Python. It provides a variety of tools to create different types of plots, including subplots. When creating subplots, it is often helpful to label each plot to make it easier for the reader to understand the information being presented. In this lab, we will learn how to label subplots using different methods provided by Matplotlib.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} matplotlib/importing_matplotlib -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} matplotlib/figures_axes -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/variables_data_types -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/for_loops -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/lists -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/tuples -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/importing_modules -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/data_collections -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/data_visualization -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} python/build_in_functions -.-> lab-48796{{"`Labelling Subplots With Matplotlib`"}} end

Import Libraries

The first step is to import the required libraries. We will be using matplotlib.pyplot and matplotlib.transforms to create and transform the subplots.

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms

Create Subplots

Next, we create the subplots using plt.subplot_mosaic. We will create a 3x2 grid of subplots and label them as follows:

  • The top-left plot will be labeled as "a)"
  • The bottom-left plot will be labeled as "b)"
  • The top-right and bottom-right plots will be labeled as "c)" and "d)" respectively.
fig, axs = plt.subplot_mosaic([['a)', 'c)'], ['b)', 'c)'], ['d)', 'd)']], layout='constrained')

Label Inside the Axes

The simplest method to label subplots is to put the label inside the axes. We can achieve this by using the ax.text method. We will loop through each subplot and add the label inside the axes using ax.transAxes.

for label, ax in axs.items():
    ## label physical distance in and down:
    trans = mtransforms.ScaledTranslation(10/72, -5/72, fig.dpi_scale_trans)
    ax.text(0.0, 1.0, label, transform=ax.transAxes + trans,
            fontsize='medium', verticalalignment='top', fontfamily='serif',
            bbox=dict(facecolor='0.7', edgecolor='none', pad=3.0))

Label Outside the Axes

We may prefer the labels outside the axes but still aligned with each other. In this case, we use a slightly different transform.

for label, ax in axs.items():
    ## label physical distance to the left and up:
    trans = mtransforms.ScaledTranslation(-20/72, 7/72, fig.dpi_scale_trans)
    ax.text(0.0, 1.0, label, transform=ax.transAxes + trans,
            fontsize='medium', va='bottom', fontfamily='serif')

Label with Title

If we want the label to be aligned with the title, we can incorporate it into the title or use the loc keyword argument.

for label, ax in axs.items():
    ax.set_title('Normal Title', fontstyle='italic')
    ax.set_title(label, fontfamily='serif', loc='left', fontsize='medium')

Display the Subplots

Finally, we display the subplots using plt.show().

plt.show()

Summary

In this lab, we learned how to label subplots in Matplotlib using different methods. We used ax.text to label inside the axes, ax.set_title to label with the title, and plt.subplot_mosaic to create the subplots. We also used matplotlib.transforms to transform the axes to align the labels. By labeling the subplots, we can make our plots more informative and easier to understand.

Other Python Tutorials you may like