TExcelTAD
Home › Matplotlib › Ticks & Axis Scales

Ticks & Axis Scales

Ticks are the little marks along an axis, and tick labels are the numbers or words next to them. Matplotlib chooses them automatically, but you'll often want to set them yourself: show every year, format numbers as currency, or switch an axis to a logarithmic scale.

Setting tick positions and labels

ax.set_xticks(positions) chooses where the ticks go; an optional second argument gives the labels:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 200)
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.plot(x, np.sin(x))

ticks = [0, np.pi / 2, np.pi, 3 * np.pi / 2, 2 * np.pi]
ax.set_xticks(ticks, ["0", r"$\pi/2
quot;, r"$\pi
quot;, r"$3\pi/2
quot;, r"$2\pi
quot;]) ax.set_yticks([-1, 0, 1]) ax.grid(alpha=0.3) plt.show() print("x tick labels:", [t.get_text() for t in ax.get_xticklabels()])
x tick labels: ['0', '$\\pi/2
  

, '$\\pi
  

, '$3\\pi/2
  

, '$2\\pi
  

]

Tick locators

For many ticks it's easier to describe a rule than a list. Locators in matplotlib.ticker do exactly that:

Locator Places ticks …
MultipleLocator(5) at every multiple of 5
MaxNLocator(4) at up to 4 "nice" positions
FixedLocator([...]) at the given positions
AutoMinorLocator(4) minor ticks, splitting each major interval in 4
NullLocator() nowhere (no ticks)
python · try it yourself
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, AutoMinorLocator

km = [0, 3, 7, 12, 18, 21, 26, 31, 36, 42]
minutes = [0, 15, 36, 61, 93, 110, 138, 166, 194, 230]

fig, ax = plt.subplots()
ax.plot(km, minutes, marker="o")
ax.xaxis.set_major_locator(MultipleLocator(5))
ax.xaxis.set_minor_locator(AutoMinorLocator(5))   # one minor tick per km
ax.yaxis.set_major_locator(MultipleLocator(30))
ax.set(xlabel="Distance (km)", ylabel="Elapsed time (min)", title="Marathon splits")
ax.grid(which="major", alpha=0.4)
plt.show()

lo, hi = ax.get_xlim()
print("major x ticks:", [int(t) for t in ax.get_xticks() if lo <= t <= hi])
major x ticks: [0, 5, 10, 15, 20, 25, 30, 35, 40]

Tick formatters

Formatters turn tick values into text. The simplest is a format string; FuncFormatter takes any function; PercentFormatter handles percentages:

python · try it yourself
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, PercentFormatter, StrMethodFormatter

products = ["Basic", "Plus", "Pro", "Team"]
revenue = [1_250_000, 3_400_000, 2_100_000, 800_000]
margin = [0.12, 0.31, 0.27, 0.45]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5), layout="constrained")
ax1.bar(products, revenue)
ax1.yaxis.set_major_formatter(FuncFormatter(lambda v, pos: f"${v / 1e6:.1f}M"))
ax1.set_title("Revenue")

ax2.bar(products, margin, color="C2")
ax2.yaxis.set_major_formatter(PercentFormatter(xmax=1))
ax2.set_title("Margin")
plt.show()

fig.canvas.draw()      # tick labels are filled in when the figure is drawn
print("ax1:", [t.get_text() for t in ax1.get_yticklabels()][:4])
print("ax2:", [t.get_text() for t in ax2.get_yticklabels()][:4])
ax1: ['$0.0M', '$0.5M', '$1.0M', '$1.5M']
ax2: ['0.0%', '10.0%', '20.0%', '30.0%']

A FuncFormatter function receives the tick value and its position index and returns a string. A simple alternative is a format string: ax.yaxis.set_major_formatter("{x:,.0f} kg").

Logarithmic scales

When values span several orders of magnitude, a linear axis squashes the small ones flat. A log scale puts equal ratios at equal distances (1, 10, 100, 1000 are evenly spaced):

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

days = np.arange(0, 31)
cases = 5 * 1.25 ** days          # 25 % growth per day

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5), layout="constrained")
ax1.plot(days, cases)
ax1.set_title("Linear scale")
ax2.plot(days, cases)
ax2.set_yscale("log")
ax2.set_title("Log scale")
for ax in (ax1, ax2):
    ax.set_xlabel("Day")
plt.show()

print("y scales:", ax1.get_yscale(), "/", ax2.get_yscale())
print(f"Cases on day 30: {cases[-1]:,.0f}")
y scales: linear / log
Cases on day 30: 4,039

Exponential growth becomes a straight line on a log scale, which makes the growth rate easy to see and compare.

Scale Call Use for
Linear set_yscale("linear") default
Log set_yscale("log"), plt.semilogy(), plt.loglog() positive data across many magnitudes
Symmetric log set_yscale("symlog") data with large positive and negative values
Logit set_yscale("logit") probabilities close to 0 and 1

Log-log plots

If both axes are logarithmic, power laws like y = x^k become straight lines whose slope is k:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.logspace(0, 3, 50)          # 1 to 1000, evenly spaced on a log axis

fig, ax = plt.subplots()
for k in [0.5, 1, 2]:
    ax.loglog(x, x ** k, label=f"$y = x^{{{k}}}
quot;) ax.legend() ax.grid(which="both", alpha=0.3) ax.set_title("Power laws on log-log axes") plt.show() print("first x values:", np.round(x[:3], 3).tolist()) print("x scale:", ax.get_xscale(), "| y scale:", ax.get_yscale())
first x values: [1.0, 1.151, 1.326]
x scale: log | y scale: log

np.logspace(0, 3, 50) produces 50 values from 10⁰ to 10³ spaced evenly in the exponent.

Note: Logarithms are undefined for zero and negative numbers. Matplotlib masks such values on a log axis; use symlog if your data crosses zero.

Test yourself

Which locator puts a tick at every multiple of 10?

  1. MaxNLocator(10)
  2. MultipleLocator(10)
  3. FixedLocator(10)
  4. AutoMinorLocator(10)

On a logarithmic y axis, what does exponential growth look like?

  1. A parabola
  2. A straight line
  3. A flat line
  4. A circle

Which axis scale can handle data that contains negative values and spans many magnitudes?

  1. log
  2. logit
  3. symlog
  4. linear only