How to make two plots on the same axis with different left and right scales with Matplotlib using Python

1 min readMatplotlibPlotData Visualization
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Plotting two variables on the same chart can be very useful to compare them against another variable.

Here is how to achieve this using Matplotlib.

# We import our libraries
import matplotlib.pyplot as plt
import numpy as np

# Generate our sample dataset
x = np.linspace(1,100)
y = np.sin(2 * np.pi * x)

# We create a canvas with one ax
fig, ax1 = plt.subplots(1, 1, figsize=(8,4))

# We plot on our first axis
ax1.plot(x, x, ls='--', alpha=0.6, c='tab:blue')

# We change the labels color of our first axis
ax1.tick_params('y', colors='tab:blue')

# We create our second ax based on our first ax
ax2 = ax1.twinx()
ax2.plot(x, y, ls='--', alpha=0.6, c='tab:red')

# We change the labels color of our second axis
ax2.tick_params('y', colors='tab:red')

# We tight the layout
fig.tight_layout()

# We plot
plt.show()

The result

Here is how to plot two variables on different y-axis

Here you are! You now know how to plot two variables on the same plot with different y-axis scales.

More on Matplotlib

If you like what you've just read and want to know more about the Matplotlib library (e.g. how to add labels, plot different types of plots, etc...) check out the other articles I wrote on the topic, just here :

Matplotlib - The Python You Need
We gathered the only Python essentials that you will probably ever need.
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.