Skip to content

Commit 6af9a45

Browse files
authored
Merge pull request #29127 from timhoffm/mnt-numcolors
MNT: Refactor matplotlib.colors.from_levels_and_colors()
2 parents 9caa0a6 + 44b9873 commit 6af9a45

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

lib/matplotlib/colors.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -3700,23 +3700,19 @@ def from_levels_and_colors(levels, colors, extend='neither'):
37003700
color_slice = slice_map[extend]
37013701

37023702
n_data_colors = len(levels) - 1
3703-
n_expected = n_data_colors + color_slice.start - (color_slice.stop or 0)
3703+
n_extend_colors = color_slice.start - (color_slice.stop or 0) # 0, 1 or 2
3704+
n_expected = n_data_colors + n_extend_colors
37043705
if len(colors) != n_expected:
37053706
raise ValueError(
3706-
f'With extend == {extend!r} and {len(levels)} levels, '
3707-
f'expected {n_expected} colors, but got {len(colors)}')
3708-
3709-
cmap = ListedColormap(colors[color_slice], N=n_data_colors)
3710-
3711-
if extend in ['min', 'both']:
3712-
cmap.set_under(colors[0])
3713-
else:
3714-
cmap.set_under('none')
3715-
3716-
if extend in ['max', 'both']:
3717-
cmap.set_over(colors[-1])
3718-
else:
3719-
cmap.set_over('none')
3707+
f'Expected {n_expected} colors ({n_data_colors} colors for {len(levels)} '
3708+
f'levels, and {n_extend_colors} colors for extend == {extend!r}), '
3709+
f'but got {len(colors)}')
3710+
3711+
data_colors = colors[color_slice]
3712+
under_color = colors[0] if extend in ['min', 'both'] else 'none'
3713+
over_color = colors[-1] if extend in ['max', 'both'] else 'none'
3714+
cmap = ListedColormap(data_colors).with_extremes(
3715+
under=under_color, over=over_color)
37203716

37213717
cmap.colorbar_extend = extend
37223718

0 commit comments

Comments
 (0)