Multiple Y-Axis Plotting With Matplotlib

PythonPythonBeginner
Practice Now

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

Introduction

In data visualization, it is often necessary to plot multiple variables with different units of measurement on the same graph. One common method to achieve this is by using multiple y-axes, where each y-axis corresponds to a different variable. In this lab, we will learn how to create a graph with multiple y-axes using 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 matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/AdvancedPlottingGroup(["`Advanced Plotting`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) 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`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") matplotlib/AdvancedPlottingGroup -.-> matplotlib/secondary_axis("`Secondary Axis`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") 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/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} matplotlib/figures_axes -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} matplotlib/line_plots -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} matplotlib/secondary_axis -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} matplotlib/legend_config -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/variables_data_types -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/lists -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/tuples -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/importing_modules -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/data_collections -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/numerical_computing -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/data_visualization -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} python/build_in_functions -.-> lab-48843{{"`Multiple Y-Axis Plotting With Matplotlib`"}} end

Import the necessary libraries

We start by importing the required libraries, Matplotlib and NumPy. Matplotlib is a data visualization library, and NumPy is a library for numerical computing in Python.

import matplotlib.pyplot as plt
import numpy as np

Create a figure and axes object

We create a figure and axes object, which represents a single plot in Matplotlib.

fig, ax = plt.subplots()

Add a twin y-axis

We add a twin y-axis to the plot using the twinx method. This will create a new y-axis on the right side of the plot.

twin1 = ax.twinx()

Set the position of the twin y-axis

We set the position of the twin y-axis using the set_position method. This will move the twin y-axis to the right of the original y-axis.

twin1.spines.right.set_position(("axes", 1.2))

Add data to the plot

We add data to the plot using the plot method. We add three lines to the plot, each with a different y-axis.

p1, = ax.plot([0, 1, 2], [0, 1, 2], "C0", label="Density")
p2, = twin1.plot([0, 1, 2], [0, 3, 2], "C1", label="Temperature")
p3, = twin2.plot([0, 1, 2], [50, 30, 15], "C2", label="Velocity")

Set the limits and labels for the axes

We set the limits and labels for each y-axis using the set method. We also set the color of the labels to match the color of the lines using the set_color method.

ax.set(xlim=(0, 2), ylim=(0, 2), xlabel="Distance", ylabel="Density")
twin1.set(ylim=(0, 4), ylabel="Temperature")
twin2.set(ylim=(1, 65), ylabel="Velocity")

ax.yaxis.label.set_color(p1.get_color())
twin1.yaxis.label.set_color(p2.get_color())
twin2.yaxis.label.set_color(p3.get_color())

Set the tick colors

We set the tick colors for each y-axis to match the color of the labels.

ax.tick_params(axis='y', colors=p1.get_color())
twin1.tick_params(axis='y', colors=p2.get_color())
twin2.tick_params(axis='y', colors=p3.get_color())

Add a legend to the plot

We add a legend to the plot using the legend method. We pass a list of line objects as the handles parameter.

ax.legend(handles=[p1, p2, p3])

Display the plot

We display the plot using the show method.

plt.show()

Summary

In this lab, we learned how to create a graph with multiple y-axes using Matplotlib. We created a figure and axes object, added a twin y-axis, set the position of the twin y-axis, added data to the plot, set the limits and labels for the axes, set the tick colors, added a legend to the plot, and displayed the plot. This technique can be useful when comparing variables with different units of measurement on the same graph.

Other Python Tutorials you may like