Subplots Spacings and Margins

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to adjust the spacing of margins and subplots using pyplot.subplots_adjust in Python Matplotlib. This can be useful to improve the layout and aesthetics of our plots.

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

First, we need to import the required libraries. For this tutorial, we will be using matplotlib.pyplot and numpy. Run the following code to import these libraries:

import matplotlib.pyplot as plt
import numpy as np

Create Plots

Next, let's create two plots using imshow and random arrays generated by numpy.random. We will also add a color bar to the plots. Run the following code:

## Fixing random state for reproducibility
np.random.seed(19680801)

plt.subplot(211)
plt.imshow(np.random.random((100, 100)))
plt.subplot(212)
plt.imshow(np.random.random((100, 100)))

cax = plt.axes([0.85, 0.1, 0.075, 0.8])
plt.colorbar(cax=cax)

plt.show()

Adjust Subplot Spacings and Margins

Now, let's adjust the subplot spacings and margins using pyplot.subplots_adjust. We can specify the values for the bottom, right, top, and left margins as fractions of the figure width and height. Run the following code:

plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

Adjust Colorbar Position

We can also adjust the position of the color bar using plt.axes. This function takes a list of [left, bottom, width, height] values as arguments to specify the position and size of the axes. Run the following code:

cax = plt.axes([0.85, 0.1, 0.075, 0.8])
plt.colorbar(cax=cax)

Display the Plot

Finally, let's display the plot using plt.show(). Run the following code:

plt.show()

Summary

In this lab, we learned how to adjust the spacing of margins and subplots using pyplot.subplots_adjust in Python Matplotlib. We also learned how to adjust the position of the color bar using plt.axes. These techniques can be useful to improve the layout and aesthetics of our plots.

Other Python Tutorials you may like