diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 5c37eef5190b..6c92f3795384 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -404,7 +404,7 @@ def __init__(self, ax, mappable=None, *, cmap=None, try: self._formatter = ticker.FormatStrFormatter(format) _ = self._formatter(0) - except TypeError: + except (TypeError, ValueError): self._formatter = ticker.StrMethodFormatter(format) else: self._formatter = format # Assume it is a Formatter or None diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py index 73c4dab9a87f..0cf098e787ee 100644 --- a/lib/matplotlib/tests/test_colorbar.py +++ b/lib/matplotlib/tests/test_colorbar.py @@ -15,7 +15,7 @@ BoundaryNorm, LogNorm, PowerNorm, Normalize, NoNorm ) from matplotlib.colorbar import Colorbar -from matplotlib.ticker import FixedLocator, LogFormatter +from matplotlib.ticker import FixedLocator, LogFormatter, StrMethodFormatter from matplotlib.testing.decorators import check_figures_equal @@ -1230,3 +1230,9 @@ def test_colorbar_wrong_figure(): fig_tl.colorbar(im) fig_tl.draw_without_rendering() fig_cl.draw_without_rendering() + + +def test_colorbar_format_string_and_old(): + plt.imshow([[0, 1]]) + cb = plt.colorbar(format="{x}%") + assert isinstance(cb._formatter, StrMethodFormatter)