How to Create a Secondary Y-Axis in Matplotlib

I’ve worked extensively with data visualization tools, and Matplotlib has always been my go-to library for creating insightful charts. One feature I often use, especially when dealing with datasets that have different units or scales, is the secondary y-axis.

If you’ve ever wanted to plot two different variables on the same graph but struggled because they have vastly different ranges, then you’ll appreciate the secondary y-axis feature in Matplotlib. It allows you to overlay a second y-axis on the right side of your plot, making it easier to compare two related datasets without confusing your audience.

In this article, I’ll walk you through how to create a secondary y-axis in Matplotlib with simple, real-world examples relevant to US-based data visualization needs.

Why Use a Secondary Y-Axis?

Imagine you are analyzing quarterly sales data for two different metrics: total revenue (in millions of dollars) and customer satisfaction scores (on a scale of 1 to 10). The scales are completely different, and plotting them on the same y-axis would make one set of data almost invisible.

Using a secondary y-axis solves this problem by giving each dataset its scale, improving readability and insights.

Check out Draw a Vertical Line Matplotlib

Method 1: Use twinx() to Add a Secondary Y-Axis

The easiest way to add a secondary y-axis in Matplotlib is by using the twinx() method in Python. This method creates a new y-axis on the right side of the plot that shares the same x-axis.

Here’s how I typically use it:

import matplotlib.pyplot as plt

# Sample data: Quarterly revenue (in millions) and customer satisfaction scores
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
revenue = [50, 60, 55, 70]  # in millions of dollars
customer_satisfaction = [7.8, 8.0, 7.5, 8.3]  # score out of 10

fig, ax1 = plt.subplots()

# Plot revenue on primary y-axis
ax1.bar(quarters, revenue, color='skyblue', label='Revenue (in millions)')
ax1.set_ylabel('Revenue (Millions $)', color='skyblue')
ax1.tick_params(axis='y', labelcolor='skyblue')

# Create secondary y-axis
ax2 = ax1.twinx()
ax2.plot(quarters, customer_satisfaction, color='orange', marker='o', label='Customer Satisfaction')
ax2.set_ylabel('Customer Satisfaction Score', color='orange')
ax2.tick_params(axis='y', labelcolor='orange')

plt.title('Quarterly Revenue and Customer Satisfaction')
fig.tight_layout()
plt.show()

You can see the output in the screenshot below.

matplotlib add second y axis

Why this works:

  • ax1 handles the revenue bar chart with the left y-axis.
  • ax2 is created with twinx() and plots the satisfaction line chart on the right y-axis.
  • Different colors help differentiate the two datasets visually.

Read Horizontal Line Matplotlib

Method 2: Use the secondary_y Parameter in Pandas Plot

If you are working with data in a Pandas DataFrame, you can use the secondary_y parameter in Python’s plot() method to quickly create a secondary y-axis.

Here’s an example using the same data:

import pandas as pd

data = {
    'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
    'Revenue': [50, 60, 55, 70],
    'Customer_Satisfaction': [7.8, 8.0, 7.5, 8.3]
}

df = pd.DataFrame(data).set_index('Quarter')

ax = df['Revenue'].plot(kind='bar', color='skyblue', label='Revenue')
df['Customer_Satisfaction'].plot(secondary_y=True, ax=ax, color='orange', marker='o', label='Customer Satisfaction')

ax.set_ylabel('Revenue (Millions $)')
ax.right_ax.set_ylabel('Customer Satisfaction Score')
plt.title('Quarterly Revenue and Customer Satisfaction')
plt.show()

You can see the output in the screenshot below.

matplotlib secondary y axis

What I like about this method:

  • It’s concise and leverages Pandas’ integration with Matplotlib.
  • You don’t have to manually create axes objects.
  • Great for quick exploratory data analysis.

Check out Stacked Bar Chart Matplotlib

Method 3: Customize the Secondary Y-Axis for Better Readability

Simply adding a secondary y-axis isn’t always enough. You want your plots to be clear and visually appealing, especially when presenting to stakeholders in the US market, like sales teams or executives.

Here are some tips I apply:

  • Match colors between axis labels and plot elements: This reduces confusion.
  • Adjust axis limits: Sometimes the default limits don’t fit your data well. Use set_ylim() to adjust.
  • Add legends: Since there are two datasets, include legends for both to clarify.
  • Use gridlines sparingly: Gridlines on the primary y-axis can improve readability without cluttering the plot.

Example with customization:

fig, ax1 = plt.subplots()

# Revenue bar chart
ax1.bar(quarters, revenue, color='skyblue', label='Revenue')
ax1.set_ylabel('Revenue (Millions $)', color='skyblue')
ax1.tick_params(axis='y', labelcolor='skyblue')
ax1.set_ylim(0, 80)

# Secondary axis for satisfaction
ax2 = ax1.twinx()
ax2.plot(quarters, customer_satisfaction, color='orange', marker='o', label='Customer Satisfaction')
ax2.set_ylabel('Customer Satisfaction Score', color='orange')
ax2.tick_params(axis='y', labelcolor='orange')
ax2.set_ylim(0, 10)

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

plt.title('Quarterly Revenue and Customer Satisfaction')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

You can see the output in the screenshot below.

matplotlib second y axis

Read Matplotlib 3D Scatter

When to Avoid Secondary Y-Axis

While secondary y-axes are useful, overusing them can confuse your audience. If the datasets are unrelated or too complex, consider creating separate plots or using subplots instead.

Using a secondary y-axis in Matplotlib has been a game-changer for me when presenting complex data with different scales. The methods I shared here are easy to implement and customize, making your visualizations more effective.

I hope you found this guide helpful!

You may also read the other Matplotlib articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.