2025, Nov 12 23:00
Set Identical X and Y Ticks and Labels in Matplotlib with a Simple Reusable Helper Function
Learn how to set the same x and y ticks and labels in Matplotlib without duplication. Use a tiny helper to keep plots consistent, DRY, and easy to maintain.
When x and y axes share the exact same ticks and labels, repeating four nearly identical calls in Matplotlib quickly turns into noise. The goal is to keep plots consistent while reducing boilerplate and making the style parameters easy to change in one place.
Example setup that repeats tick configuration
The following snippet shows a small plot where both axes use the same tick positions and the same bold, small-sized labels.
import matplotlib.pyplot as mp
import seaborn as sb
mp.style.use('seaborn-v0_8')
canvas, axes = mp.subplots(figsize=(4, 4))
tick_vals = [0.00, 0.25, 0.50, 0.75, 1.00]
axes.set_xticks(tick_vals)
axes.set_xticklabels(tick_vals, weight='bold', size=8)
axes.set_yticks(tick_vals)
axes.set_yticklabels(tick_vals, weight='bold', size=8)
mp.show()What’s the actual issue
The configuration for x and y is identical, yet it is duplicated in four calls. This is tedious to maintain and easy to desynchronize if you later tweak parameters like weight or size in only one place. The intent is straightforward: set the same ticks and labels on both axes with a single, clear action.
Concise solution
A tiny helper function keeps the behavior the same while consolidating the setup. It accepts the axis object, the tick values, and any text styling through keyword arguments, then applies everything to both axes.
import matplotlib.pyplot as mp
mp.style.use('seaborn-v0_8')
def apply_ticks_and_text(axis_obj, values, **opts):
axis_obj.set_xticks(values)
axis_obj.set_xticklabels(values, **opts)
axis_obj.set_yticks(values)
axis_obj.set_yticklabels(values, **opts)
canvas, axes = mp.subplots(figsize=(4, 4))
tick_vals = [0.00, 0.25, 0.50, 0.75, 1.00]
apply_ticks_and_text(axes, tick_vals, weight='bold', size=8)
mp.show()Why this matters
Encapsulation reduces repetition and helps keep your plotting code tidy. When the labels or styling change, there is exactly one place to update. This improves readability, makes consistent formatting effortless, and lowers the chance of mismatched parameters across axes.
Takeaways
If x and y need the same ticks and labels, centralize the configuration in a small function. Pass the tick positions and label styling once, and let the helper handle both axes. Your plots stay consistent, and your code stays lean and maintainable.