Mastering Subplot Customization with GridSpec

PythonPythonBeginner
Practice Now

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

Introduction

In this tutorial, we will learn how to use GridSpec to generate subplots, control the relative sizes of subplots with width_ratios and height_ratios, and the spacing around and between subplots using subplot params (left, right, bottom, top, wspace, and hspace).

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 matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} matplotlib/figures_axes -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/booleans -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/for_loops -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/lists -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/tuples -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/function_definition -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/importing_modules -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/using_packages -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/data_visualization -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} python/build_in_functions -.-> lab-48679{{"`Mastering Subplot Customization with GridSpec`"}} end

Import Libraries

We start by importing the necessary libraries, which are matplotlib.pyplot and GridSpec.

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

Generate Subplots with GridSpec

In this step, we will use GridSpec to generate subplots. We will create a figure with 2 rows and 2 columns. We will also specify the width_ratios and height_ratios to control the relative sizes of the subplots.

fig = plt.figure()
gs = GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[4, 1])
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])
ax3 = fig.add_subplot(gs[2])
ax4 = fig.add_subplot(gs[3])

Control Spacing Around and Between Subplots

In this step, we will use GridSpec to control the spacing around and between subplots. We will create a figure with 2 gridspecs, each with 3 rows and 3 columns. We will specify the left, right, bottom, top, wspace, and hspace parameters to control the spacing.

fig = plt.figure()
gs1 = GridSpec(3, 3, left=0.05, right=0.48, wspace=0.05)
ax1 = fig.add_subplot(gs1[:-1, :])
ax2 = fig.add_subplot(gs1[-1, :-1])
ax3 = fig.add_subplot(gs1[-1, -1])

gs2 = GridSpec(3, 3, left=0.55, right=0.98, hspace=0.05)
ax4 = fig.add_subplot(gs2[:, :-1])
ax5 = fig.add_subplot(gs2[:-1, -1])
ax6 = fig.add_subplot(gs2[-1, -1])

Annotate Axes

In this step, we will annotate the axes with their corresponding subplot numbers.

def annotate_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

annotate_axes(fig)

Display the Plots

In this step, we will display the plots.

plt.show()

Summary

In this tutorial, we learned how to use GridSpec to generate subplots and control the spacing around and between subplots. We also learned how to annotate the axes with their corresponding subplot numbers. These skills will be useful in creating complex plots and visualizations.

Other Python Tutorials you may like