import matplotlib.pyplot as plt
y = [0, 1e4, 2.3e4, 3.12e4]
x = [2000, 2010, 2020, 2030]mpl gallery about ticks
mpl ticker API
Default tick formatter
from matplotlib.ticker import ScalarFormatter
ax.xaxis.set_major_formatter(ScalarFormatter()) Format string as usually
from matplotlib.ticker import StrMethodFormatter
ax.xaxis.set_major_formatter(StrMethodFormatter('{x:.1f}')) Ticks in a scientific/engineering notation
from matplotlib.ticker import EngFormatter
ax.xaxis.set_major_formatter(EngFormatter(sep='')) # no unit, no distance to the multiplier
ax.xaxis.set_major_formatter(EngFormatter(unit='Hz')) Percent formatter that does the scaling too
from matplotlib.ticker import PercentFormatter
value_100perc = 2.5 # data value corresponding to the 100%
ax.xaxis.set_major_formatter(PercentFormatter(xmax=value_100perc)) Lambda formatter (func formatter)
Option 1:
from matplotlib import ticker
@ticker.FuncFormatter
def custom_formatter(x, pos):
return f'[{x:.2f}]'
ax.xaxis.set_major_formatter(custom_formatter)Option 2:
from matplotlib.ticker import FuncFormatter
custom_formatter = lambda x, pos: f'[{x:.2f}]'
ax.xaxis.set_major_formatter(FuncFormatter(custom_formatter))Space as a separator between thousands
Use the FuncFormatter, which requires a function of a form:
def my_func(x,pos):
# blablabla
return formatted_x_stringNow implement the formatter. We want every 3 digits separated by a space, and our labels to be integers (won’t work for floats). We will use format(), which accepts parameter ,d producing comma-separated notation, and replace the commas with spaces.
The formatter can be applied to each axis separately.
from matplotlib.ticker import FuncFormatter
format_spaces = lambda x, pos: format(int(round(x)), ',d').replace(',',' ')
ax.yaxis.set_major_formatter(FuncFormatter(format_spaces))f, ax = plt.subplots()
ax.plot(x,y,marker='o')
from matplotlib.ticker import FuncFormatter
format_spaces = lambda x, pos: format(int(round(x)), ',d').replace(',',' ')
ax.yaxis.set_major_formatter(FuncFormatter(format_spaces))