October 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 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

Matplotlib Two Y Axes in Python: Plot Independent Scales

Use twinx() to plot two independent series against one x-axis, or secondary_yaxis() when the second scale is a conversion of the same quantity.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To plot two independent quantities against the same x-values in Matplotlib, create a second axes with ax2 = ax1.twinx(). Plot one series on each axes: the first uses the left y-axis, and the second uses the right. If the second scale is just a unit conversion of the first, use secondary_yaxis() instead.

Plot two independent y-values with twinx()

Axes.twinx() creates a second Axes that shares the original x-axis but has its own y-scale and right-side y-ticks. Use it when the two plotted series are independent measurements, such as temperature and rainfall. The following example assumes x, y_left, and y_right are already defined as compatible sequences.

As an Amazon Associate I earn from qualifying purchases.

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

ax1.plot(x, y_left, color="tab:red", label="Left quantity")
ax1.set_ylabel("Left quantity (unit)", color="tab:red")
ax1.tick_params(axis="y", labelcolor="tab:red")

ax2.plot(x, y_right, color="tab:blue", label="Right quantity")
ax2.set_ylabel("Right quantity (unit)", color="tab:blue")
ax2.tick_params(axis="y", labelcolor="tab:blue")

fig.tight_layout()
plt.show()

Replace each label’s quantity and unit with the meaning of your data. Matching the line, axis-label, and tick-label colors makes it easier to see which scale belongs to which series. fig.tight_layout() helps keep the right-side label from being clipped.

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.

Show both series in one legend

Each Axes owns its own plotted artists, so collect handles and labels from both before creating a combined legend:

lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc="best")

Place this after plotting both series and before plt.show(). The labels come from the label arguments in the plot calls.

Use secondary_yaxis() for a converted scale

If both scales express the same underlying quantity in different units—for example, Celsius and Fahrenheit—use ax.secondary_yaxis("right", functions=(forward, inverse)). Here, forward converts values from the parent axis’s units to the secondary units, and inverse converts them back. Both functions must accept NumPy arrays. Plot the data on the parent Axes; the secondary axis is for displaying the transformed scale, not for holding a separate data series.

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)")

For exact requirements and behavior, see Matplotlib’s secondary_yaxis API documentation.

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

Choose the axis API that matches the data

Need Use Why
Two independent series sharing an x-axis ax1.twinx() Creates another Axes with its own y-scale.
A second y-scale that converts the same quantity ax.secondary_yaxis() Derives its displayed scale from the parent through conversion functions.

Matplotlib’s twinx API documentation describes the second Axes as sharing the x-axis. Its y-scale remains independent, so the two axes’ limits and tick values are not automatically synchronized.

Make the comparison readable and avoid misleading alignment

  • Label both y-axes with the quantity and unit; do not rely on color alone.
  • Use distinct, consistent colors for each series and its corresponding y-axis labels and ticks.
  • Remember that independent scales can make unrelated trends look visually aligned. If that could mislead readers, consider separate panels instead of two y-axes.
  • If matching tick-mark positions is important, Matplotlib’s twinx documentation points to LinearLocator. Aligned positions do not make the scales equivalent.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Know the overlay and interaction behavior

The two Axes occupy the same plotting area. Matplotlib notes that, when picking artists on twin Axes, pick events are called only for artists in the top-most Axes. This matters when building interactive charts that rely on picking; consult the Axes.twinx documentation for the API’s behavior.

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.