88
99This example illustrates the usage and effect of the most common formatters.
1010
11+ The tick format is configured via the function `~.Axis.set_major_formatter`
12+ or `~.Axis.set_minor_formatter`. It accepts:
13+
14+ - a format string, which implicitly creates a `.StrMethodFormatter`.
15+ - a function, implicitly creates a `.FuncFormatter`.
16+ - an instance of a `.Formatter` subclass. The most common are
17+
18+ - `.NullFormatter`: No labels on the ticks.
19+ - `.StrMethodFormatter`: Use string `str.format` method.
20+ - `.FormatStrFormatter`: Use %-style formatting.
21+ - `.FuncFormatter`: Define labels through a function.
22+ - `.FixedFormatter`: Set the label strings explicitly.
23+ - `.ScalarFormatter`: Default formatter for scalars: auto-pick the format string.
24+ - `.PercentFormatter`: Format labels as a percentage.
25+
26+ See :ref:`formatters` for a complete list.
27+
1128"""
1229
1330import matplotlib .pyplot as plt
@@ -34,103 +51,55 @@ def setup(ax, title):
3451 fontsize = 14 , fontname = 'Monospace' , color = 'tab:blue' )
3552
3653
37- # %%
38- # Tick formatters can be set in one of two ways, either by passing a ``str``
39- # or function to `~.Axis.set_major_formatter` or `~.Axis.set_minor_formatter`,
40- # or by creating an instance of one of the various `~.ticker.Formatter` classes
41- # and providing that to `~.Axis.set_major_formatter` or
42- # `~.Axis.set_minor_formatter`.
43- #
44- # The first two examples directly pass a ``str`` or function.
54+ fig = plt .figure (figsize = (8 , 8 ), layout = 'constrained' )
55+ fig0 , fig1 , fig2 = fig .subfigures (3 , height_ratios = [1.5 , 1.5 , 7.5 ])
4556
46- fig0 , axs0 = plt . subplots ( 2 , 1 , figsize = ( 8 , 2 ) )
47- fig0 .suptitle ( 'Simple Formatting' )
57+ fig0 . suptitle ( 'String Formatting' , fontsize = 16 , x = 0 , ha = 'left' )
58+ ax0 = fig0 .subplots ( )
4859
49- # A ``str``, using format string function syntax, can be used directly as a
50- # formatter. The variable ``x`` is the tick value and the variable ``pos`` is
51- # tick position. This creates a StrMethodFormatter automatically.
52- setup (axs0 [0 ], title = "'{x} km'" )
53- axs0 [0 ].xaxis .set_major_formatter ('{x} km' )
60+ setup (ax0 , title = "'{x} km'" )
61+ ax0 .xaxis .set_major_formatter ('{x} km' )
5462
55- # A function can also be used directly as a formatter. The function must take
56- # two arguments: ``x`` for the tick value and ``pos`` for the tick position,
57- # and must return a ``str``. This creates a FuncFormatter automatically.
58- setup (axs0 [1 ], title = "lambda x, pos: str(x-5)" )
59- axs0 [1 ].xaxis .set_major_formatter (lambda x , pos : str (x - 5 ))
6063
61- fig0 .tight_layout ()
64+ fig1 .suptitle ('Function Formatting' , fontsize = 16 , x = 0 , ha = 'left' )
65+ ax1 = fig1 .subplots ()
6266
67+ setup (ax1 , title = "def(x, pos): return str(x-5)" )
68+ ax1 .xaxis .set_major_formatter (lambda x , pos : str (x - 5 ))
6369
64- # %%
65- # The remaining examples use `.Formatter` objects.
6670
67- fig1 , axs1 = plt . subplots ( 7 , 1 , figsize = ( 8 , 6 ) )
68- fig1 . suptitle ( 'Formatter Object Formatting' )
71+ fig2 . suptitle ( 'Formatter Object Formatting' , fontsize = 16 , x = 0 , ha = 'left' )
72+ axs2 = fig2 . subplots ( 7 , 1 )
6973
70- # Null formatter
71- setup (axs1 [0 ], title = "NullFormatter()" )
72- axs1 [0 ].xaxis .set_major_formatter (ticker .NullFormatter ())
74+ setup (axs2 [0 ], title = "NullFormatter()" )
75+ axs2 [0 ].xaxis .set_major_formatter (ticker .NullFormatter ())
7376
74- # StrMethod formatter
75- setup (axs1 [1 ], title = "StrMethodFormatter('{x:.3f}')" )
76- axs1 [1 ].xaxis .set_major_formatter (ticker .StrMethodFormatter ("{x:.3f}" ))
77+ setup (axs2 [1 ], title = "StrMethodFormatter('{x:.3f}')" )
78+ axs2 [1 ].xaxis .set_major_formatter (ticker .StrMethodFormatter ("{x:.3f}" ))
7779
80+ setup (axs2 [2 ], title = "FormatStrFormatter('#%d')" )
81+ axs2 [2 ].xaxis .set_major_formatter (ticker .FormatStrFormatter ("#%d" ))
7882
79- # FuncFormatter can be used as a decorator
80- @ticker .FuncFormatter
81- def major_formatter (x , pos ):
83+
84+ def fmt_two_digits (x , pos ):
8285 return f'[{ x :.2f} ]'
8386
8487
85- setup (axs1 [ 2 ], title = 'FuncFormatter("[{:.2f}]".format)' )
86- axs1 [ 2 ].xaxis .set_major_formatter (major_formatter )
88+ setup (axs2 [ 3 ], title = 'FuncFormatter("[{:.2f}]".format)' )
89+ axs2 [ 3 ].xaxis .set_major_formatter (ticker . FuncFormatter ( fmt_two_digits ) )
8790
88- # Fixed formatter
89- setup (axs1 [3 ], title = "FixedFormatter(['A', 'B', 'C', ...])" )
91+ setup (axs2 [4 ], title = "FixedFormatter(['A', 'B', 'C', 'D', 'E', 'F'])" )
9092# FixedFormatter should only be used together with FixedLocator.
9193# Otherwise, one cannot be sure where the labels will end up.
9294positions = [0 , 1 , 2 , 3 , 4 , 5 ]
9395labels = ['A' , 'B' , 'C' , 'D' , 'E' , 'F' ]
94- axs1 [3 ].xaxis .set_major_locator (ticker .FixedLocator (positions ))
95- axs1 [3 ].xaxis .set_major_formatter (ticker .FixedFormatter (labels ))
96-
97- # Scalar formatter
98- setup (axs1 [4 ], title = "ScalarFormatter()" )
99- axs1 [4 ].xaxis .set_major_formatter (ticker .ScalarFormatter (useMathText = True ))
96+ axs2 [4 ].xaxis .set_major_locator (ticker .FixedLocator (positions ))
97+ axs2 [4 ].xaxis .set_major_formatter (ticker .FixedFormatter (labels ))
10098
101- # FormatStr formatter
102- setup (axs1 [5 ], title = "FormatStrFormatter('#%d')" )
103- axs1 [5 ].xaxis .set_major_formatter (ticker .FormatStrFormatter ("#%d" ))
99+ setup (axs2 [5 ], title = "ScalarFormatter()" )
100+ axs2 [5 ].xaxis .set_major_formatter (ticker .ScalarFormatter (useMathText = True ))
104101
105- # Percent formatter
106- setup (axs1 [6 ], title = "PercentFormatter(xmax=5)" )
107- axs1 [6 ].xaxis .set_major_formatter (ticker .PercentFormatter (xmax = 5 ))
102+ setup (axs2 [6 ], title = "PercentFormatter(xmax=5)" )
103+ axs2 [6 ].xaxis .set_major_formatter (ticker .PercentFormatter (xmax = 5 ))
108104
109- fig1 .tight_layout ()
110105plt .show ()
111-
112-
113- # %%
114- #
115- # .. admonition:: References
116- #
117- # The use of the following functions, methods, classes and modules is shown
118- # in this example:
119- #
120- # - `matplotlib.pyplot.subplots`
121- # - `matplotlib.axes.Axes.text`
122- # - `matplotlib.axis.Axis.set_major_formatter`
123- # - `matplotlib.axis.Axis.set_major_locator`
124- # - `matplotlib.axis.Axis.set_minor_locator`
125- # - `matplotlib.axis.XAxis.set_ticks_position`
126- # - `matplotlib.axis.YAxis.set_ticks_position`
127- # - `matplotlib.ticker.FixedFormatter`
128- # - `matplotlib.ticker.FixedLocator`
129- # - `matplotlib.ticker.FormatStrFormatter`
130- # - `matplotlib.ticker.FuncFormatter`
131- # - `matplotlib.ticker.MultipleLocator`
132- # - `matplotlib.ticker.NullFormatter`
133- # - `matplotlib.ticker.NullLocator`
134- # - `matplotlib.ticker.PercentFormatter`
135- # - `matplotlib.ticker.ScalarFormatter`
136- # - `matplotlib.ticker.StrMethodFormatter`
0 commit comments