Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Add a Secondary Y-Axis in Matplotlib

Use secondary_yaxis() for a converted scale of the same quantity, or twinx() for an independent series sharing the x-axis.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the Matplotlib API based on what the second scale means: use secondary_yaxis() for a reversible conversion of the same quantity, such as Celsius to Fahrenheit; use twinx() for a separate quantity that shares the same x-axis. The distinction determines where you plot the data and how the right-hand axis gets its limits.

Choose the right kind of second y-axis

What the second axis represents Use Where to plot the data How the second scale behaves
The same quantity expressed in different units, such as temperature in °C and °F Axes.secondary_yaxis() Plot on the parent Axes; the secondary axis is for displaying the transformed scale Its limits derive from the parent axis through the conversion
A different quantity measured alongside the first, such as two unrelated measurements over time Axes.twinx() Plot the second series on the new Axes returned by twinx() Each y-axis has its own scale and can be configured independently

Matplotlib’s “Plots with different scales” example uses two Axes that share an x-axis. For a unit conversion, however, prefer a secondary axis: it makes the relationship between the scales explicit rather than treating them as unrelated measurements.

Show a converted scale with secondary_yaxis()

For Celsius data with Fahrenheit ticks on the right, provide a forward conversion from the parent axis scale and an inverse conversion back to it. The pair must be in that order:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Plot the data on the parent Axes in Celsius.
ax.plot(x, temperature_c, color="tab:red")
ax.set_xlabel("Time")
ax.set_ylabel("Temperature (°C)", color="tab:red")
ax.tick_params(axis="y", labelcolor="tab:red")

def celsius_to_fahrenheit(c):
    return c * 1.8 + 32

def fahrenheit_to_celsius(f):
    return (f - 32) / 1.8

secax = ax.secondary_yaxis(
    "right",
    functions=(celsius_to_fahrenheit, fahrenheit_to_celsius),
)
secax.set_ylabel("Temperature (°F)", color="tab:blue")
secax.tick_params(axis="y", labelcolor="tab:blue")

fig.tight_layout()
plt.show()

Replace x and temperature_c with your own arrays. The functions must accept NumPy arrays, not just individual scalar values. Matplotlib’s secondary-axis example shows the same Celsius/Fahrenheit conversion pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Control the parent axis, not the secondary one

The secondary axis derives its limits from the parent Axes through the supplied transformation. Set the visible data range on ax, for example with ax.set_ylim(...). Setting limits on the secondary axis does not control the parent range. The secondary-axis API documentation describes it as a display axis rather than an Axes for plotting data.

Make custom conversions valid across the visible range

If your mapping is nonlinear or custom, both directions need to work not only for the values in the dataset but throughout the full visible axis range, including margins around the plotted values. Matplotlib’s secondary-axis example specifically cautions that the mapping should extend beyond the nominal plotted data so those margins can be handled.

Plot independent quantities with twinx()

When the second series is a different measurement—not a conversion of the first—create a twin Axes and plot that series on the returned object:

fig, ax1 = plt.subplots()
ax1.plot(x, series_left, color="tab:red")
ax1.set_xlabel("Time")
ax1.set_ylabel("Quantity A", color="tab:red")
ax1.tick_params(axis="y", labelcolor="tab:red")

ax2 = ax1.twinx()
ax2.plot(x, series_right, color="tab:blue")
ax2.set_ylabel("Quantity B", color="tab:blue")
ax2.tick_params(axis="y", labelcolor="tab:blue")

fig.tight_layout()

twinx() creates another Axes that shares the x-axis while keeping an independent y-axis on the opposite side. Configure each y-axis on its own Axes: use ax1 for the first series and its scale, and ax2 for the second. The official Axes.twinx API documents this shared-x, independent-y arrangement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Label and lay out both axes clearly

  • Give each axis a descriptive label with units, such as Temperature (°C) and Temperature (°F), or the names and units of two independent quantities.
  • Color an axis label and its tick labels to match its line when that helps readers connect the scale to the data series.
  • Call fig.tight_layout() to help keep the right-side label from being clipped at the edge of the figure.

These choices are illustrated in Matplotlib’s two-scales example. For version-specific details, consult the API documentation matching the Matplotlib version installed in your environment; the cited stable API pages may reflect a different release.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.