Add minor log ticks

How do I add unlabeled minor ticks between decades on a Matplotlib log axis?

In Matplotlib, LogLocator(base=10,subs=np.arange(2,10)) adds minor ticks at 2 through 9 within each positive decade.

On this page

Published and tested 21 November 2026.

Which code change produces this result?

I set the log scale first, attach the minor locator, then use NullFormatter for minor labels. The example keeps major decade labels and uses faint minor grid lines over x=1 to 1000.

This article uses simulated example data.

Original output: A positive log axis with major decade ticks only.
Open full-size image
Original output. A positive log axis with major decade ticks only.
Result output: There are eight interior minor positions per decade, including 2 to 9, 20 to 90 and 200 to 900. The underlying 80 sampled values remain unchanged.
Open full-size image
Result output. There are eight interior minor positions per decade, including 2 to 9, 20 to 90 and 200 to 900. The underlying 80 sampled values remain unchanged.

What changes in the actual output?

There are eight interior minor positions per decade, including 2 to 9, 20 to 90 and 200 to 900. The underlying 80 sampled values remain unchanged.

xresponse
1.01.0
1.09137671465127341.044689769573376
1.19110313328300691.0913767146512734
1.29994222441324571.1401500885467868
1.41872667411659651.1911031332830069
1.54836525658549861.2443332578475506
1.68984978681245731.2999422244132457
1.84426270858553451.3580363428809756
2.0127853758499391.4187266741165965
2.1967070907932351.4821292422704693
2.3974349678010771.5483652565854986
2.6165046987488211.6175613431177258

The table shows the first 12 rows; the CSV contains all rows. (80)

What should I check before using this setting?

Only positive values belong to a log axis. This setting owns within-decade ticks; use the separate symlog answer when zero or negative values need a display.

How can I reproduce the figures?

Run python example.py in a writable folder. Tested with Python 3.12.4, Matplotlib 3.8.4 and NumPy 1.26.4. The script writes data.csv, before.png, after.png and after.pdf beside itself.

These are the code, data and result files used in this article. Choose a file below to run the example or compare your results.

  • example.pyComplete example code to run on your computer.
  • data.csvThe input data used in the example; open it as a table.
  • before.pngThe figure before the change, for comparison.
  • after.pngThe figure after applying the settings in this article.
  • after.pdfThe result in PDF format, for viewing and page layout.
  • Usage license · LICENSE.txtTerms for reusing the code, data and figures, with source and font notices.
File verification
  • hashes.jsonChecksums for checking whether the downloaded files are complete.

Complete Python code

# Original Bopbun example, CC0-1.0. See LICENSE.txt for font/software notices.
# Tested: Python 3.12.4, Matplotlib 3.8.4, NumPy 1.26.4.
from pathlib import Path
import csv
import json
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import colors, dates
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.backends.backend_agg import FigureCanvasAgg
from datetime import datetime, timedelta
from textwrap import fill

OUT = Path(__file__).resolve().parent
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11,
    "axes.spines.top": False, "axes.spines.right": False,
    "pdf.fonttype": 42, "figure.dpi": 120, "savefig.dpi": 160})

def data_file(header, rows):
    with (OUT / "data.csv").open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f); w.writerow(header); w.writerows(rows)

def canvas():
    return plt.subplots(figsize=(7.2, 4.5), layout="constrained")

def line_data():
    x = np.arange(1, 7)
    y = np.array([2., 4., 3., 6., 5., 8.])
    data_file(["time", "response"], zip(x, y))
    return x, y

def matrix_data():
    z = np.array([[1., 3., 5., 7.], [2., 4., 6., 8.], [0., 2., 4., 6.]])
    data_file(["row", "column", "value"], ((i,j,z[i,j]) for i,j in np.ndindex(z.shape)))
    return z

from matplotlib import ticker
from matplotlib.collections import LineCollection


def make(fixed):
    x=np.logspace(0,3,80);y=np.sqrt(x);data_file(['x','response'],zip(x,y));fig,ax=canvas();ax.plot(x,y)
    ax.set_xscale('log');ax.set(xlim=(1,1000),xlabel='Positive input (a.u.)',ylabel='Response (a.u.)',title='Minor ticks at 2 through 9 in each decade')
    if fixed:
        ax.xaxis.set_minor_locator(ticker.LogLocator(base=10,subs=np.arange(2,10)));ax.xaxis.set_minor_formatter(ticker.NullFormatter());ax.grid(which='minor',axis='x',alpha=0.15)
    else:ax.xaxis.set_minor_locator(ticker.NullLocator())
    ax.grid(which='major',axis='x',alpha=0.35);return fig

if __name__ == '__main__':
    before=make(False);after=make(True)
    before.savefig(OUT/'before.png');after.savefig(OUT/'after.png')
    after.savefig(OUT/'after.pdf',metadata={'CreationDate':None,'ModDate':None})
    after.canvas.draw();print(json.dumps({'axes':len(after.axes),'limits':[{'x':list(a.get_xlim()),'y':list(a.get_ylim())} for a in after.axes]}))
    plt.close('all')

Which sources and licenses apply?

Original code and data: CC0-1.0. Figures use DejaVu Sans; its font license remains separate. Install Matplotlib and NumPy locally to run the code.

Historical discussion.

Which related answer do I need?

Research figure questions