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

Skip to content

Commit 05a5db0

Browse files
committed
Cast vmin/vmax to floats before nonsingular-expanding them.
Nonsingular-expansion is fundamentally about adding small floats to separate vmin/vmax so casting to float is normal; this avoids running into plain wrong autoscales with ``` im = imshow([[np.int16(-20000), np.int16(20000)]]) colorbar() print(im.norm.vmin, im.norm.vmax) ``` or ``` im = imshow([[np.int16(-32768), np.int16(0)]]) colorbar() print(im.norm.vmin, im.norm.vmax) ``` (The bug is present as far back as 2.2.0.)
1 parent 58c6698 commit 05a5db0

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

lib/matplotlib/tests/test_colorbar.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,3 +570,14 @@ def test_colorbar_label():
570570

571571
cbar3 = fig.colorbar(im, orientation='horizontal', label='horizontal cbar')
572572
assert cbar3.ax.get_xlabel() == 'horizontal cbar'
573+
574+
575+
@pytest.mark.parametrize("clim", [(-20000, 20000), (-32768, 0)])
576+
def test_colorbar_int(clim):
577+
# Check that we cast to float early enough to not
578+
# overflow ``int16(20000) - int16(-20000)`` or
579+
# run into ``abs(int16(-32768)) == -32768``.
580+
fig, ax = plt.subplots()
581+
im = ax.imshow([[*map(np.int16, clim)]])
582+
fig.colorbar(im)
583+
assert (im.norm.vmin, im.norm.vmax) == clim

lib/matplotlib/transforms.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2791,6 +2791,10 @@ def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
27912791
vmin, vmax = vmax, vmin
27922792
swapped = True
27932793

2794+
# Expand vmin, vmax to float: if they were integer types, they can wrap
2795+
# around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
2796+
vmin, vmax = map(float, [vmin, vmax])
2797+
27942798
maxabsvalue = max(abs(vmin), abs(vmax))
27952799
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
27962800
vmin = -expander

0 commit comments

Comments
 (0)