import matplotlib.pyplot as plt
= [0, 1e4, 2.3e4, 3.12e4]
y = [2000, 2010, 2020, 2030] x
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
'{x:.1f}')) ax.xaxis.set_major_formatter(StrMethodFormatter(
Ticks in a scientific/engineering notation
from matplotlib.ticker import EngFormatter
='')) # no unit, no distance to the multiplier
ax.xaxis.set_major_formatter(EngFormatter(sep='Hz')) ax.xaxis.set_major_formatter(EngFormatter(unit
Percent formatter that does the scaling too
from matplotlib.ticker import PercentFormatter
= 2.5 # data value corresponding to the 100%
value_100perc =value_100perc)) ax.xaxis.set_major_formatter(PercentFormatter(xmax
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
= lambda x, pos: f'[{x:.2f}]'
custom_formatter 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_string
Now 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
= lambda x, pos: format(int(round(x)), ',d').replace(',',' ')
format_spaces ax.yaxis.set_major_formatter(FuncFormatter(format_spaces))
= plt.subplots()
f, ax ='o')
ax.plot(x,y,marker
from matplotlib.ticker import FuncFormatter
= lambda x, pos: format(int(round(x)), ',d').replace(',',' ')
format_spaces ax.yaxis.set_major_formatter(FuncFormatter(format_spaces))