Skip to content

Commit

Permalink
MNT: Refactor from_levels_and_colors()
Browse files Browse the repository at this point in the history
Primary motivation was to remove the N parameter to ListedColormap (in
preparation of its deprecation
matplotlib#28763 (comment)
-2322791660).
That parameter is not needed here because
`len(colors[color_slice]) == n_data_colors)`, otherwise the ValueError
above would have raised.

Hopefully, this is overall more readable.
  • Loading branch information
timhoffm committed Nov 12, 2024
1 parent ca39d41 commit 04707f5
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -3690,23 +3690,19 @@ def from_levels_and_colors(levels, colors, extend='neither'):
color_slice = slice_map[extend]

n_data_colors = len(levels) - 1
n_expected = n_data_colors + color_slice.start - (color_slice.stop or 0)
n_extend_colors = color_slice.start - (color_slice.stop or 0)
n_expected = n_data_colors + n_extend_colors
if len(colors) != n_expected:
raise ValueError(
f'With extend == {extend!r} and {len(levels)} levels, '
f'expected {n_expected} colors, but got {len(colors)}')

cmap = ListedColormap(colors[color_slice], N=n_data_colors)

if extend in ['min', 'both']:
cmap.set_under(colors[0])
else:
cmap.set_under('none')

if extend in ['max', 'both']:
cmap.set_over(colors[-1])
else:
cmap.set_over('none')
f'Expected {n_expected} colors ({n_data_colors} colors for {len(levels)} '
f'levels, and {n_extend_colors} colors for extend == {extend!r}), '
f'but got {len(colors)}')

data_colors = colors[color_slice]
under_color = colors[0] if extend in ['min', 'both'] else 'none'
over_color = colors[-1] if extend in ['max', 'both'] else 'none'
cmap = ListedColormap(data_colors).with_extremes(
under=under_color, over=over_color)

cmap.colorbar_extend = extend

Expand Down

0 comments on commit 04707f5

Please sign in to comment.