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

Skip to content

Commit 84d979b

Browse files
authored
Merge pull request #6837 from anntzer/fix-integer-normalization
FIX: Normalize(<signed integer array>). closes #6825
2 parents 0cfc7a8 + ac0c85a commit 84d979b

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
@@ -884,8 +884,9 @@ def process_value(value):
884884
if is_scalar:
885885
value = [value]
886886
dtype = np.min_scalar_type(value)
887-
dtype = (np.float32 if dtype.itemsize <= 2
888-
else np.promote_types(dtype, float))
887+
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
888+
# bool_/int8/int16 -> float32; int32/int64 -> float64
889+
dtype = np.promote_types(dtype, np.float32)
889890
result = np.ma.array(value, dtype=dtype, copy=True)
890891
return result, is_scalar
891892

@@ -903,7 +904,9 @@ def __call__(self, value, clip=None):
903904
result, is_scalar = self.process_value(value)
904905

905906
self.autoscale_None(result)
906-
vmin, vmax = self.vmin, self.vmax
907+
# Convert at least to float, without losing precision.
908+
(vmin,), _ = self.process_value(self.vmin)
909+
(vmax,), _ = self.process_value(self.vmax)
907910
if vmin == vmax:
908911
result.fill(0) # Or should it be all masked? Or 0.5?
909912
elif vmin > vmax:
@@ -927,7 +930,8 @@ def __call__(self, value, clip=None):
927930
def inverse(self, value):
928931
if not self.scaled():
929932
raise ValueError("Not invertible until scaled")
930-
vmin, vmax = self.vmin, self.vmax
933+
(vmin,), _ = self.process_value(self.vmin)
934+
(vmax,), _ = self.process_value(self.vmax)
931935

932936
if cbook.iterable(value):
933937
val = np.ma.asarray(value)

lib/matplotlib/tests/test_colors.py

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

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

0 commit comments

Comments
 (0)