How to Set Ticks and Tick Frequency in Matplotlib

Change how often Matplotlib draws ticks with set_xticks, MultipleLocator, and MaxNLocator, add custom tick labels and minor ticks, and control date ticks.

To put a tick every N units in Matplotlib, use ax.xaxis.set_major_locator(MultipleLocator(N)). To choose exact positions and labels, use ax.set_xticks(positions, labels=names). The same calls exist for the y-axis (ax.yaxis and ax.set_yticks).

Quick Example

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator

rng = np.random.default_rng(31)
km = np.linspace(0, 42.2, 300)
elevation = 120 + 45 * np.sin(km / 5.5) + 20 * np.sin(km / 1.9) + rng.normal(0, 1.2, km.size)

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.fill_between(km, elevation, color="#a7f3d0")
ax.plot(km, elevation, color="#047857", linewidth=1.5)
ax.set_xlim(0, 42.2)
ax.set_ylim(0, 200)
ax.xaxis.set_major_locator(MultipleLocator(5))   # labeled tick every 5 km
ax.xaxis.set_minor_locator(MultipleLocator(1))   # small tick every 1 km
ax.yaxis.set_major_locator(MultipleLocator(50))
ax.set_title("Marathon elevation profile")
ax.set_xlabel("Distance (km)")
ax.set_ylabel("Elevation (m)")
plt.show()

Matplotlib marathon elevation profile with x-axis ticks every 5 km, minor ticks every kilometer, and y-axis ticks every 50 meters

The x-axis now has a labeled tick every 5 km with unlabeled ticks for each kilometer between them. The code targets Matplotlib 3.10 and 3.11.

Which Tick Method Should I Use?

You want Use
A tick every N units MultipleLocator(N)
No more than N intervals, at round numbers MaxNLocator(N) or ax.locator_params(axis="x", nbins=N)
Whole numbers only MaxNLocator(integer=True)
Exactly N evenly spaced ticks LinearLocator(N)
Ticks at specific positions, with your own text ax.set_xticks(positions, labels=...)
Small unlabeled ticks between the main ones ax.minorticks_on() or AutoMinorLocator(n)
Ticks on month, week, or day boundaries locators from matplotlib.dates

A locator decides where ticks go. A formatter decides what text they show. Locators keep working when the data or zoom level changes; a fixed list of positions doesn't.

Set Specific Tick Positions and Labels

Pass a list of positions to ax.set_xticks, plus labels if the numbers should read as something else. The two lists must be the same length.

fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
ax.plot(km, elevation, color="#047857", linewidth=1.5)
ax.set_xticks([0, 10, 21.1, 30, 42.2],
              labels=["Start", "10K", "Half", "30K", "Finish"])
for x in ax.get_xticks():
    ax.axvline(x, color="#d1d5db", linewidth=1, zorder=0)
ax.set_xlim(0, 42.2)
ax.set_title("Ticks at the race checkpoints")
ax.set_ylabel("Elevation (m)")
plt.show()

Elevation line chart with custom x tick labels Start, 10K, Half, 30K, and Finish at unevenly spaced positions

Things to watch:

  • The labels argument of set_xticks was added in Matplotlib 3.5. Calling set_xticklabels() on its own raises a UserWarning, because the labels can end up on the wrong ticks. Set both together.
  • set_xticks expands the axis limits if a position falls outside them. Call set_xlim afterwards if you need a specific range.
  • ax.set_xticks([]) removes the ticks completely. See hiding axis ticks and labels for the other options.
  • With pyplot, the equivalent is plt.xticks(positions, labels).

For long labels that overlap, add rotation=45 to set_xticks or follow Rotating Axis Labels in Matplotlib.

Change Tick Frequency with Locators

Here is the same 0 to 130 axis with five different locators:

from matplotlib.ticker import FixedLocator, LinearLocator, MaxNLocator

locators = [
    ("AutoLocator (default)", None),
    ("MultipleLocator(25)", MultipleLocator(25)),
    ("MaxNLocator(4)", MaxNLocator(4)),
    ("LinearLocator(6)", LinearLocator(6)),
    ("FixedLocator([0, 33, 90, 120])", FixedLocator([0, 33, 90, 120])),
]
fig, axes = plt.subplots(len(locators), 1, figsize=(8, 4.8), layout="constrained")
for ax, (name, locator) in zip(axes, locators):
    ax.set_xlim(0, 130)
    if locator is not None:
        ax.xaxis.set_major_locator(locator)
    ax.set_yticks([])
    ax.spines[["left", "right", "top"]].set_visible(False)
    ax.set_title(name, loc="left", family="monospace", fontsize=11)
plt.show()

Five number lines comparing tick placement: the default uses steps of 20, MultipleLocator steps of 25, MaxNLocator steps of 40, LinearLocator steps of 26, and FixedLocator the four listed positions

MaxNLocator treats the number as an upper limit on intervals and picks a "nice" step, here 40. LinearLocator gives the exact count but doesn't care whether the values are round.

Create a new locator object for each axis. A locator is bound to the axis you attach it to, so sharing one instance between axes gives wrong ticks.

Add and Style Minor Ticks

AutoMinorLocator(n) splits each major interval into n parts. ax.tick_params styles the tick marks, and which picks major, minor, or both.

from matplotlib.ticker import AutoMinorLocator

t = np.linspace(0, 10, 400)
signal = np.exp(-t / 4) * np.cos(2 * np.pi * t / 2.5)

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.plot(t, signal, color="#7c3aed", linewidth=2)
ax.xaxis.set_major_locator(MultipleLocator(2))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(5))
ax.tick_params(which="major", direction="in", length=8, width=1.4, top=True, right=True)
ax.tick_params(which="minor", direction="in", length=4, color="#6b7280", top=True, right=True)
ax.grid(which="major", color="#d1d5db")
ax.grid(which="minor", color="#f3f4f6")
ax.set_title("Damped oscillation with major and minor ticks")
ax.set_xlabel("Seconds")
plt.show()

Damped oscillation plot with inward-pointing major and minor ticks on all four sides and a two-level grid

Gridlines follow the tick locations, so changing the locator also moves the grid. More on that in Customizing the Grid in Matplotlib.

Set Date Tick Frequency

Date axes use locators from matplotlib.dates: YearLocator, MonthLocator, WeekdayLocator, DayLocator, and HourLocator. Don't use MultipleLocator for calendar units, since months aren't all the same length.

import matplotlib.dates as mdates

days = np.arange("2026-01-01", "2027-01-01", dtype="datetime64[D]")
n = days.size
bookings = (200 + 90 * np.sin((np.arange(n) - 100) / 365 * 2 * np.pi)
            + rng.normal(0, 14, n))

fig, ax = plt.subplots(figsize=(8, 3.8), layout="constrained")
ax.plot(days, bookings, color="#c2410c", linewidth=1.2)
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1, 4, 7, 10]))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
ax.tick_params(which="major", length=7)
ax.set_title("Daily bookings, quarterly major ticks")
plt.show()

Line chart of daily bookings over 2026 with labeled ticks at the start of each quarter and minor ticks each month

DateFormatter takes strftime codes. There are more examples in custom date formatting in Matplotlib.

Practical Tips

  • On a categorical bar chart the ticks sit at 0, 1, 2, and so on. Use those integers if you need to reposition labels.
  • If MultipleLocator with a tiny step makes a solid black axis, the step is too small for the data range. Matplotlib logs a warning when a locator would create more than 1,000 ticks.
  • To change how values are written (currency, percent, thousands), set a formatter. See formatting axis labels as currency or percentages.
  • Log axes need LogLocator, set up automatically by ax.set_xscale("log").

Similar Topics