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

Skip to content

Backport PR #24970 on branch v3.7.x (FIX: Handle uint8 indices properly for colormap lookups) #24977

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
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
21 changes: 11 additions & 10 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,16 +715,17 @@ def __call__(self, X, alpha=None, bytes=False):
if not xa.dtype.isnative:
xa = xa.byteswap().newbyteorder() # Native byteorder is faster.
if xa.dtype.kind == "f":
with np.errstate(invalid="ignore"):
xa *= self.N
# Negative values are out of range, but astype(int) would
# truncate them towards zero.
xa[xa < 0] = -1
# xa == 1 (== N after multiplication) is not out of range.
xa[xa == self.N] = self.N - 1
# Avoid converting large positive values to negative integers.
np.clip(xa, -1, self.N, out=xa)
xa = xa.astype(int)
xa *= self.N
# Negative values are out of range, but astype(int) would
# truncate them towards zero.
xa[xa < 0] = -1
# xa == 1 (== N after multiplication) is not out of range.
xa[xa == self.N] = self.N - 1
# Avoid converting large positive values to negative integers.
np.clip(xa, -1, self.N, out=xa)
with np.errstate(invalid="ignore"):
# We need this cast for unsigned ints as well as floats
xa = xa.astype(int)
# Set the over-range indices before the under-range;
# otherwise the under-range values get converted to over-range.
xa[xa > self.N - 1] = self._i_over
Expand Down
7 changes: 7 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ def test_create_lookup_table(N, result):
assert_array_almost_equal(mcolors._create_lookup_table(N, data), result)


@pytest.mark.parametrize("dtype", [np.uint8, int, np.float16, float])
def test_index_dtype(dtype):
# We use subtraction in the indexing, so need to verify that uint8 works
cm = mpl.colormaps["viridis"]
assert_array_equal(cm(dtype(0)), cm(0))


def test_resampled():
"""
GitHub issue #6025 pointed to incorrect ListedColormap.resampled;
Expand Down