MCPcopy Index your code
hub / github.com/matplotlib/matplotlib / from_levels_and_colors

Function from_levels_and_colors

lib/matplotlib/colors.py:4224–4273  ·  view source on GitHub ↗

A helper routine to generate a cmap and a norm instance which behave similar to contourf's levels and colors arguments. Parameters ---------- levels : sequence of numbers The quantization levels used to construct the `BoundaryNorm`. Value ``v`` is quantized to l

(levels, colors, extend='neither')

Source from the content-addressed store, hash-verified

4222
4223
4224def from_levels_and_colors(levels, colors, extend='neither'):
4225 """
4226 A helper routine to generate a cmap and a norm instance which
4227 behave similar to contourf's levels and colors arguments.
4228
4229 Parameters
4230 ----------
4231 levels : sequence of numbers
4232 The quantization levels used to construct the `BoundaryNorm`.
4233 Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``.
4234 colors : sequence of colors
4235 The fill color to use for each level. If *extend* is "neither" there
4236 must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add
4237 one extra color, and for an *extend* of "both" add two colors.
4238 extend : {'neither', 'min', 'max', 'both'}, optional
4239 The behaviour when a value falls out of range of the given levels.
4240 See `~.Axes.contourf` for details.
4241
4242 Returns
4243 -------
4244 cmap : `~matplotlib.colors.Colormap`
4245 norm : `~matplotlib.colors.Normalize`
4246 """
4247 slice_map = {
4248 'both': slice(1, -1),
4249 'min': slice(1, None),
4250 'max': slice(0, -1),
4251 'neither': slice(0, None),
4252 }
4253 _api.check_in_list(slice_map, extend=extend)
4254 color_slice = slice_map[extend]
4255
4256 n_data_colors = len(levels) - 1
4257 n_extend_colors = color_slice.start - (color_slice.stop or 0) # 0, 1 or 2
4258 n_expected = n_data_colors + n_extend_colors
4259 if len(colors) != n_expected:
4260 raise ValueError(
4261 f'Expected {n_expected} colors ({n_data_colors} colors for {len(levels)} '
4262 f'levels, and {n_extend_colors} colors for extend == {extend!r}), '
4263 f'but got {len(colors)}')
4264
4265 data_colors = colors[color_slice]
4266 under_color = colors[0] if extend in ['min', 'both'] else 'none'
4267 over_color = colors[-1] if extend in ['max', 'both'] else 'none'
4268 cmap = ListedColormap(data_colors, under=under_color, over=over_color)
4269
4270 cmap.colorbar_extend = extend
4271
4272 norm = BoundaryNorm(levels, ncolors=n_data_colors)
4273 return cmap, norm

Callers

nothing calls this directly

Calls 2

ListedColormapClass · 0.85
BoundaryNormClass · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…