Linear axes make equal numeric gaps look equal, which can bury patterns when a Matplotlib plot spans several powers of ten. A logarithmic axis spaces ticks by ratio, so growth from 100 to 1,000 uses the same visual interval as growth from 10,000 to 100,000.
The object-oriented Axes API keeps the scale change attached to one subplot. Set the vertical scale with ax.set_yscale(“log”), or set the horizontal scale with ax.set_xscale(“log”) when the x values span the wide range.
Use positive values on a normal logarithmic axis. Matplotlib uses base 10 by default for log scale, and data at zero or below needs a deliberate choice such as masking, clipping, or symlog before it is plotted.
Related: How to create a line chart in Matplotlib
Related: How to set axis limits in Matplotlib
Related: How to format tick labels in Matplotlib
Steps to set a Matplotlib axis to log scale:
- Keep the values on the log-scaled axis positive.
Values at zero or below cannot be positioned on a normal logarithmic scale. Mask or clip them deliberately, or use symlog when the plot must include values on both sides of zero.
- Save the plotting script as log_axis_scale.py.
- log_axis_scale.py
import matplotlib.pyplot as plt years = [2022, 2023, 2024, 2025, 2026] requests = [250, 1800, 12600, 94000, 710000] fig, ax = plt.subplots(layout="constrained") ax.plot(years, requests, marker="o") ax.set_yscale("log") ax.set_xticks(years) ax.set_xlabel("Year") ax.set_ylabel("Requests") ax.set_title("Requests by year") ax.grid(True, which="both", axis="y", color="0.9") fig.savefig("requests-log-axis.png", dpi=150) print(f"x scale: {ax.get_xscale()}") print(f"y scale: {ax.get_yscale()}") print("saved: requests-log-axis.png")
ax.set_yscale(“log”) changes only the y-axis. Use ax.set_xscale(“log”) instead for a horizontal log axis, or use both calls when both dimensions need logarithmic spacing.
- Run the script.
$ python log_axis_scale.py x scale: linear y scale: log saved: requests-log-axis.png
- Open the saved PNG and confirm the y-axis is spaced by powers of ten.
Look for y scale: log in the output and powers-of-ten spacing on the y-axis in the image.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.