DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober 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 Now×
Skip to content
World desk3 min

How to Plot a Matplotlib Secondary Y-Axis with a Log Scale

Create a converted right-side axis with Matplotlib’s secondary_yaxis(), keep its conversion functions array-compatible, and apply log scales where needed.

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.

Use Axes.secondary_yaxis() when the right axis should show converted values of the same quantity as the left axis. Provide forward and inverse conversion functions, then set the logarithmic scale on the primary axis—and on the secondary axis too if you want logarithmic ticks there. For independent data series with separate scales, use twinx() instead.

Plot a converted secondary y-axis on a log scale

This runnable example plots distance in meters on the left and the corresponding values in kilometers on the right. The data are strictly positive so they can be displayed on logarithmic scales.

import matplotlib.pyplot as plt
import numpy as np

# Primary values are meters; secondary values are kilometers.
def meters_to_kilometers(meters):
    return np.asarray(meters) / 1000

def kilometers_to_meters(kilometers):
    return np.asarray(kilometers) * 1000

x = np.linspace(0, 10, 100)
y_meters = np.geomspace(100, 100_000, x.size)

fig, ax = plt.subplots()
ax.plot(x, y_meters)
ax.set_xlabel("x")
ax.set_ylabel("Distance (m)")
ax.set_yscale("log")

secax = ax.secondary_yaxis(
    "right",
    functions=(meters_to_kilometers, kilometers_to_meters),
)
secax.set_ylabel("Distance (km)")
secax.set_yscale("log")

plt.show()

The first function converts primary-axis values to secondary-axis values; the second converts them back. The API requires both functions to accept NumPy arrays, and they should be mutually consistent across the displayed range. Matplotlib’s Axes.secondary_yaxis API reference documents the method and its requirements.

Why the secondary axis needs a conversion

secondary_yaxis("right", functions=(forward, inverse)) creates an axis whose values are derived from the parent axis through the supplied transformation. It is intended for alternate units or representations of the same quantity, not for plotting another dataset. Its limits follow the parent through the conversion; to change the displayed range, adjust the primary axis limits rather than treating the secondary axis as independently scaled.

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

The secondary axis is an overlaid axis, not a data-bearing plotting area. Keep plotting calls on the parent axes. A positive unit conversion such as meters to kilometers preserves positivity, which is necessary for a logarithmic display.

Choose where to apply the logarithmic scale

Use ax.set_yscale("log") to make the primary y-axis logarithmic. Matplotlib uses base 10 by default; pass a different base to set_yscale if another logarithm base is needed. The Matplotlib log-scale guide documents the scale options and how nonpositive values are handled.

To show logarithmic ticks on the right as well, call secax.set_yscale("log"). If you omit that call, the secondary axis does not explicitly receive a logarithmic scale setting. Matplotlib’s secondary-axis gallery example demonstrates a logarithmic parent axis and a child axis that is also made logarithmic.

Check the domain of the data and conversion

Nonpositive values cannot be displayed on a logarithmic scale. Matplotlib masks or clips such values, depending on the configured behavior; choose handling that matches what the data mean rather than silently changing values. Also check the conversion’s output: if it can produce zero or negative values, those values cannot appear on a logarithmic secondary axis.

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

Use twinx() for an unrelated series

If the right axis represents a different quantity or an independent dataset, use a twinned axis such as ax.twinx() rather than supplying a conversion. A twin can plot a separate series and use its own y scale. Label both axes and the plotted series clearly so readers do not mistake the scales for two units of one quantity. Matplotlib distinguishes transformed secondary axes from plots using different scales in its secondary-axis gallery.

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

Version note

The API reference labels secondary_yaxis experimental as of Matplotlib 3.1 and warns that the API may change. Check the documentation for the Matplotlib version used by your environment when maintaining long-lived code.

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.