How to add a logarithmic axis in Matplotlib (with Code)
The Short Answer (TL;DR)
Call ax.set_yscale("log", base=10) to display positive y values on a base-10 logarithmic axis. Equal ratios then occupy equal vertical distances, which helps compare values across several orders of magnitude.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(); ax.plot([1, 2, 3], [1, 10, 100], marker="o")
ax.set_yscale("log", base=10)
Detailed Implementation
This example uses synthetic data and does not need a network connection. Install the recorded package versions in a separate Python environment before running it.
python -m pip install numpy==2.5.4 pandas==3.0.6 matplotlib==3.11.2 seaborn==0.13.2
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 5)
y = np.array([1.0, 10.0, 100.0, 1000.0])
fig, ax = plt.subplots(figsize=(5.4, 3.5), layout="constrained")
ax.plot(x, y, marker="o", color="#176b87")
ax.set_yscale("log", base=10)
ax.set(xlabel="Step", ylabel="Positive response (log scale)",
title="A tenfold increase at each step")
ax.grid(True, which="major", alpha=0.3)
fig.savefig("logarithmic-axis.png", dpi=160)
plt.show()
The four points are equally spaced vertically because each response is ten times the previous response. The y-axis retains labels in the original response units.
Should the values be logged before plotting?
Use original positive values with a log axis when ticks should display the original units. Taking logarithms first and then setting a logarithmic axis applies two transformations and usually changes the intended chart. Plotting logged values on a linear axis is a different, valid presentation when its units are clearly labelled.
What happens to zeros and negative values?
An ordinary real logarithm is undefined at zero and for negative inputs. Matplotlib may clip or mask such values depending on settings, which can hide important observations. Inspect and handle them explicitly rather than replacing them with an arbitrary small positive number. A symlog axis is a different scale with a linear region near zero.
Does changing the base change the ordering?
Any logarithm with a base greater than one preserves the order of positive values. A different base changes tick spacing and labels; it does not turn a multiplicative relationship into an additive one. State the scale clearly when presenting a chart to readers.
Mathematical Context
A base-10 logarithmic axis maps a positive response y to log₁₀(y) before positioning it. The displayed values 1, 10, 100 and 1000 therefore map to 0, 1, 2 and 3. More generally, log₁₀(ay) − log₁₀(y) = log₁₀(a), so multiplying by the same positive factor produces the same display displacement.
\[ \log_{10}(ay)-\log_{10}(y)=\log_{10}(a) \]
Reproducibility
Executed with Python 3.12.14; numpy 2.5.4, pandas 3.0.6, matplotlib 3.11.2, seaborn 0.13.2. Automated checks confirm the stated output properties.