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

Skip to content

Commit 782c82a

Browse files
committed
Reverted the code according to the review and kept the support for
both StrMethodFormatter and FormatStrFormatter if format is str
1 parent c316142 commit 782c82a

2 files changed

Lines changed: 11 additions & 3 deletions

File tree

lib/matplotlib/colorbar.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,8 @@ class Colorbar:
352352
ticks : `~matplotlib.ticker.Locator` or array-like of float
353353
354354
format : str or `~matplotlib.ticker.Formatter`
355+
If string, it supports '%' operator and `str.format` formats:
356+
e.g. ``"%4.2e"`` or ``"{x:.2e}"``.
355357
356358
drawedges : bool
357359
@@ -487,7 +489,12 @@ def __init__(self, ax, mappable=None, *, cmap=None,
487489
self.locator = ticks # Handle default in _ticker()
488490

489491
if isinstance(format, str):
490-
self.formatter = ticker.FormatStrFormatter(format)
492+
# Check format type between FormatStrFormatter and StrMethodFormatter
493+
try:
494+
self.formatter = ticker.FormatStrFormatter(format)
495+
_ = self.formatter(0)
496+
except TypeError:
497+
self.formatter = ticker.StrMethodFormatter(format)
491498
else:
492499
self.formatter = format # Assume it is a Formatter or None
493500
self.draw_all()

lib/matplotlib/tests/test_colorbar.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -543,14 +543,15 @@ def test_colorbar_renorm():
543543
assert np.isclose(cbar.vmax, z.max() * 1000)
544544

545545

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

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

0 commit comments

Comments
 (0)