From 782c82a6b2d57af5b3ee9149c1ef89b994af7bd6 Mon Sep 17 00:00:00 2001 From: vfdev-5 Date: Mon, 8 Nov 2021 23:25:24 +0100 Subject: [PATCH 1/2] Reverted the code according to the review and kept the support for both StrMethodFormatter and FormatStrFormatter if format is str --- lib/matplotlib/colorbar.py | 9 ++++++++- lib/matplotlib/tests/test_colorbar.py | 5 +++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 0c3f91503960..d588ed792df6 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 type 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' From c4aae9dbfeb2023430f74e7d3b6d1a6325cb53df Mon Sep 17 00:00:00 2001 From: vfdev-5 Date: Tue, 9 Nov 2021 00:57:05 +0100 Subject: [PATCH 2/2] Fixed flake8 --- lib/matplotlib/colorbar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index d588ed792df6..e812550c46fd 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -489,7 +489,7 @@ def __init__(self, ax, mappable=None, *, cmap=None, self.locator = ticks # Handle default in _ticker() if isinstance(format, str): - # Check format type between FormatStrFormatter and StrMethodFormatter + # Check format between FormatStrFormatter and StrMethodFormatter try: self.formatter = ticker.FormatStrFormatter(format) _ = self.formatter(0)