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
9 changes: 8 additions & 1 deletion lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,8 @@ class Colorbar:
ticks : `~matplotlib.ticker.Locator` or array-like of float

format : str or `~matplotlib.ticker.Formatter`
If string, it supports '%' operator and `str.format` formats:
e.g. ``"%4.2e"`` or ``"{x:.2e}"``.

drawedges : bool

Expand Down Expand Up @@ -487,7 +489,12 @@ def __init__(self, ax, mappable=None, *, cmap=None,
self.locator = ticks # Handle default in _ticker()

if isinstance(format, str):
self.formatter = ticker.FormatStrFormatter(format)
# Check format between FormatStrFormatter and StrMethodFormatter
try:
self.formatter = ticker.FormatStrFormatter(format)
_ = self.formatter(0)
except TypeError:
self.formatter = ticker.StrMethodFormatter(format)
else:
self.formatter = format # Assume it is a Formatter or None
self.draw_all()
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/tests/test_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,14 +543,15 @@ def test_colorbar_renorm():
assert np.isclose(cbar.vmax, z.max() * 1000)


def test_colorbar_format():
@pytest.mark.parametrize('fmt', ['%4.2e', '{x:.2e}'])
def test_colorbar_format(fmt):
# make sure that format is passed properly
x, y = np.ogrid[-4:4:31j, -4:4:31j]
z = 120000*np.exp(-x**2 - y**2)

fig, ax = plt.subplots()
im = ax.imshow(z)
cbar = fig.colorbar(im, format='%4.2e')
cbar = fig.colorbar(im, format=fmt)
fig.canvas.draw()
assert cbar.ax.yaxis.get_ticklabels()[4].get_text() == '8.00e+04'

Expand Down