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

Skip to content

Commit 7e938fa

Browse files
committed
Merge pull request #6837 from anntzer/fix-integer-normalization
FIX: Normalize(<signed integer array>). closes #6825
1 parent 875e539 commit 7e938fa

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

lib/matplotlib/colors.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -811,8 +811,9 @@ def process_value(value):
811811
if is_scalar:
812812
value = [value]
813813
dtype = np.min_scalar_type(value)
814-
dtype = (np.float32 if dtype.itemsize <= 2
815-
else np.promote_types(dtype, float))
814+
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
815+
# bool_/int8/int16 -> float32; int32/int64 -> float64
816+
dtype = np.promote_types(dtype, np.float32)
816817
result = np.ma.array(value, dtype=dtype, copy=True)
817818
return result, is_scalar
818819

@@ -830,7 +831,9 @@ def __call__(self, value, clip=None):
830831
result, is_scalar = self.process_value(value)
831832

832833
self.autoscale_None(result)
833-
vmin, vmax = self.vmin, self.vmax
834+
# Convert at least to float, without losing precision.
835+
(vmin,), _ = self.process_value(self.vmin)
836+
(vmax,), _ = self.process_value(self.vmax)
834837
if vmin == vmax:
835838
result.fill(0) # Or should it be all masked? Or 0.5?
836839
elif vmin > vmax:
@@ -854,7 +857,8 @@ def __call__(self, value, clip=None):
854857
def inverse(self, value):
855858
if not self.scaled():
856859
raise ValueError("Not invertible until scaled")
857-
vmin, vmax = self.vmin, self.vmax
860+
(vmin,), _ = self.process_value(self.vmin)
861+
(vmax,), _ = self.process_value(self.vmax)
858862

859863
if cbook.iterable(value):
860864
val = ma.asarray(value)

lib/matplotlib/tests/test_colors.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,12 @@ def test_Normalize():
193193
_scalar_tester(norm, vals)
194194
_mask_tester(norm, vals)
195195

196+
# Handle integer input correctly (don't overflow when computing max-min,
197+
# i.e. 127-(-128) here).
198+
vals = np.array([-128, 127], dtype=np.int8)
199+
norm = mcolors.Normalize(vals.min(), vals.max())
200+
assert_array_equal(np.asarray(norm(vals)), [0, 1])
201+
196202
# Don't lose precision on longdoubles (float128 on Linux):
197203
# for array inputs...
198204
vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)

0 commit comments

Comments
 (0)