data visualization
tick labels
matplotlib
plotting
chart customization

Modify tick label text

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Modifying tick label text is a common plotting task when default axis labels are not user-friendly. In Matplotlib, you can either set tick locations and labels directly or use formatter functions for dynamic behavior. The correct choice depends on whether labels are static, derived, or dependent on interactive zoom.

Core Sections

Static Relabeling for Known Tick Positions

If axis positions are fixed, set ticks and labels explicitly. This is simple and easy to understand in reports.

python
1import matplotlib.pyplot as plt
2
3x = [0, 1, 2, 3]
4y = [10, 25, 18, 30]
5
6fig, ax = plt.subplots()
7ax.plot(x, y, marker="o")
8
9ax.set_xticks([0, 1, 2, 3])
10ax.set_xticklabels(["Q1", "Q2", "Q3", "Q4"])
11ax.set_title("Quarterly Sales")
12plt.tight_layout()
13plt.show()

This works well for dashboards with fixed categorical periods.

Use FuncFormatter for Dynamic Labels

For continuous numeric axes, use a formatter function. This keeps labels synchronized with ticks during panning and zooming.

python
1import matplotlib.pyplot as plt
2from matplotlib.ticker import FuncFormatter
3
4x = [1000, 2000, 3000, 4000, 5000]
5y = [3, 4, 6, 7, 9]
6
7fig, ax = plt.subplots()
8ax.plot(x, y)
9
10formatter = FuncFormatter(lambda value, _: f"{value/1000:.0f}k")
11ax.xaxis.set_major_formatter(formatter)
12ax.set_xlabel("Users")
13plt.show()

Formatter-based labels are usually the best long-term approach for numeric scales.

Rotate and Align Labels for Readability

Long labels can overlap. Rotate labels and adjust alignment to keep charts readable.

python
1categories = ["North Region", "South Region", "West Region", "East Region"]
2values = [42, 35, 50, 28]
3
4fig, ax = plt.subplots()
5ax.bar(categories, values)
6plt.setp(ax.get_xticklabels(), rotation=30, ha="right")
7plt.tight_layout()
8plt.show()

Always check export output at final figure size, not only notebook previews.

Format Date Ticks Correctly

For date axes, combine locator and formatter classes instead of manual strings.

python
1import matplotlib.pyplot as plt
2import matplotlib.dates as mdates
3from datetime import datetime, timedelta
4
5dates = [datetime(2026, 1, 1) + timedelta(days=i*7) for i in range(8)]
6values = [10, 12, 11, 14, 13, 15, 16, 18]
7
8fig, ax = plt.subplots()
9ax.plot(dates, values)
10ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=2))
11ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
12plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
13plt.tight_layout()
14plt.show()

This ensures consistent date formatting across scales.

Avoid Mixing Manual Labels with Auto Locators

If you call set_xticklabels without setting matching tick positions, labels can drift or mismatch when plot limits change. Set both positions and labels together, or use formatters.

For reusable plotting utilities, expose tick-label customization as parameters so callers can switch between static and dynamic formatting cleanly.

Build Reusable Formatting Helpers

If many charts in one codebase need the same label style, centralize that formatting in utility functions. This keeps plots visually consistent and prevents minor formatting differences across dashboards.

python
1from matplotlib.ticker import FuncFormatter
2
3def currency_k_formatter():
4    return FuncFormatter(lambda value, _: f"$ {value/1000:.1f}k")
5
6# usage:
7# ax.yaxis.set_major_formatter(currency_k_formatter())

Reusable formatters are also easier to test. You can validate representative values in small unit tests and catch formatting regressions before reports reach users.

When presenting figures to non-technical audiences, label transformations should be documented in chart subtitles so axis meaning stays clear.

Reusable axis formatting conventions also simplify dashboard maintenance.

Consistent labels improve comparability across recurring analytics reports.

Common Pitfalls

  • Setting custom labels without defining matching tick positions.
  • Using static labels on interactive plots where limits can change.
  • Forgetting to rotate long labels and ending up with unreadable overlap.
  • Formatting date ticks as plain strings instead of date-aware formatters.
  • Applying many style changes without tight_layout, causing clipped labels.

Summary

  • Use explicit tick positions and labels for fixed categorical axes.
  • Use formatter functions for dynamic numeric or date axes.
  • Improve readability with rotation and alignment adjustments.
  • Use date locator and formatter pairs for time-series plots.
  • Keep tick logic consistent to avoid label-position mismatches.

Course illustration
Course illustration

All Rights Reserved.