October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Plot Two Y Axes with the Same Data in Matplotlib

Use twinx() for two independent series sharing an x-axis; use secondary_yaxis() when the second scale is a conversion of the first.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To put two independent data series on one Matplotlib plot with a shared x-axis, create a second Axes with ax1.twinx() and plot the second series on it. If the axes show the same quantity in different units, such as Celsius and Fahrenheit, use secondary_yaxis() with a conversion and its inverse instead.

Choose the right kind of second y-axis

Use case API How the second scale behaves
Two independent series that share an x-axis Axes.twinx() Creates another Axes with an independent y-axis, normally on the right. Each Axes owns the series plotted on it and can have its own y limits, tick locator, and formatter. Matplotlib Axes.twinx API
One quantity expressed on two related scales, such as Celsius and Fahrenheit Axes.secondary_yaxis() Shows a converted scale derived from the parent axis. Supply forward and inverse conversion functions; the parent Axes controls the view limits. Matplotlib secondary_yaxis API

In short: use twinx() when each series has its own values and scale; use secondary_yaxis() when the second scale is a conversion of the first. A secondary axis is not a place to plot an unrelated second dataset.

Plot two independent series with twinx()

This example puts y1 on the left axis and y2 on the right. Replace the sample arrays with your data; x must contain the corresponding shared x-values.

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

ax1.plot(x, y1, color="tab:red")
ax1.set_xlabel("X")
ax1.set_ylabel("Series 1", color="tab:red")
ax1.tick_params(axis="y", labelcolor="tab:red")

ax2 = ax1.twinx()
ax2.plot(x, y2, color="tab:blue")
ax2.set_ylabel("Series 2", color="tab:blue")
ax2.tick_params(axis="y", labelcolor="tab:blue")

fig.tight_layout()
plt.show()

What the code does

  • plt.subplots() creates the figure and the first Axes, ax1.
  • ax1.twinx() creates a second Axes that shares the x-axis and has its own y-axis, positioned on the right by default. Plot y2 on ax2, not on ax1. Matplotlib Axes.twinx API
  • The matching line, label, and tick colors help show which scale belongs to which series. fig.tight_layout() can help keep the right-side label within the figure. Matplotlib two-scales example

Set each scale independently

Because the two Axes have independent y-axes, set a limit, tick locator, or formatter on the Axes that owns the corresponding series. For example, ax1.set_ylim(...) affects the left scale, while ax2.set_ylim(...) affects the right. Choose limits that preserve the meaning of each dataset rather than adjusting them solely to make the lines overlap.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Use secondary_yaxis() for convertible units

When both sides represent the same underlying quantity, define a forward conversion from the primary scale and an inverse conversion back. For Celsius and Fahrenheit, the conversion is F = C * 9 / 5 + 32, and its inverse is C = (F - 32) * 5 / 9.

def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

def fahrenheit_to_celsius(f):
    return (f - 32) * 5 / 9

fig, ax = plt.subplots()
ax.plot(x, temperature_c)
ax.set_ylabel("Temperature (°C)")

secax = ax.secondary_yaxis(
    "right",
    functions=(celsius_to_fahrenheit, fahrenheit_to_celsius),
)
secax.set_ylabel("Temperature (°F)")

fig.tight_layout()
plt.show()

The conversion functions need to work with NumPy arrays. The secondary axis derives its range from the parent Axes through those functions; setting limits directly on the secondary axis does not control the displayed view. Matplotlib labels the secondary_yaxis() API experimental, so check the documentation and compatibility for the Matplotlib release you use. The stable documentation surfaced here is labeled Matplotlib 3.11.2; that does not establish which version is installed in your environment. Matplotlib secondary_yaxis API

Common issues with twinned axes

  • The right-axis label is clipped: call fig.tight_layout() and check the saved or displayed figure. Layout behavior can depend on how and where the figure is rendered.
  • It is unclear which scale belongs to which line: use distinct line colors and repeat those colors for the matching y-axis label and tick labels.
  • A line appears misleadingly aligned with the other: remember that each y-axis can have independent limits. The apparent crossing or overlap depends on those limits, so it does not by itself establish a relationship between the series.
  • Pick events miss artists: with twinned Axes, Matplotlib calls pick events only for artists in the top-most Axes. This matters when building interactive plots. Matplotlib Axes.twinx API

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
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.