Matplotlib Two Y Axes in Python

I’ve often faced the challenge of visualizing data that involves two different scales or units on the same plot. This is especially common in fields like finance, economics, or marketing analytics, where you might want to compare stock prices with trading volume, or GDP growth with unemployment rates, all in one clear, concise graph.

Matplotlib, Python’s go-to library for plotting, doesn’t just offer basic charts; it also supports more advanced visualizations like dual y-axes. This lets you present two datasets with different scales side-by-side, making your insights much easier to grasp.

In this article, I’ll walk you through the most effective methods to create plots with two y-axes using Matplotlib. I’ll share practical examples you can relate to, especially if you’re working with US economic or business data.

Methods to Use Two Y Axes

Imagine you want to compare the monthly average temperature in New York City with the monthly electricity consumption of households. Temperature is measured in degrees Fahrenheit, while electricity consumption is in kilowatt-hours. Plotting these on the same y-axis would be misleading because their scales differ greatly.

Using two y-axes allows you to visualize both datasets clearly without distorting the data’s meaning.

Read Matplotlib set_yticklabels

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

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

Here’s how I typically implement it:

import matplotlib.pyplot as plt

# Sample data: Monthly average temperature (°F) and electricity consumption (kWh) in NYC
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
temperature = [31, 35, 45, 56, 66, 75, 80, 78, 70, 59, 48, 37]
electricity = [320, 300, 280, 260, 240, 220, 210, 215, 230, 250, 280, 310]

fig, ax1 = plt.subplots()

# Plot temperature on the left y-axis
ax1.plot(months, temperature, 'r-o', label='Temperature (°F)')
ax1.set_xlabel('Month')
ax1.set_ylabel('Temperature (°F)', color='r')
ax1.tick_params(axis='y', labelcolor='r')

# Create a second y-axis for electricity consumption
ax2 = ax1.twinx()
ax2.plot(months, electricity, 'b-s', label='Electricity Consumption (kWh)')
ax2.set_ylabel('Electricity Consumption (kWh)', color='b')
ax2.tick_params(axis='y', labelcolor='b')

# Add title and show plot
plt.title('NYC Monthly Temperature and Electricity Consumption')
fig.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

matplotlib two y axes
  • The left y-axis shows temperature in red, and the right y-axis shows electricity consumption in blue.
  • Using color coding helps users quickly associate each line with its respective axis.
  • The shared x-axis (months) keeps the timeline consistent and easy to follow.

2: Use secondary_y in Pandas Plotting (If Data is in DataFrame)

If your data is in a Pandas DataFrame, you can leverage the secondary_y parameter in the DataFrame’s plot() method. This is a quick way to plot two series with different y-axes without explicitly using Matplotlib’s twinx().

Here’s how I use it with US economic data:

import pandas as pd
import matplotlib.pyplot as plt

# Sample DataFrame with US GDP growth (%) and unemployment rate (%)
data = {
    'Year': list(range(2010, 2021)),
    'GDP Growth': [2.5, 1.6, 2.2, 1.8, 2.5, 2.9, 1.6, 2.4, 2.9, 2.3, -3.5],
    'Unemployment Rate': [9.6, 8.9, 8.1, 7.4, 6.2, 5.3, 4.9, 4.4, 3.9, 3.7, 8.1]
}

df = pd.DataFrame(data)
df.set_index('Year', inplace=True)

# Plot GDP Growth on left y-axis and Unemployment Rate on right y-axis
ax = df['GDP Growth'].plot(color='green', label='GDP Growth (%)')
df['Unemployment Rate'].plot(secondary_y=True, color='orange', label='Unemployment Rate (%)', ax=ax)

ax.set_ylabel('GDP Growth (%)')
ax.right_ax.set_ylabel('Unemployment Rate (%)')
plt.title('US GDP Growth vs Unemployment Rate (2010-2020)')
ax.figure.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

matplotlib two y axis
  • It’s concise and leverages Pandas’ built-in plotting capabilities.
  • Great for quick exploratory analysis when working with DataFrames.
  • Automatically handles legends and axis labeling.

Read Matplotlib fill_between

3: Customize Two Y Axes with Additional Features

Sometimes you want more control over the appearance of your dual y-axis plot. For example, adjusting axis limits, ticks, or adding grid lines can improve readability.

Here’s an example with some customization:

fig, ax1 = plt.subplots()

# Plotting stock price of a US company (e.g., Apple) and its trading volume
dates = pd.date_range(start='2025-01-01', periods=10, freq='D')
stock_price = [150, 152, 148, 155, 157, 160, 162, 161, 159, 158]
volume = [1.2e7, 1.5e7, 1.1e7, 1.8e7, 2.0e7, 1.7e7, 1.6e7, 1.9e7, 1.4e7, 1.3e7]

ax1.plot(dates, stock_price, 'g-', label='Stock Price ($)')
ax1.set_xlabel('Date')
ax1.set_ylabel('Stock Price ($)', color='g')
ax1.tick_params(axis='y', labelcolor='g')
ax1.set_ylim(145, 165)

ax2 = ax1.twinx()
ax2.bar(dates, volume, alpha=0.3, color='blue', label='Volume')
ax2.set_ylabel('Trading Volume', color='blue')
ax2.tick_params(axis='y', labelcolor='blue')
ax2.set_ylim(0, 2.5e7)

plt.title('Apple Stock Price and Trading Volume Over 10 Days')
fig.tight_layout()
plt.show()

I executed the above example code and added the screenshot below.

matplotlib secondary y axis
  • Setting the y-axis limits to better frame the data range.
  • Using a bar chart for volume on the secondary axis for better visual distinction.
  • Transparency on bars (alpha=0.3) to avoid overpowering the line plot.

Check out Matplotlib set_xticklabels

Tips for Effective Dual Y-Axis Plots

  • Color-code your axes and plots to avoid confusion.
  • Label both y-axes clearly with units to prevent misinterpretation.
  • Avoid cluttering the plot with too many lines or bars.
  • Use legends or annotations for clarity.
  • Remember that dual y-axes can sometimes mislead if scales are manipulated improperly, so always be transparent about axis scales.

I hope you find these methods helpful for your data visualization projects, especially when dealing with complex datasets involving multiple metrics. Matplotlib’s flexibility makes it straightforward to create insightful and visually appealing plots with two y-axes, whether you’re analyzing US economic indicators, business KPIs, or environmental data.

You may also read 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.