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

Skip to content

Automatically create tick formatters for str and callable inputs. #16715

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ per-file-ignores =
examples/misc/svg_filter_line.py: E402
examples/misc/svg_filter_pie.py: E402
examples/misc/table_demo.py: E201
examples/mplot3d/surface3d.py: E402
examples/pie_and_polar_charts/bar_of_pie.py: E402
examples/pie_and_polar_charts/nested_pie.py: E402
examples/pie_and_polar_charts/pie_and_donut_labels.py: E402
Expand Down Expand Up @@ -232,6 +233,8 @@ per-file-ignores =
examples/shapes_and_collections/path_patch.py: E402
examples/shapes_and_collections/quad_bezier.py: E402
examples/shapes_and_collections/scatter.py: E402
examples/showcase/anatomy.py: E402
examples/showcase/bachelors_degrees_by_gender.py: E402
examples/showcase/firefox.py: E501
examples/specialty_plots/anscombe.py: E402
examples/specialty_plots/radar_chart.py: E402
Expand All @@ -251,6 +254,7 @@ per-file-ignores =
examples/subplots_axes_and_figures/two_scales.py: E402
examples/subplots_axes_and_figures/zoom_inset_axes.py: E402
examples/tests/backend_driver_sgskip.py: E402
examples/text_labels_and_annotations/date_index_formatter.py: E402
examples/text_labels_and_annotations/demo_text_rotation_mode.py: E402
examples/text_labels_and_annotations/custom_legends.py: E402
examples/text_labels_and_annotations/fancyarrow_demo.py: E402
Expand All @@ -261,7 +265,11 @@ per-file-ignores =
examples/text_labels_and_annotations/mathtext_asarray.py: E402
examples/text_labels_and_annotations/tex_demo.py: E402
examples/text_labels_and_annotations/watermark_text.py: E402
examples/ticks_and_spines/custom_ticker1.py: E402
examples/ticks_and_spines/date_concise_formatter.py: E402
examples/ticks_and_spines/major_minor_demo.py: E402
examples/ticks_and_spines/tick-formatters.py: E402
examples/ticks_and_spines/tick_labels_from_values.py: E402
examples/user_interfaces/canvasagg.py: E402
examples/user_interfaces/embedding_in_gtk3_panzoom_sgskip.py: E402
examples/user_interfaces/embedding_in_gtk3_sgskip.py: E402
Expand Down
7 changes: 7 additions & 0 deletions doc/users/next_whats_new/2020-03-06-auto-tick-formatters.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Allow tick formatters to be set with str or function inputs
------------------------------------------------------------------------
`~.Axis.set_major_formatter` and `~.Axis.set_minor_formatter`
now accept `str` or function inputs in addition to `~.ticker.Formatter`
instances. For a `str` a `~.ticker.StrMethodFormatter` is automatically
generated and used. For a function a `~.ticker.FuncFormatter` is automatically
generated and used.
23 changes: 21 additions & 2 deletions examples/mplot3d/surface3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib.ticker import LinearLocator
import numpy as np

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
Expand All @@ -31,9 +31,28 @@
# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# A StrMethodFormatter is used automatically
ax.zaxis.set_major_formatter('{x:.02f}')

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()


#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:

import matplotlib
matplotlib.pyplot.subplots
matplotlib.axis.Axis.set_major_formatter
matplotlib.axis.Axis.set_major_locator
matplotlib.ticker.LinearLocator
matplotlib.ticker.StrMethodFormatter
18 changes: 8 additions & 10 deletions examples/pyplots/dollar_ticks.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,22 @@
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Fixing random state for reproducibility
np.random.seed(19680801)

fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))

formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
# Use automatic StrMethodFormatter
ax.yaxis.set_major_formatter('${x:1.2f}')

for tick in ax.yaxis.get_major_ticks():
tick.label1.set_visible(False)
tick.label2.set_visible(True)
tick.label2.set_color('green')
ax.yaxis.set_tick_params(which='major', labelcolor='green',
labelleft=False, labelright=True)

plt.show()


#############################################################################
#
# ------------
Expand All @@ -36,8 +34,8 @@
# in this example:

import matplotlib
matplotlib.ticker
matplotlib.ticker.FormatStrFormatter
matplotlib.pyplot.subplots
matplotlib.axis.Axis.set_major_formatter
matplotlib.axis.Axis.get_major_ticks
matplotlib.axis.Axis.set_tick_params
matplotlib.axis.Tick
matplotlib.ticker.StrMethodFormatter
28 changes: 25 additions & 3 deletions examples/showcase/anatomy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
from matplotlib.ticker import AutoMinorLocator, MultipleLocator

np.random.seed(19680801)

Expand All @@ -24,13 +24,14 @@
def minor_tick(x, pos):
if not x % 1.0:
return ""
return "%.2f" % x
return f"{x:.2f}"

ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))
# FuncFormatter is created and used automatically
ax.xaxis.set_minor_formatter(minor_tick)

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
Expand Down Expand Up @@ -141,3 +142,24 @@ def text(x, y, text):
fontsize=10, ha="right", color='.5')

plt.show()


#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:

import matplotlib
matplotlib.pyplot.figure
matplotlib.axes.Axes.text
matplotlib.axis.Axis.set_minor_formatter
matplotlib.axis.Axis.set_major_locator
matplotlib.axis.Axis.set_minor_locator
matplotlib.patches.Circle
matplotlib.patheffects.withStroke
matplotlib.ticker.FuncFormatter
24 changes: 22 additions & 2 deletions examples/showcase/bachelors_degrees_by_gender.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@
# Set a fixed location and format for ticks.
ax.set_xticks(range(1970, 2011, 10))
ax.set_yticks(range(0, 91, 10))
ax.xaxis.set_major_formatter(plt.FuncFormatter('{:.0f}'.format))
ax.yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}%'.format))
# Use automatic StrMethodFormatter creation
ax.xaxis.set_major_formatter('{x:.0f}')
ax.yaxis.set_major_formatter('{x:.0f}%')

# Provide tick lines across the plot to help your viewers trace along
# the axis ticks. Make sure that the lines are light and small so they
Expand Down Expand Up @@ -113,3 +114,22 @@
# Just change the file extension in this call.
# fig.savefig('percent-bachelors-degrees-women-usa.png', bbox_inches='tight')
plt.show()

#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:

import matplotlib
matplotlib.pyplot.subplots
matplotlib.axes.Axes.text
matplotlib.axis.Axis.set_major_formatter
matplotlib.axis.XAxis.tick_bottom
matplotlib.axis.YAxis.tick_left
matplotlib.artist.Artist.set_visible
matplotlib.ticker.StrMethodFormatter
21 changes: 19 additions & 2 deletions examples/text_labels_and_annotations/date_index_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker

# Load a numpy record array from yahoo csv data with fields date, open, close,
# volume, adj_close from the mpl-data/example directory. The record array
Expand All @@ -36,8 +35,26 @@ def format_date(x, pos=None):


ax2.plot(ind, r.adj_close, 'o-')
ax2.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
# Use automatic FuncFormatter creation
ax2.xaxis.set_major_formatter(format_date)
ax2.set_title("Custom tick formatter")
fig.autofmt_xdate()

plt.show()


#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:

import matplotlib
matplotlib.pyplot.subplots
matplotlib.axis.Axis.set_major_formatter
matplotlib.cbook.get_sample_data
matplotlib.ticker.FuncFormatter
29 changes: 19 additions & 10 deletions examples/ticks_and_spines/custom_ticker1.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,32 @@
In this example a user defined function is used to format the ticks in
millions of dollars on the y axis.
"""
from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
import numpy as np

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


def millions(x, pos):
"""The two args are the value and tick position."""
return '$%1.1fM' % (x * 1e-6)


formatter = FuncFormatter(millions)
return '${:1.1f}M'.format(x*1e-6)

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
plt.bar(x, money)
plt.xticks(x, ('Bill', 'Fred', 'Mary', 'Sue'))
# Use automatic FuncFormatter creation
ax.yaxis.set_major_formatter(millions)
ax.bar(['Bill', 'Fred', 'Mary', 'Sue'], money)
plt.show()

#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:

import matplotlib
matplotlib.pyplot.subplots
matplotlib.axis.Axis.set_major_formatter
matplotlib.ticker.FuncFormatter
38 changes: 31 additions & 7 deletions examples/ticks_and_spines/major_minor_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@
Minor tick labels can be turned on by setting the minor formatter.

`.MultipleLocator` places ticks on multiples of some base.
`.FormatStrFormatter` uses a format string (e.g., ``'%d'`` or ``'%1.2f'`` or
``'%1.1f cm'``) to format the tick labels.
`.StrMethodFormatter` uses a format string (e.g., ``'{x:d}'`` or ``'{x:1.2f}'``
or ``'{x:1.1f} cm'``) to format the tick labels (the variable in the format
string must be ``'x'``). For a `.StrMethodFormatter`, the string can be passed
directly to `.Axis.set_major_formatter` or
`.Axis.set_minor_formatter`. An appropriate `.StrMethodFormatter` will
be created and used automatically.

`.pyplot.grid` changes the grid settings of the major ticks of the y and y axis
together. If you want to control the grid of the minor ticks for a given axis,
Expand All @@ -29,8 +33,7 @@

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)


t = np.arange(0.0, 100.0, 0.1)
Expand All @@ -40,10 +43,11 @@
ax.plot(t, s)

# Make a plot with major ticks that are multiples of 20 and minor ticks that
# are multiples of 5. Label major ticks with '%d' formatting but don't label
# minor ticks.
# are multiples of 5. Label major ticks with '.0f' formatting but don't label
# minor ticks. The string is used directly, the `StrMethodFormatter` is
# created automatically.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_major_formatter('{x:.0f}')

# For the minor ticks, use no labels; default NullFormatter.
ax.xaxis.set_minor_locator(MultipleLocator(5))
Expand Down Expand Up @@ -74,3 +78,23 @@
ax.tick_params(which='minor', length=4, color='r')

plt.show()


#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:

import matplotlib
matplotlib.pyplot.subplots
matplotlib.axis.Axis.set_major_formatter
matplotlib.axis.Axis.set_major_locator
matplotlib.axis.Axis.set_minor_locator
matplotlib.ticker.AutoMinorLocator
matplotlib.ticker.MultipleLocator
matplotlib.ticker.StrMethodFormatter
Loading