0
0
Matplotlibdata~5 mins

Secondary axes in Matplotlib

Choose your learning style9 modes available
Introduction

Secondary axes let you show two different scales on the same plot. This helps compare data that have different units or ranges.

You want to compare temperature and sales on the same chart.
You have data in kilometers and miles and want to show both scales.
You want to display revenue and profit margin together but they use different units.
You want to add a percentage scale alongside a count scale on a graph.
Syntax
Matplotlib
ax.secondary_xaxis(location, functions=(forward, inverse))
ax.secondary_yaxis(location, functions=(forward, inverse))

location is where the secondary axis appears (e.g., 'top' or 'right').

functions are two functions: one to convert from primary to secondary axis, and one to convert back.

Examples
Adds a secondary y-axis on the right side with the same scale as the primary y-axis.
Matplotlib
secax = ax.secondary_yaxis('right')
Adds a secondary x-axis on top converting kilometers to miles and back.
Matplotlib
secax = ax.secondary_xaxis('top', functions=(lambda x: x*1.6, lambda x: x/1.6))
Sample Program

This code plots y = x² on the primary y-axis. It adds a secondary y-axis on the right side that shows the values scaled down by 10. This helps compare the same data in a different scale.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y1 = x ** 2  # primary y-axis data

def forward(x):
    return x / 10  # convert primary y to secondary y

def inverse(x):
    return x * 10  # convert secondary y back to primary y

fig, ax = plt.subplots()
ax.plot(x, y1, label='y = x^2')
ax.set_ylabel('Primary Y axis (x^2)')

secax = ax.secondary_yaxis('right', functions=(forward, inverse))
secax.set_ylabel('Secondary Y axis (scaled)')

ax.set_xlabel('X axis')
ax.legend()
plt.show()
OutputSuccess
Important Notes

Secondary axes need conversion functions if scales differ.

Without functions, the secondary axis matches the primary axis scale.

Use secondary axes to make complex data easier to understand.

Summary

Secondary axes show two scales on one plot.

Use conversion functions to link primary and secondary axes.

They help compare different units or ranges clearly.