0
0
Matplotlibdata~5 mins

Custom tick formatters in Matplotlib

Choose your learning style9 modes available
Introduction

Custom tick formatters let you change how numbers or labels appear on graph axes. This helps make charts easier to read and understand.

You want to show dates or times in a special way on the axis.
You need to add units like % or $ to the numbers on the axis.
You want to shorten long numbers, like showing 1000 as 1K.
You want to show only certain ticks with custom labels.
You want to format numbers with fixed decimal places.
Syntax
Matplotlib
from matplotlib.ticker import FuncFormatter

formatter = FuncFormatter(function)
ax.xaxis.set_major_formatter(formatter)

The function you provide takes two inputs: the tick value and its position.

The function should return a string that will be shown on the axis.

Examples
This example formats y-axis ticks as currency with 2 decimals.
Matplotlib
def currency(x, pos):
    return f'${x:.2f}'

formatter = FuncFormatter(currency)
ax.yaxis.set_major_formatter(formatter)
This example formats x-axis ticks as percentages with 1 decimal.
Matplotlib
def percent(x, pos):
    return f'{x*100:.1f}%'

formatter = FuncFormatter(percent)
ax.xaxis.set_major_formatter(formatter)
This example shows numbers in thousands with 'K' suffix.
Matplotlib
def kilo(x, pos):
    return f'{int(x/1000)}K'

formatter = FuncFormatter(kilo)
ax.xaxis.set_major_formatter(formatter)
Sample Program

This program plots sales data over time. The y-axis numbers are shown in thousands with a 'K' suffix using a custom tick formatter.

Matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

# Sample data
x = [0, 1, 2, 3, 4, 5]
y = [1000, 1500, 3000, 4500, 6000, 7500]

fig, ax = plt.subplots()
ax.plot(x, y)

# Custom formatter to show y-axis in thousands with K

def thousands_formatter(x, pos):
    return f'{int(x/1000)}K'

formatter = FuncFormatter(thousands_formatter)
ax.yaxis.set_major_formatter(formatter)

plt.title('Sales over time')
plt.xlabel('Time (months)')
plt.ylabel('Sales')
plt.show()
OutputSuccess
Important Notes

Custom tick formatters help make your charts clearer and more professional.

Remember to import FuncFormatter from matplotlib.ticker.

The formatter function must always return a string.

Summary

Custom tick formatters change how axis labels look.

Use FuncFormatter with a function that returns a string.

This makes charts easier to read and understand.