xticks and yticks (Matplotlib)

set_xticks() and set_xticklabels() control where the tick marks sit on an axis and what text labels them. They let you place ticks at chosen positions and replace numbers with custom labels.

Matplotlib

ax.set_xticks([0, 1, 2, 3]) puts tick marks at exactly those positions, and ax.set_xticklabels(['Q1', 'Q2', 'Q3', 'Q4']) swaps the numeric labels for text. A frequent use is rotating crowded labels with the rotation keyword so long category names don't overlap.

In recent Matplotlib you can pass both positions and labels in one call — ax.set_xticks(positions, labels) — which keeps them in sync and avoids the classic bug where labels and tick positions drift apart. The y-axis equivalents are set_yticks and set_yticklabels.

For automatic but smarter tick placement, the locator and formatter objects in matplotlib.ticker (for example formatting an axis as currency or dates) give finer control than setting ticks by hand.

Syntax

ax.set_xticks(positions, labels=None, rotation=0)

Examples

Python

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_xticks([0, 1, 2])
print(ax.get_xticks())

Output:

[0 1 2]

Learn it in a lesson

See also

Back to the Dictionary