Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5b4acbc

Browse files
committed
Rewrite Tick formatters example
- Collect all relevant descriptions in the summary text at the top - Merge everything into one figure. The code should be mostly irrelevant for the example. The figure can serve as a standalone reference.
1 parent 5f25d20 commit 5b4acbc

File tree

2 files changed

+49
-51
lines changed

2 files changed

+49
-51
lines changed

galleries/examples/ticks/tick-formatters.py

Lines changed: 47 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,23 @@
88
99
This 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 (this implicitly creates a `.StrMethodFormatter`)
15+
- a function (this 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: autopick the format string.
24+
- `.PercentFormatter`: Format labels as a percentage.
25+
26+
See :ref:`formatters` for a complete list.
27+
1128
"""
1229

1330
import matplotlib.pyplot as plt
@@ -34,79 +51,58 @@ 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.
4554

46-
fig0, axs0 = plt.subplots(2, 1, figsize=(8, 2))
47-
fig0.suptitle('Simple Formatting')
55+
fig = plt.figure(figsize=(8, 8), layout='constrained')
56+
fig0, fig1, fig2 = fig.subfigures(3, height_ratios=[1.5, 1.5, 7.5])
4857

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')
58+
fig0.suptitle('String Formatting', fontsize=16, x=0, ha='left')
59+
ax0 = fig0.subplots()
5460

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))
61+
setup(ax0, title="'{x} km'")
62+
ax0.xaxis.set_major_formatter('{x} km')
6063

61-
fig0.tight_layout()
6264

65+
fig1.suptitle('Function Formatting', fontsize=16, x=0, ha='left')
66+
ax1 = fig1.subplots()
67+
68+
setup(ax1, title="def(x, pos): return str(x-5)")
69+
ax1.xaxis.set_major_formatter(lambda x, pos: str(x-5))
6370

64-
# %%
65-
# The remaining examples use `.Formatter` objects.
6671

67-
fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6))
68-
fig1.suptitle('Formatter Object Formatting')
72+
fig2.suptitle('Formatter Object Formatting', fontsize=16, x=0, ha='left')
73+
axs2 = fig2.subplots(7, 1)
6974

70-
# Null formatter
71-
setup(axs1[0], title="NullFormatter()")
72-
axs1[0].xaxis.set_major_formatter(ticker.NullFormatter())
75+
setup(axs2[0], title="NullFormatter()")
76+
axs2[0].xaxis.set_major_formatter(ticker.NullFormatter())
7377

74-
# StrMethod formatter
75-
setup(axs1[1], title="StrMethodFormatter('{x:.3f}')")
76-
axs1[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))
78+
setup(axs2[1], title="StrMethodFormatter('{x:.3f}')")
79+
axs2[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))
7780

81+
setup(axs2[2], title="FormatStrFormatter('#%d')")
82+
axs2[2].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))
7883

79-
# FuncFormatter can be used as a decorator
80-
@ticker.FuncFormatter
81-
def major_formatter(x, pos):
84+
85+
def fmt_two_digits(x, pos):
8286
return f'[{x:.2f}]'
8387

8488

85-
setup(axs1[2], title='FuncFormatter("[{:.2f}]".format)')
86-
axs1[2].xaxis.set_major_formatter(major_formatter)
89+
setup(axs2[3], title='FuncFormatter("[{:.2f}]".format)')
90+
axs2[3].xaxis.set_major_formatter(ticker.FuncFormatter(fmt_two_digits))
8791

88-
# Fixed formatter
89-
setup(axs1[3], title="FixedFormatter(['A', 'B', 'C', ...])")
92+
setup(axs2[4], title="FixedFormatter(['A', 'B', 'C', 'D', 'E', 'F'])")
9093
# FixedFormatter should only be used together with FixedLocator.
9194
# Otherwise, one cannot be sure where the labels will end up.
9295
positions = [0, 1, 2, 3, 4, 5]
9396
labels = ['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))
97+
axs2[4].xaxis.set_major_locator(ticker.FixedLocator(positions))
98+
axs2[4].xaxis.set_major_formatter(ticker.FixedFormatter(labels))
10099

101-
# FormatStr formatter
102-
setup(axs1[5], title="FormatStrFormatter('#%d')")
103-
axs1[5].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))
100+
setup(axs2[5], title="ScalarFormatter()")
101+
axs2[5].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
104102

105-
# Percent formatter
106-
setup(axs1[6], title="PercentFormatter(xmax=5)")
107-
axs1[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
103+
setup(axs2[6], title="PercentFormatter(xmax=5)")
104+
axs2[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
108105

109-
fig1.tight_layout()
110106
plt.show()
111107

112108

lib/matplotlib/ticker.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@
7777
ax.xaxis.set_major_locator(MultipleLocator(5))
7878
ax2.xaxis.set_major_locator(MultipleLocator(5))
7979
80+
.. _formatters:
81+
8082
Tick formatting
8183
---------------
8284

0 commit comments

Comments
 (0)