Align Y-Labels in Matplotlib Plots

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, you will learn how to align y-labels in Matplotlib plots. The alignment of y-labels is important for improving the readability of plots, especially when there are multiple subplots.

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`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) 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/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") 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/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} matplotlib/importing_matplotlib -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} matplotlib/figures_axes -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} matplotlib/line_plots -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/variables_data_types -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/for_loops -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/lists -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/tuples -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/function_definition -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/importing_modules -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/standard_libraries -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/math_random -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/data_collections -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/numerical_computing -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/data_visualization -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} python/build_in_functions -.-> lab-48534{{"`Align Y-Labels in Matplotlib Plots`"}} end

Import Required Libraries

The first step is to import the required libraries. In this lab, we will be using Matplotlib and NumPy.

import matplotlib.pyplot as plt
import numpy as np

Create the Plot

The next step is to create the plot. We will create a plot with two subplots, where the y-labels are not aligned.

def make_plot(axs):
    box = dict(facecolor='yellow', pad=5, alpha=0.2)

    ## Fixing random state for reproducibility
    np.random.seed(19680801)
    ax1 = axs[0, 0]
    ax1.plot(2000*np.random.rand(10))
    ax1.set_title('ylabels not aligned')
    ax1.set_ylabel('misaligned 1', bbox=box)
    ax1.set_ylim(0, 2000)

    ax3 = axs[1, 0]
    ax3.set_ylabel('misaligned 2', bbox=box)
    ax3.plot(np.random.rand(10))

    ax2 = axs[0, 1]
    ax2.set_title('ylabels aligned')
    ax2.plot(2000*np.random.rand(10))
    ax2.set_ylabel('aligned 1', bbox=box)
    ax2.set_ylim(0, 2000)

    ax4 = axs[1, 1]
    ax4.plot(np.random.rand(10))
    ax4.set_ylabel('aligned 2', bbox=box)

fig, axs = plt.subplots(2, 2)
fig.subplots_adjust(left=0.2, wspace=0.6)
make_plot(axs)
plt.show()

Align Y-Labels Automatically

The third step is to align the y-labels automatically using the .Figure.align_ylabels method.

fig, axs = plt.subplots(2, 2)
fig.subplots_adjust(left=0.2, wspace=0.6)
make_plot(axs)
fig.align_ylabels(axs[:, 1])
plt.show()

Align Y-Labels Manually

The fourth step is to align the y-labels manually using the ~.Axis.set_label_coords method of the y-axis object.

fig, axs = plt.subplots(2, 2)
fig.subplots_adjust(left=0.2, wspace=0.6)
make_plot(axs)

labelx = -0.3  ## axes coords

for j in range(2):
    axs[j, 1].yaxis.set_label_coords(labelx, 0.5)

plt.show()

Summary

In this lab, you learned how to align y-labels in Matplotlib plots. The alignment of y-labels is important for improving the readability of plots, especially when there are multiple subplots. We covered two methods for aligning y-labels, one using a short call to .Figure.align_ylabels and the second a manual way to align the labels.

Conclusion

Congratulations! You have learned how to align y-labels in Matplotlib plots. Keep practicing and exploring the Matplotlib library to improve your visualization skills.

Summary

Congratulations! You have completed the Align Y-Labels lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like