How can I make a figure with 2 charts, and both charts have dual Y axis in matplotlib?

Kamran Ahmed Khan
2 min readJan 26, 2023

Matplotlib

You can use the matplotlib.pyplot library to create a figure with two charts and dual Y axes. Here's an example of how you can do this:

import matplotlib.pyplot as plt

# Create figure and axes
fig, ax1 = plt.subplots()

# Create second Y axis
ax2 = ax1.twinx()

# Plot data on first Y axis
ax1.plot(data1, '-b', label='Data 1')

# Plot data on second Y axis
ax2.plot(data2, '-r', label='Data 2')

# Set labels and limits for first Y axis
ax1.set_ylabel('Data 1', color='b')
ax1.set_ylim(0, 10)

# Set labels and limits for second Y axis
ax2.set_ylabel('Data 2', color='r')
ax2.set_ylim(0, 100)

# Add legend
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')

# Show plot
plt.show()

In this example, we first create a figure object and axes object using plt.subplots(). Then we create a second Y axis object ax2 by calling the twinx() method on the first axis object ax1. This will create a new axis object that shares the same x-axis as the first axis but has its own y-axis.

Next, we plot the data on the two Y axis using the plot() method. We then set the labels and limits for each axis using the set_ylabel() and set_ylim() methods.

Finally, we add a legend to the plot using the legend() method. We can specify the location of the legend using the loc parameter. plt.show() is used to display the figure.

This should produce a figure with two charts, each with its own Y axis, and a common X axis.

You can also make use of make_axes_locatable function to create twin x-axis and twin y-axis for your plots.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Kamran Ahmed Khan
Kamran Ahmed Khan

Written by Kamran Ahmed Khan

Software Engineer, Tech enthusiast and Devops Engineer

No responses yet

Write a response