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

Skip to content

Commit 9c5ab5e

Browse files
committed
various requested fixes
1 parent 763ef98 commit 9c5ab5e

File tree

11 files changed

+97
-73
lines changed

11 files changed

+97
-73
lines changed

doc/users/next_whats_new/2020-03-06-auto-tick-formatters.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,5 @@ Allow tick formatters to be set with str or function inputs
33
`~.Axis.set_major_formatter` and `~.Axis.set_minor_formatter`
44
now accept `str` or function inputs in addition to `~.ticker.Formatter`
55
instances. For a `str` a `~.ticker.StrMethodFormatter` is automatically
6-
created and used. For a function a `~.ticker.FuncFormatter` is automatically
7-
created and used.
6+
generated and used. For a function a `~.ticker.FuncFormatter` is automatically
7+
generated and used.

examples/mplot3d/surface3d.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,5 @@
5454
matplotlib.pyplot.subplots
5555
matplotlib.axis.Axis.set_major_formatter
5656
matplotlib.axis.Axis.set_major_locator
57+
matplotlib.ticker.LinearLocator
5758
matplotlib.ticker.StrMethodFormatter

examples/pyplots/dollar_ticks.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,8 @@
1717
# Use automatic StrMethodFormatter
1818
ax.yaxis.set_major_formatter('${x:1.2f}')
1919

20-
for tick in ax.yaxis.get_major_ticks():
21-
tick.label1.set_visible(False)
22-
tick.label2.set_visible(True)
23-
tick.label2.set_color('green')
20+
ax.yaxis.set_tick_params(which='major', labelcolor='green',
21+
labelleft=False, labelright=True)
2422

2523
plt.show()
2624

@@ -38,6 +36,6 @@
3836
import matplotlib
3937
matplotlib.pyplot.subplots
4038
matplotlib.axis.Axis.set_major_formatter
41-
matplotlib.axis.Axis.get_major_ticks
39+
matplotlib.axis.Axis.set_tick_params
4240
matplotlib.axis.Tick
4341
matplotlib.ticker.StrMethodFormatter

examples/ticks_and_spines/custom_ticker1.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@
1212
millions of dollars on the y axis.
1313
"""
1414
import matplotlib.pyplot as plt
15-
import numpy as np
1615

17-
x = np.arange(4)
1816
money = [1.5e5, 2.5e6, 5.5e6, 2.0e7]
1917

2018

@@ -25,8 +23,7 @@ def millions(x, pos):
2523
fig, ax = plt.subplots()
2624
# Use automatic FuncFormatter creation
2725
ax.yaxis.set_major_formatter(millions)
28-
ax.bar(x, money)
29-
ax.set_xticks(x, ('Bill', 'Fred', 'Mary', 'Sue'))
26+
ax.bar(['Bill', 'Fred', 'Mary', 'Sue'], money)
3027
plt.show()
3128

3229
#############################################################################

examples/ticks_and_spines/tick-formatters.py

Lines changed: 39 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -34,59 +34,76 @@ def setup(ax, title):
3434
fontsize=14, fontname='Monospace', color='tab:blue')
3535

3636

37-
fig, axs = plt.subplots(9, 1, figsize=(8, 8))
37+
# Tick formatters can be set in one of two ways, either by passing a ``str``
38+
# or function to `~.Axis.set_major_formatter` or `~.Axis.set_minor_formatter`,
39+
# or by creating an instance of one of the various `~.ticker.Formatter` classes
40+
# and providing that to `~.Axis.set_major_formatter` or
41+
# `~.Axis.set_minor_formatter`.
3842

39-
# A string, using format string function syntax, can be used directly as a
43+
# The first two examples directly pass a ``str`` or function.
44+
45+
fig0, axs0 = plt.subplots(2, 1, figsize=(8, 2))
46+
fig0.suptitle('Simple Formatting')
47+
48+
# A ``str``, using format string function syntax, can be used directly as a
4049
# formatter. The variable ``x`` is the tick value and the variable ``pos`` is
4150
# tick position. This creates a StrMethodFormatter automatically.
42-
setup(axs[0], title="'{x} km'")
43-
axs[0].xaxis.set_major_formatter('{x} km')
51+
setup(axs0[0], title="'{x} km'")
52+
axs0[0].xaxis.set_major_formatter('{x} km')
4453

4554
# A function can also be used directly as a formatter. The function must take
4655
# two arguments: ``x`` for the tick value and ``pos`` for the tick position,
4756
# and must return a ``str`` This creates a FuncFormatter automatically.
48-
setup(axs[1], title="lambda x, pos: str(x-5)")
49-
axs[1].xaxis.set_major_formatter(lambda x, pos: str(x-5))
57+
setup(axs0[1], title="lambda x, pos: str(x-5)")
58+
axs0[1].xaxis.set_major_formatter(lambda x, pos: str(x-5))
59+
60+
fig0.tight_layout()
61+
62+
63+
# The remaining examples use Formatter objects.
64+
65+
fig1, axs1 = plt.subplots(7, 1, figsize=(8, 6))
66+
fig1.suptitle('Formatter Object Formatting')
5067

5168
# Null formatter
52-
setup(axs[2], title="NullFormatter()")
53-
axs[2].xaxis.set_major_formatter(ticker.NullFormatter())
69+
setup(axs1[0], title="NullFormatter()")
70+
axs1[0].xaxis.set_major_formatter(ticker.NullFormatter())
5471

5572
# StrMethod formatter
56-
setup(axs[3], title="StrMethodFormatter('{x:.3f}')")
57-
axs[3].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))
73+
setup(axs1[1], title="StrMethodFormatter('{x:.3f}')")
74+
axs1[1].xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.3f}"))
5875

5976
# FuncFormatter can be used as a decorator
6077
@ticker.FuncFormatter
6178
def major_formatter(x, pos):
6279
return f'[{x:.2f}]'
6380

6481

65-
setup(axs[4], title='FuncFormatter("[{:.2f}]".format')
66-
axs[4].xaxis.set_major_formatter(major_formatter)
82+
setup(axs1[2], title='FuncFormatter("[{:.2f}]".format')
83+
axs1[2].xaxis.set_major_formatter(major_formatter)
6784

6885
# Fixed formatter
69-
setup(axs[5], title="FixedFormatter(['A', 'B', 'C', ...])")
86+
setup(axs1[3], title="FixedFormatter(['A', 'B', 'C', ...])")
7087
# FixedFormatter should only be used together with FixedLocator.
7188
# Otherwise, one cannot be sure where the labels will end up.
7289
positions = [0, 1, 2, 3, 4, 5]
7390
labels = ['A', 'B', 'C', 'D', 'E', 'F']
74-
axs[5].xaxis.set_major_locator(ticker.FixedLocator(positions))
75-
axs[5].xaxis.set_major_formatter(ticker.FixedFormatter(labels))
91+
axs1[3].xaxis.set_major_locator(ticker.FixedLocator(positions))
92+
axs1[3].xaxis.set_major_formatter(ticker.FixedFormatter(labels))
7693

7794
# Scalar formatter
78-
setup(axs[6], title="ScalarFormatter()")
79-
axs[6].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
95+
setup(axs1[4], title="ScalarFormatter()")
96+
axs1[4].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
8097

8198
# FormatStr formatter
82-
setup(axs[7], title="FormatStrFormatter('#%d')")
83-
axs[7].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))
99+
setup(axs1[5], title="FormatStrFormatter('#%d')")
100+
axs1[5].xaxis.set_major_formatter(ticker.FormatStrFormatter("#%d"))
84101

85102
# Percent formatter
86-
setup(axs[8], title="PercentFormatter(xmax=5)")
87-
axs[8].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
103+
setup(axs1[6], title="PercentFormatter(xmax=5)")
104+
axs1[6].xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
88105

89-
fig.tight_layout()
106+
fig1.tight_layout()
90107
plt.show()
91108

92109

lib/matplotlib/axis.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1530,8 +1530,8 @@ def set_major_formatter(self, formatter):
15301530
See the `~matplotlib.ticker.StrMethodFormatter` documentation for
15311531
more information.
15321532
1533-
For a function a `~matplotlib.ticker.FuncFormatter` is used.
1534-
The function should take in two inputs (a tick value ``x`` and a
1533+
For a function, a `~matplotlib.ticker.FuncFormatter` is used.
1534+
The function must take two inputs (a tick value ``x`` and a
15351535
position ``pos``), and return a string containing the corresponding
15361536
tick label.
15371537
See the `~matplotlib.ticker.FuncFormatter` documentation for

lib/matplotlib/tests/test_axes.py

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,25 +204,46 @@ def test_formatter_ticker():
204204
ax.autoscale_view()
205205

206206

207-
def test_auto_formatter():
207+
def test_funcformatter_auto_formatter():
208208
def _formfunc(x, pos):
209209
return ''
210210

211-
formstr = '{x}_{pos}'
212-
213211
ax = plt.figure().subplots()
212+
213+
assert ax.xaxis.isDefault_majfmt == True
214+
assert ax.xaxis.isDefault_minfmt == True
215+
214216
ax.xaxis.set_major_formatter(_formfunc)
215-
ax.yaxis.set_minor_formatter(formstr)
217+
218+
assert ax.xaxis.isDefault_majfmt == False
219+
assert ax.xaxis.isDefault_minfmt == True
216220

217221
targ_funcformatter = mticker.FuncFormatter(_formfunc)
218-
targ_strformatter = mticker.StrMethodFormatter(formstr)
219222

220223
assert isinstance(ax.xaxis.get_major_formatter(),
221224
mticker.FuncFormatter)
225+
226+
assert ax.xaxis.get_major_formatter().func == targ_funcformatter.func
227+
228+
229+
def test_strmethodformatter_auto_formatter():
230+
formstr = '{x}_{pos}'
231+
232+
ax = plt.figure().subplots()
233+
234+
assert ax.yaxis.isDefault_majfmt == True
235+
assert ax.yaxis.isDefault_minfmt == True
236+
237+
ax.yaxis.set_minor_formatter(formstr)
238+
239+
assert ax.yaxis.isDefault_majfmt == True
240+
assert ax.yaxis.isDefault_minfmt == False
241+
242+
targ_strformatter = mticker.StrMethodFormatter(formstr)
243+
222244
assert isinstance(ax.yaxis.get_minor_formatter(),
223245
mticker.StrMethodFormatter)
224246

225-
assert ax.xaxis.get_major_formatter().func == targ_funcformatter.func
226247
assert ax.yaxis.get_minor_formatter().fmt == targ_strformatter.fmt
227248

228249

lib/matplotlib/ticker.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -159,11 +159,11 @@
159159
ax.yaxis.set_major_formatter(ymajor_formatter)
160160
ax.yaxis.set_minor_formatter(yminor_formatter)
161161
162-
In addition to `.Formatter`, `~.Axis.set_major_formatter` and
163-
`~.Axis.set_minor_formatter` also accept a ``str`` or function. In the case of
164-
a ``str``, a `.StrMethodFormatter` will be automatically created and applied
165-
based on the given ``str``. Similarly, for a function a `.FuncFormatter` will
166-
be automatically created and applied using the given function.
162+
In addition to a `.Formatter` instance, `~.Axis.set_major_formatter` and
163+
`~.Axis.set_minor_formatter` also accept a ``str`` or function. ``str`` input
164+
will be internally replaced with an autogenerated `.StrMethodFormatter` with
165+
the input ``str``. For function input, a `.FuncFormatter` with the input
166+
function will be generated and used.
167167
168168
See :doc:`/gallery/ticks_and_spines/major_minor_demo` for an
169169
example of setting major and minor ticks. See the :mod:`matplotlib.dates`

tutorials/intermediate/artists.py

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -650,19 +650,9 @@ class in the matplotlib API, and the one you will be working with most
650650
# ============== ==========================================================
651651
#
652652
# Here is an example which sets the formatter for the right side ticks with
653-
# dollar signs and colors them green on the right side of the yaxis
654-
655-
# Fixing random state for reproducibility
656-
np.random.seed(19680801)
657-
658-
fig, ax = plt.subplots()
659-
ax.plot(100*np.random.rand(20))
660-
661-
ax.yaxis.set_major_formatter('${x:1.2f}')
662-
663-
for tick in ax.yaxis.get_major_ticks():
664-
tick.label1.set_visible(False)
665-
tick.label2.set_visible(True)
666-
tick.label2.set_color('green')
667-
668-
plt.show()
653+
# dollar signs and colors them green on the right side of the yaxis.
654+
#
655+
#
656+
# .. include:: ../../gallery/pyplots/dollar_ticks.rst
657+
# :start-after: y axis labels.
658+
# :end-before: -------

tutorials/introductory/lifecycle.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
66
This tutorial aims to show the beginning, middle, and end of a single
77
visualization using Matplotlib. We'll begin with some raw data and
8-
end by saving a figure of a customized visualization. Along the way we'll try
8+
end by saving a figure of a customized visualization. Along the way we try
99
to highlight some neat features and best-practices using Matplotlib.
1010
1111
.. currentmodule:: matplotlib
@@ -74,7 +74,7 @@
7474
# ===============
7575
#
7676
# This data is naturally visualized as a barplot, with one bar per
77-
# group. To do this with the object-oriented approach, we'll first generate
77+
# group. To do this with the object-oriented approach, we first generate
7878
# an instance of :class:`figure.Figure` and
7979
# :class:`axes.Axes`. The Figure is like a canvas, and the Axes
8080
# is a part of that canvas on which we will make a particular visualization.
@@ -143,7 +143,7 @@
143143
###############################################################################
144144
# It looks like this cut off some of the labels on the bottom. We can
145145
# tell Matplotlib to automatically make room for elements in the figures
146-
# that we create. To do this we'll set the ``autolayout`` value of our
146+
# that we create. To do this we set the ``autolayout`` value of our
147147
# rcParams. For more information on controlling the style, layout, and
148148
# other features of plots with rcParams, see
149149
# :doc:`/tutorials/introductory/customizing`.
@@ -156,7 +156,7 @@
156156
plt.setp(labels, rotation=45, horizontalalignment='right')
157157

158158
###############################################################################
159-
# Next, we'll add labels to the plot. To do this with the OO interface,
159+
# Next, we add labels to the plot. To do this with the OO interface,
160160
# we can use the :meth:`axes.Axes.set` method to set properties of this
161161
# Axes object.
162162

@@ -187,7 +187,7 @@
187187

188188
###############################################################################
189189
# For labels, we can specify custom formatting guidelines in the form of
190-
# functions. Below we'll define a function that takes an integer as input, and
190+
# functions. Below we define a function that takes an integer as input, and
191191
# returns a string as an output. When used with `.Axis.set_major_formatter` or
192192
# `.Axis.set_minor_formatter`, they will automatically create and use a
193193
# :class:`ticker.FuncFormatter` class.
@@ -207,7 +207,7 @@ def currency(x, pos):
207207

208208
###############################################################################
209209
# We can then apply this function to the labels on our plot. To do this,
210-
# we'll use the ``xaxis`` attribute of our axis. This lets you perform
210+
# we use the ``xaxis`` attribute of our axis. This lets you perform
211211
# actions on a specific axis on our plot.
212212

213213
fig, ax = plt.subplots(figsize=(6, 8))
@@ -240,7 +240,7 @@ def currency(x, pos):
240240
ax.text(145000, group, "New Company", fontsize=10,
241241
verticalalignment="center")
242242

243-
# Now we'll move our title up since it's getting a little cramped
243+
# Now we move our title up since it's getting a little cramped
244244
ax.title.set(y=1.05)
245245

246246
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
@@ -263,7 +263,7 @@ def currency(x, pos):
263263

264264
###############################################################################
265265
# We can then use the :meth:`figure.Figure.savefig` in order to save the figure
266-
# to disk. Note that there are several useful flags we'll show below:
266+
# to disk. Note that there are several useful flags we show below:
267267
#
268268
# * ``transparent=True`` makes the background of the saved figure transparent
269269
# if the format supports it.

tutorials/text/text_intro.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -286,8 +286,8 @@
286286
# used `matplotlib.ticker.StrMethodFormatter` (new-style ``str.format()``
287287
# format string) or `matplotlib.ticker.FormatStrFormatter` (old-style '%'
288288
# format string) and passed it to the ``ax.xaxis``. A
289-
# `matplotlib.ticker.StrMethodFormatter` can also be created by simply
290-
# passing a ``str`` without having to explicitly create the formatter.
289+
# `matplotlib.ticker.StrMethodFormatter` can also be created by passing a
290+
# ``str`` without having to explicitly create the formatter.
291291

292292
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
293293
axs[0].plot(x1, y1)
@@ -350,7 +350,7 @@
350350
##############################################################################
351351
# Finally, we can specify functions for the formatter using
352352
# `matplotlib.ticker.FuncFormatter`. Further, like
353-
# `matplotlib.ticker.StrMethodFormatter`, simply passing a function will
353+
# `matplotlib.ticker.StrMethodFormatter`, passing a function will
354354
# automatically create a `matplotlib.ticker.FuncFormatter`.
355355

356356

0 commit comments

Comments
 (0)