Create Dual-Axis Matplotlib Plot

PythonPythonBeginner
Practice Now

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

Introduction

This tutorial will guide you through the steps of creating a simple plot using Matplotlib, a Python library used for data visualization. We will be using the host_subplot module to create a plot with two y-axes.

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`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) 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`") matplotlib/PlottingDataGroup -.-> matplotlib/line_plots("`Line Plots`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} matplotlib/figures_axes -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} matplotlib/line_plots -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/booleans -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/lists -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/tuples -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/sets -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/importing_modules -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/using_packages -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/numerical_computing -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} python/data_visualization -.-> lab-48939{{"`Create Dual-Axis Matplotlib Plot`"}} end

Import necessary modules

The first step is to import the necessary modules for our plot. We will be using numpy to generate our x and y data, matplotlib.pyplot to create the plot, and mpl_toolkits.axes_grid1 to create the second y-axis.

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import host_subplot

Generate data

Next, we need to generate our x and y data. We will be generating a sine wave for this example.

xx = np.arange(0, 2*np.pi, 0.01)
yy = np.sin(xx)

Create the plot

Now we can create our plot using the host_subplot function. This function creates a subplot with two y-axes.

ax = host_subplot(111)
ax.plot(xx, yy)

Create the second y-axis

To create the second y-axis, we need to create a new axis object using the twin function.

ax2 = ax.twin()

Set tick labels for the second y-axis

We can set the tick labels for the second y-axis using the set_xticks function and passing in the tick locations and labels as arguments.

ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi],
               labels=["$0$", r"$\frac{1}{2}\pi$",
                       r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])

Hide tick labels for the right y-axis

We can hide the tick labels for the right y-axis using the major_ticklabels.set_visible function.

ax2.axis["right"].major_ticklabels.set_visible(False)

Show tick labels for the top y-axis

We can show the tick labels for the top y-axis using the same major_ticklabels.set_visible function.

ax2.axis["top"].major_ticklabels.set_visible(True)

Display the plot

Finally, we can display our plot using the show function.

plt.show()

Summary

In this tutorial, we learned how to create a simple plot with two y-axes using Matplotlib. We used the host_subplot module to create the plot and the mpl_toolkits.axes_grid1 module to create the second y-axis. We generated our data using numpy and displayed the plot using matplotlib.pyplot.

Other Python Tutorials you may like