Use matplotlib.ticker.MultipleLocator(step) via ax.xaxis.set_major_locator(MultipleLocator(step)) (or ax.yaxis.set_major_locator(...)) to space ticks at fixed numeric intervals, MaxNLocator(nbins=...) to cap the maximum number of evenly spaced ticks automatically, or ax.set_xticks(ticks) / plt.xticks(ticks) when supplying an explicit array of tick positions.
Basic Example
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
x = np.linspace(0, 20, 200)
y = np.sin(x) * 50
fig, ax = plt.subplots(layout="constrained")
ax.plot(x, y)
# 1. Fixed step interval: Place major ticks every 2 units on X, and every 25 units on Y
ax.xaxis.set_major_locator(ticker.MultipleLocator(2))
ax.yaxis.set_major_locator(ticker.MultipleLocator(25))
# 2. Optional minor ticks: Place minor ticks every 0.5 units on X (no labels by default)
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.5))
plt.show()
Key Details & Edge Cases
- Choosing between
MultipleLocator,MaxNLocator, andset_xticks():ticker.MultipleLocator(step): Guarantees ticks fall on exact multiples ofstep(e.g.,0, 5, 10, 15), even when panning or zooming interactively. Avoid setting a tinystepover a huge range (such asMultipleLocator(1)across0..100,000), which generates 100,000 overlapping tick artists and freezes rendering.ticker.MaxNLocator(nbins=6, integer=True): Automatically chooses “nice” round intervals (1, 2, 5, 10) while ensuring at mostnbinsintervals (nbins + 1ticks) appear—ideal when data ranges vary dynamically or when you only want whole-number ticks (integer=True).ax.set_xticks(np.arange(0, 21, 2)): Fast one-liner for static plots when you want exact start/stop bounds, though ticks remain fixed if the user zooms out interactively.
- Adjusting tick frequency on Date / Time (
datetime) axes (matplotlib.dates):- Numeric
MultipleLocatorcounts raw matplotlib float days and can misalign with calendar months or hours. Usematplotlib.dates(mdates) locators instead:import matplotlib.dates as mdates # Place a major tick every 2 weeks on Mondays, or every 6 hours ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO, interval=2)) ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d")) # Alternative intervals: mdates.DayLocator(interval=5), mdates.MonthLocator(interval=3), mdates.HourLocator(interval=6)
- Numeric
- Reducing crowded string/categorical x-axis labels (bar charts or text labels):
- When plotting string categories on the x-axis, every category gets a tick at integer positions
0, 1, 2, .... Thin them cleanly without dropping data points usingMultipleLocator(n)or slicing existing ticks:# Show every 5th categorical label cleanly ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
- When plotting string categories on the x-axis, every category gets a tick at integer positions
- Logarithmic axes (
ax.set_xscale("log")): Switching an axis to"log"resets its locator toLogLocator. To control tick frequency on a log axis, passbase=10andnumticks=6toticker.LogLocator(base=10.0, numticks=6). - Preventing overlapping labels after increasing tick density: When increasing tick frequency, rotate labels via
ax.tick_params(axis="x", labelrotation=45)or reduce font size viaax.tick_params(axis="both", labelsize=9).
Comparison of Tick Frequency Locators in Matplotlib
| Locator / Method | Syntax | Dynamic on Zoom/Pan? | Best Used When |
|---|---|---|---|
ticker.MultipleLocator(step) |
ax.xaxis.set_major_locator(ticker.MultipleLocator(5)) |
Yes | You want ticks at exact fixed intervals (e.g., every 5 units or every 0.25). |
ticker.MaxNLocator(nbins=N) |
ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) |
Yes | Data ranges change dynamically and you want to cap the total number of ticks cleanly. |
ax.set_xticks(ticks) |
ax.set_xticks(np.arange(0, 101, 10)) |
No (fixed array) | Quick static scripts where exact start, end, and step values are known up front. |
mdates Locators |
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2)) |
Yes | Time-series plots requiring calendar-aware intervals (days, weeks, months, hours). |
Minor Ticks (set_minor_locator) |
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(4)) |
Yes | Adding unlabelled subdivision tick marks between major ticks for visual precision. |
You must log in or register to comment.