From 5d99e151be80bcb0b3b6d081fd3038330f573d94 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Tue, 28 Jan 2020 22:12:51 -0500 Subject: [PATCH] Backport PR #16344: Cast vmin/vmax to floats before nonsingular-expanding them. --- lib/matplotlib/tests/test_colorbar.py | 11 +++++++++++ lib/matplotlib/transforms.py | 4 ++++ 2 files changed, 15 insertions(+) diff --git a/lib/matplotlib/tests/test_colorbar.py b/lib/matplotlib/tests/test_colorbar.py index 0798e257bbd5..27eaeb159a76 100644 --- a/lib/matplotlib/tests/test_colorbar.py +++ b/lib/matplotlib/tests/test_colorbar.py @@ -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 diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py index e4a37373e9a1..481b7074157b 100644 --- a/lib/matplotlib/transforms.py +++ b/lib/matplotlib/transforms.py @@ -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