diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 0c3f91503960..e812550c46fd 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -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 @@ -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() diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py index 6b691713e7e6..1e9e82974178 100644 --- a/lib/matplotlib/tests/test_colorbar.py +++ b/lib/matplotlib/tests/test_colorbar.py @@ -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'