Automatically create tick formatters for str and callable inputs. by toddrjen · Pull Request #16715 · matplotlib/matplotlib · GitHub
Skip to content
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
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
Comment thread
story645 marked this conversation as resolved.
------------------------------------------------------------------------
`~.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
Comment thread
toddrjen marked this conversation as resolved.
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)
Comment thread
toddrjen marked this conversation as resolved.

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
Loading