@@ -2011,33 +2011,23 @@ def from_levels_and_colors(levels, colors, extend='neither'):
2011
2011
cmap : `~matplotlib.colors.Normalize`
2012
2012
norm : `~matplotlib.colors.Colormap`
2013
2013
"""
2014
- colors_i0 = 0
2015
- colors_i1 = None
2016
-
2017
- if extend == 'both' :
2018
- colors_i0 = 1
2019
- colors_i1 = - 1
2020
- extra_colors = 2
2021
- elif extend == 'min' :
2022
- colors_i0 = 1
2023
- extra_colors = 1
2024
- elif extend == 'max' :
2025
- colors_i1 = - 1
2026
- extra_colors = 1
2027
- elif extend == 'neither' :
2028
- extra_colors = 0
2029
- else :
2030
- raise ValueError ('Unexpected value for extend: {0!r}' .format (extend ))
2014
+ slice_map = {
2015
+ 'both' : slice (1 , - 1 ),
2016
+ 'min' : slice (1 , None ),
2017
+ 'max' : slice (0 , - 1 ),
2018
+ 'neither' : slice (0 , None ),
2019
+ }
2020
+ cbook ._check_in_list (slice_map , extend = extend )
2021
+ color_slice = slice_map [extend ]
2031
2022
2032
2023
n_data_colors = len (levels ) - 1
2033
- n_expected_colors = n_data_colors + extra_colors
2034
- if len (colors ) != n_expected_colors :
2035
- raise ValueError ('With extend == {0!r} and n_levels == {1!r} expected'
2036
- ' n_colors == {2!r}. Got {3!r}.'
2037
- '' .format (extend , len (levels ), n_expected_colors ,
2038
- len (colors )))
2039
-
2040
- cmap = ListedColormap (colors [colors_i0 :colors_i1 ], N = n_data_colors )
2024
+ n_expected = n_data_colors + color_slice .start - (color_slice .stop or 0 )
2025
+ if len (colors ) != n_expected :
2026
+ raise ValueError (
2027
+ f'With extend == { extend !r} and { len (levels )} levels, '
2028
+ f'expected { n_expected } colors, but got { len (colors )} ' )
2029
+
2030
+ cmap = ListedColormap (colors [color_slice ], N = n_data_colors )
2041
2031
2042
2032
if extend in ['min' , 'both' ]:
2043
2033
cmap .set_under (colors [0 ])
0 commit comments