October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober 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: When to Use twinx() or a Secondary Axis

Use twinx() for independent measurements sharing x, secondary_yaxis() for a genuine unit conversion, and one y axis when both series share a comparable scale.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For two unrelated measurements that share an x variable, use Matplotlib’s Axes.twinx() to give each series its own y scale. If the right axis is a unit conversion of the same measurement, use secondary_yaxis() with forward and inverse conversion functions. When both series have the same units and fit one comparable range, plot them on a single y axis instead.

Choose the axis method that matches the data

Data relationship Recommended approach Why
Same unit and comparable values One Axes, one y scale A second axis is unnecessary when both series can be read against the same valid scale.
Different measurements with a common x variable Axes.twinx() It creates a second Axes with an independent y scale while sharing the x axis.
Same measurement shown in another unit Axes.secondary_yaxis() The second scale expresses a defined conversion of the parent axis rather than an unrelated measurement.

Matplotlib’s “Plots with different scales” example uses two Axes that share x, created with twinx(). The secondary-axis example demonstrates a converted scale with explicit forward and inverse functions.

As an Amazon Associate I earn from qualifying purchases.

Plot independent measurements with twinx()

Call twinx() on the original Axes. Plot each series on the Axes whose y-axis label and scale describe it. Give the lines and corresponding y-axis labels or tick labels matching colors so the mapping is easy to follow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()
ax1.plot(x, y1, color="tab:red")
ax1.set_xlabel("time (s)")
ax1.set_ylabel("quantity 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("quantity 2", color="tab:blue")
ax2.tick_params(axis="y", labelcolor="tab:blue")

fig.tight_layout()
plt.show()

The resulting right-hand y scale is independent of the left-hand scale. The x-axis autoscale setting is inherited from the original Axes. Use tight_layout() to help keep the right y-axis label from being clipped. These behaviors are documented in Matplotlib’s Axes.twinx API and its two-scales example.

Make the scale mapping explicit

  • Label both y axes with the measured quantity and its unit.
  • Use line and axis colors consistently, as in the example above.
  • Do not imply that two series are directly comparable merely because they share a chart. Independent scales can be adjusted separately, so the visual relationship between lines can be misleading unless the measurements and axis mappings are clear.

Align tick positions when needed

If the left and right y-axis tick positions should line up, Matplotlib’s API notes that a locator such as LinearLocator can be used. Matching tick positions does not make the values or units equivalent; explain what each scale represents.

Show a converted unit with secondary_yaxis()

For a true conversion—such as displaying radians on the main axis and degrees on the right—use secondary_yaxis(). Supply a forward function that converts the parent scale to the displayed scale, and an inverse function that converts back:

secax = ax.secondary_yaxis(
    "right",
    functions=(forward, inverse),
)
secax.set_ylabel("converted units")

Both functions must accept NumPy arrays. The API also permits an invertible Transform instead of a function pair. The secondary limits are derived from the parent Axes, so setting limits directly on the secondary axis has no effect. See Matplotlib’s secondary-axis example and its documentation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

When separate subplots are a better choice

If two independent scales make it difficult to judge the data, put the measurements in separate subplots with a shared x axis. This keeps their time or category alignment while avoiding a single plot whose two y scales may suggest a stronger visual relationship than the data supports.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Version note

Matplotlib’s stable documentation cited here identified version 3.11.2 for the two-scales gallery example and the Axes.twinx API. Stable documentation can change over time; consult the documentation for your installed Matplotlib version if relying on version-specific behavior or optional parameters.

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
Crashes, No Sound, or Screen Glitches?Free driver 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.