Introduction
Matplotlib is a popular Python library used for data visualization. In this lab, we will learn how to combine two subplots using subplots and GridSpec in 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.
Import Required Libraries
We start by importing the necessary libraries for this lab. We will be using Matplotlib for data visualization.
import matplotlib.pyplot as plt
Create a Figure with Subplots
We create a figure with three columns and three rows of subplots.
fig, axs = plt.subplots(ncols=3, nrows=3)
Get the GridSpec from the Axes
We get the GridSpec from the second row and third column of the subplots.
gs = axs[1, 2].get_gridspec()
Remove the Underlying Axes
We remove the underlying axes that are covered by the bigger axes that we will create in the next step.
for ax in axs[1:, -1]:
ax.remove()
Add a Bigger Axes
We add a bigger axes that covers the second and third rows of the last column.
axbig = fig.add_subplot(gs[1:, -1])
Annotate the Bigger Axes
We annotate the bigger axes with some text.
axbig.annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5),
xycoords='axes fraction', va='center')
Adjust the Layout
We adjust the layout of the subplots to ensure they fit in the figure.
fig.tight_layout()
Display the Plot
We display the plot using Matplotlib.
plt.show()
Summary
In this lab, we learned how to combine two subplots using subplots and GridSpec in Matplotlib. We created a figure with subplots, got the GridSpec from the axes, removed the underlying axes, added a bigger axes, annotated the bigger axes, and adjusted the layout of the subplots. Finally, we displayed the plot using Matplotlib.