8000 Merge pull request #21542 from vfdev-5/fix-21378 · matplotlib/matplotlib@a3ba7cf · GitHub
[go: up one dir, main page]

Skip to content

Commit a3ba7cf

Browse files
authored
Merge pull request #21542 from vfdev-5/fix-21378
[ENH]: Use new style format strings for colorbar ticks
2 parents d7563cd + c4aae9d commit a3ba7cf

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

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 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)
0