Skip to content

Backport PR #16344 on branch v3.2.x (Cast vmin/vmax to floats before nonsingular-expanding them.) #16364

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/matplotlib/tests/test_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -580,3 +580,14 @@ def test_colorbar_label():

cbar3 = fig.colorbar(im, orientation='horizontal', label='horizontal cbar')
assert cbar3.ax.get_xlabel() == 'horizontal cbar'


@pytest.mark.parametrize("clim", [(-20000, 20000), (-32768, 0)])
def test_colorbar_int(clim):
# Check that we cast to float early enough to not
# overflow ``int16(20000) - int16(-20000)`` or
# run into ``abs(int16(-32768)) == -32768``.
fig, ax = plt.subplots()
im = ax.imshow([[*map(np.int16, clim)]])
fig.colorbar(im)
assert (im.norm.vmin, im.norm.vmax) == clim
4 changes: 4 additions & 0 deletions lib/matplotlib/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2812,6 +2812,10 @@ def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
vmin, vmax = vmax, vmin
swapped = True

# Expand vmin, vmax to float: if they were integer types, they can wrap
# around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
vmin, vmax = map(float, [vmin, vmax])

maxabsvalue = max(abs(vmin), abs(vmax))
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
vmin = -expander
Expand Down