Force integer axis labels on Matplotlib

The last line makes the y-axis have integer-only labels.

import numpy as np
from matplotlib.pyplot import figure, show
from matplotlib.ticker import MaxNLocator

x = np.arange(0.1,10.5,0.1) # arbitrary data

ax = figure().gca()
ax.plot(x)

ax.yaxis.set_major_locator(MaxNLocator(integer=True))

show()

You can do the same for the x-axis as well.

Too few ticks

Noting the Matplotlib MaxNLocator docs, you must have

at least min_n_ticks integers…found within the view limits

You can set MaxNLocator(nbins=5,integer=True) or similar if the defaults aren’t forcing integer ticks.

Leave a Comment