Debian Codegraph @

pyvista/plotting/colors.py

raw
1 """Color module supporting plotting module.
2
3 Used code from matplotlib.colors. Thanks for your work.
4 """
5
6 # Necessary for autodoc_type_aliases to recognize the type aliases used in the signatures
7 # of methods defined in this module.
8 from __future__ import annotations
9
10 from colorsys import rgb_to_hls
11 import contextlib
12 import importlib
13 import inspect
14 from typing import TYPE_CHECKING
15 from typing import Any
16 from typing import Literal
17 from typing import get_args
18
19 from cycler import Cycler
20 from cycler import cycler
21 from matplotlib.colors import ListedColormap
22 import matplotlib.pyplot as plt
23 import numpy as np
24
25 import pyvista as pv
26 from pyvista import _validation
27 from pyvista import _vtk
28 from pyvista._deprecate_positional_args import _deprecate_positional_args
29 from pyvista._warn_external import warn_external
30 from pyvista.core.errors import PyVistaDeprecationWarning
31 from pyvista.core.utilities.misc import _NoNewAttrMixin
32
33 try:
34 from matplotlib import colormaps
35 from matplotlib import colors
36 except ImportError: # pragma: no cover
37 # typing for newer versions of matplotlib
38 # in newer versions cm is a module
39 from matplotlib import cm as colormaps # type: ignore[assignment]
40 from matplotlib import colors
41
42 if TYPE_CHECKING:
43 from ._typing import ColorLike
44 from ._typing import ColormapOptions
45
46 IPYGANY_MAP = {
47 'reds': 'Reds',
48 'spectral': 'Spectral',
49 }
50
51 _ALLOWED_COLOR_NAME_DELIMITERS = '_' + '-' + ' '
52 _REMOVE_DELIMITER_LOOKUP = str.maketrans('', '', _ALLOWED_COLOR_NAME_DELIMITERS)
53
54
55 def _format_color_name(name: str):
56 """Format name as lower-case and remove delimiters."""
57 return name.lower().translate(_REMOVE_DELIMITER_LOOKUP)
58
59
60 def _format_color_dict(colors: dict[str, str]):
61 """Format name and hex value."""
62 return {_format_color_name(n): h.lower() for n, h in colors.items()}
63
64
65 # Colors from the CSS standard. Matches matplotlib.colors.CSS4_COLORS
66 # but with synonyms removed
67 _CSS_COLORS = {
68 'alice_blue': '#f0f8ff',
69 'antique_white': '#faebd7',
70 'aquamarine': '#7fffd4',
71 'azure': '#f0ffff',
72 'beige': '#f5f5dc',
73 'bisque': '#ffe4c4',
74 'black': '#000000',
75 'blanched_almond': '#ffebcd',
76 'blue': '#0000ff',
77 'blue_violet': '#8a2be2',
78 'brown': '#a52a2a',
79 'burly_wood': '#deb887',
80 'cadet_blue': '#5f9ea0',
81 'chartreuse': '#7fff00',
82 'chocolate': '#d2691e',
83 'coral': '#ff7f50',
84 'cornflower_blue': '#6495ed',
85 'corn_silk': '#fff8dc',
86 'crimson': '#dc143c',
87 'cyan': '#00ffff',
88 'dark_blue': '#00008b',
89 'dark_cyan': '#008b8b',
90 'dark_goldenrod': '#b8860b',
91 'dark_gray': '#a9a9a9',
92 'dark_green': '#006400',
93 'dark_khaki': '#bdb76b',
94 'dark_magenta': '#8b008b',
95 'dark_olive_green': '#556b2f',
96 'dark_orange': '#ff8c00',
97 'dark_orchid': '#9932cc',
98 'dark_red': '#8b0000',
99 'dark_salmon': '#e9967a',
100 'dark_sea_green': '#8fbc8f',
101 'dark_slate_blue': '#483d8b',
102 'dark_slate_gray': '#2f4f4f',
103 'dark_turquoise': '#00ced1',
104 'dark_violet': '#9400d3',
105 'deep_pink': '#ff1493',
106 'deep_sky_blue': '#00bfff',
107 'dim_gray': '#696969',
108 'dodger_blue': '#1e90ff',
109 'fire_brick': '#b22222',
110 'floral_white': '#fffaf0',
111 'forest_green': '#228b22',
112 'gainsboro': '#dcdcdc',
113 'ghost_white': '#f8f8ff',
114 'gold': '#ffd700',
115 'goldenrod': '#daa520',
116 'gray': '#808080',
117 'green': '#008000',
118 'green_yellow': '#adff2f',
119 'honeydew': '#f0fff0',
120 'hot_pink': '#ff69b4',
121 'indian_red': '#cd5c5c',
122 'indigo': '#4b0082',
123 'ivory': '#fffff0',
124 'khaki': '#f0e68c',
125 'lavender': '#e6e6fa',
126 'lavender_blush': '#fff0f5',
127 'lawn_green': '#7cfc00',
128 'lemon_chiffon': '#fffacd',
129 'light_blue': '#add8e6',
130 'light_coral': '#f08080',
131 'light_cyan': '#e0ffff',
132 'light_goldenrod_yellow': '#fafad2',
133 'light_gray': '#d3d3d3',
134 'light_green': '#90ee90',
135 'light_pink': '#ffb6c1',
136 'light_salmon': '#ffa07a',
137 'light_sea_green': '#20b2aa',
138 'light_sky_blue': '#87cefa',
139 'light_slate_gray': '#778899',
140 'light_steel_blue': '#b0c4de',
141 'light_yellow': '#ffffe0',
142 'lime': '#00ff00',
143 'lime_green': '#32cd32',
144 'linen': '#faf0e6',
145 'magenta': '#ff00ff',
146 'maroon': '#800000',
147 'medium_aquamarine': '#66cdaa',
148 'medium_blue': '#0000cd',
149 'medium_orchid': '#ba55d3',
150 'medium_purple': '#9370db',
151 'medium_sea_green': '#3cb371',
152 'medium_slate_blue': '#7b68ee',
153 'medium_spring_green': '#00fa9a',
154 'medium_turquoise': '#48d1cc',
155 'medium_violet_red': '#c71585',
156 'midnight_blue': '#191970',
157 'mint_cream': '#f5fffa',
158 'misty_rose': '#ffe4e1',
159 'moccasin': '#ffe4b5',
160 'navajo_white': '#ffdead',
161 'navy': '#000080',
162 'old_lace': '#fdf5e6',
163 'olive': '#808000',
164 'olive_drab': '#6b8e23',
165 'orange': '#ffa500',
166 'orange_red': '#ff4500',
167 'orchid': '#da70d6',
168 'pale_goldenrod': '#eee8aa',
169 'pale_green': '#98fb98',
170 'pale_turquoise': '#afeeee',
171 'pale_violet_red': '#db7093',
172 'papaya_whip': '#ffefd5',
173 'peach_puff': '#ffdab9',
174 'peru': '#cd853f',
175 'pink': '#ffc0cb',
176 'plum': '#dda0dd',
177 'powder_blue': '#b0e0e6',
178 'purple': '#800080',
179 'rebecca_purple': '#663399',
180 'red': '#ff0000',
181 'rosy_brown': '#bc8f8f',
182 'royal_blue': '#4169e1',
183 'saddle_brown': '#8b4513',
184 'salmon': '#fa8072',
185 'sandy_brown': '#f4a460',
186 'sea_green': '#2e8b57',
187 'seashell': '#fff5ee',
188 'sienna': '#a0522d',
189 'silver': '#c0c0c0',
190 'sky_blue': '#87ceeb',
191 'slate_blue': '#6a5acd',
192 'slate_gray': '#708090',
193 'snow': '#fffafa',
194 'spring_green': '#00ff7f',
195 'steel_blue': '#4682b4',
196 'tan': '#d2b48c',
197 'teal': '#008080',
198 'thistle': '#d8bfd8',
199 'tomato': '#ff6347',
200 'turquoise': '#40e0d0',
201 'violet': '#ee82ee',
202 'wheat': '#f5deb3',
203 'white': '#ffffff',
204 'white_smoke': '#f5f5f5',
205 'yellow': '#ffff00',
206 'yellow_green': '#9acd32',
207 }
208
209 # Tableau colors. Matches matplotlib.colors.TABLEAU_COLORS
210 _TABLEAU_COLORS = {
211 'tab:blue': '#1f77b4',
212 'tab:orange': '#ff7f0e',
213 'tab:green': '#2ca02c',
214 'tab:red': '#d62728',
215 'tab:purple': '#9467bd',
216 'tab:brown': '#8c564b',
217 'tab:pink': '#e377c2',
218 'tab:gray': '#7f7f7f',
219 'tab:olive': '#bcbd22',
220 'tab:cyan': '#17becf',
221 }
222 _PARAVIEW_COLORS = {
223 'paraview_background': '#54596d',
224 'paraview_background_warm': '#625d5a',
225 }
226
227 # Colors from https://htmlpreview.github.io/?https://github.com/Kitware/vtk-examples/blob/gh-pages/VTKNamedColorPatches.html
228 # The vtk colors are only partially supported:
229 # - VTK colors with the same name as CSS colors but different values are excluded
230 # (i.e. the CSS colors take precedent)
231 # - Not all VTK synonyms are supported.
232 # - Colors with adjective suffixes are renamed to use a prefix instead
233 # (e.g. 'green_pale' is renamed to 'pale_green'). This is done to keep VTK color
234 # names consistent with CSS names. In most cases this altered color name is
235 # supported directly by vtkNamedColors, but in some cases this technically is no
236 # longer a valid named vtk color. See tests.
237 _VTK_COLORS = {
238 'alizarin_crimson': '#e32636',
239 'aureoline_yellow': '#ffa824',
240 'banana': '#e3cf57',
241 'brick': '#9c661f',
242 'brown_madder': '#db2929',
243 'brown_ochre': '#87421f',
244 'burnt_sienna': '#8a360f',
245 'burnt_umber': '#8a3324',
246 'cadmium_lemon': '#ffe303',
247 'cadmium_orange': '#ff6103',
248 'cadmium_yellow': '#ff9912',
249 'carrot': '#ed9121',
250 'cerulean': '#05b8cc',
251 'chrome_oxide_green': '#668014',
252 'cinnabar_green': '#61b329',
253 'cobalt': '#3d59ab',
254 'cobalt_green': '#3d9140',
255 'cold_grey': '#808a87',
256 'deep_cadmium_red': '#e3170d',
257 'deep_cobalt_violet': '#91219e',
258 'deep_naples_yellow': '#ffa812',
259 'deep_ochre': '#733d1a',
260 'eggshell': '#fce6c9',
261 'emerald_green': '#00c957',
262 'english_red': '#d43d1a',
263 'flesh': '#ff7d40',
264 'flesh_ochre': '#ff5721',
265 'geranium_lake': '#e31230',
266 'gold_ochre': '#c77826',
267 'greenish_umber': '#ff3d0d',
268 'ivory_black': '#292421',
269 'lamp_black': '#2e473b',
270 'light_cadmium_red': '#ff030d',
271 'light_cadmium_yellow': '#ffb00f',
272 'light_slate_blue': '#8470ff',
273 'light_viridian': '#6eff70',
274 'madder_lake_deep': '#e32e30',
275 'manganese_blue': '#03a89e',
276 'mars_orange': '#964514',
277 'mars_yellow': '#e3701a',
278 'melon': '#e3a869',
279 'mint': '#bdfcc9',
280 'peacock': '#33a1c9',
281 'permanent_green': '#0ac92b',
282 'permanent_red_violet': '#db2645',
283 'raspberry': '#872657',
284 'raw_sienna': '#c76114',
285 'raw_umber': '#734a12',
286 'rose_madder': '#e33638',
287 'sap_green': '#308014',
288 'sepia': '#5e2612',
289 'terre_verte': '#385e0f',
290 'titanium_white': '#fcfff0',
291 'turquoise_blue': '#00c78c',
292 'ultramarine': '#120a8f',
293 'ultramarine_violet': '#5c246e',
294 'van_dyke_brown': '#5e2605',
295 'venetian_red': '#d41a1f',
296 'violet_red': '#d02090',
297 'warm_grey': '#808069',
298 'yellow_ochre': '#e38217',
299 'zinc_white': '#fcf7ff',
300 }
301
302 hex_colors = _CSS_COLORS | _PARAVIEW_COLORS | _TABLEAU_COLORS | _VTK_COLORS
303 _formatted_hex_colors = _format_color_dict(hex_colors)
304
305
306 def _get_deprecated_hexcolors():
307 msg = (
308 "'hexcolors' is deprecated; use 'hex_colors' instead. "
309 'The color names in `hex_colors` are delimited with `_`.'
310 )
311 warn_external(msg, PyVistaDeprecationWarning)
312 if pv.version_info >= (0, 51): # pragma: no cover
313 msg = 'Convert this deprecation warning into an error.'
314 raise RuntimeError(msg)
315 if pv.version_info >= (0, 52): # pragma: no cover
316 msg = 'Remove hexcolors.'
317 raise RuntimeError(msg)
318 return _formatted_hex_colors
319
320
321 def __getattr__(name: str):
322 if name == 'hexcolors':
323 return _get_deprecated_hexcolors()
324 if pv.version_info >= (0, 52): # pragma: no cover
325 msg = 'Remove colors.__getattr__.'
326 raise RuntimeError(msg)
327 msg = f'module {__name__!r} has no attribute {name!r}'
328 raise AttributeError(msg)
329
330
331 color_names = {h: n for n, h in hex_colors.items()}
332
333 color_char_to_word = {
334 'b': 'blue',
335 'g': 'green',
336 'r': 'red',
337 'c': 'cyan',
338 'm': 'magenta',
339 'y': 'yellow',
340 'k': 'black',
341 'w': 'white',
342 }
343
344 color_synonyms = {
345 **color_char_to_word,
346 'aqua': 'cyan',
347 'dark_grey': 'dark_gray',
348 'dark_slate_grey': 'dark_slate_gray',
349 'dim_grey': 'dimgray',
350 'fuchsia': 'magenta',
351 'grey': 'gray',
352 'light_grey': 'light_gray',
353 'light_slate_grey': 'light_slate_gray',
354 'pv': 'paraview_background',
355 'paraview': 'paraview_background',
356 'paraview_warm': 'paraview_background_warm',
357 'slate_grey': 'slate_gray',
358 'light_goldenrod': 'light_goldenrod_yellow',
359 }
360
361 _formatted_color_synonyms = {
362 _format_color_name(syn): _format_color_name(name) for syn, name in color_synonyms.items()
363 }
364
365
366 _ALL_COLORS_LITERAL = Literal[
367 # CSS colors
368 'alice_blue',
369 'antique_white',
370 'aquamarine',
371 'azure',
372 'beige',
373 'bisque',
374 'black',
375 'blanched_almond',
376 'blue',
377 'blue_violet',
378 'brown',
379 'burly_wood',
380 'cadet_blue',
381 'chartreuse',
382 'chocolate',
383 'coral',
384 'cornflower_blue',
385 'corn_silk',
386 'crimson',
387 'cyan',
388 'dark_blue',
389 'dark_cyan',
390 'dark_goldenrod',
391 'dark_gray',
392 'dark_green',
393 'dark_khaki',
394 'dark_magenta',
395 'dark_olive_green',
396 'dark_orange',
397 'dark_orchid',
398 'dark_red',
399 'dark_salmon',
400 'dark_sea_green',
401 'dark_slate_blue',
402 'dark_slate_gray',
403 'dark_turquoise',
404 'dark_violet',
405 'deep_pink',
406 'deep_sky_blue',
407 'dim_gray',
408 'dodger_blue',
409 'fire_brick',
410 'floral_white',
411 'forest_green',
412 'gainsboro',
413 'ghost_white',
414 'gold',
415 'goldenrod',
416 'gray',
417 'green',
418 'green_yellow',
419 'honeydew',
420 'hot_pink',
421 'indian_red',
422 'indigo',
423 'ivory',
424 'khaki',
425 'lavender',
426 'lavender_blush',
427 'lawn_green',
428 'lemon_chiffon',
429 'light_blue',
430 'light_coral',
431 'light_cyan',
432 'light_goldenrod_yellow',
433 'light_gray',
434 'light_green',
435 'light_pink',
436 'light_salmon',
437 'light_sea_green',
438 'light_sky_blue',
439 'light_slate_gray',
440 'light_steel_blue',
441 'light_yellow',
442 'lime',
443 'lime_green',
444 'linen',
445 'magenta',
446 'maroon',
447 'medium_aquamarine',
448 'medium_blue',
449 'medium_orchid',
450 'medium_purple',
451 'medium_sea_green',
452 'medium_slate_blue',
453 'medium_spring_green',
454 'medium_turquoise',
455 'medium_violet_red',
456 'midnight_blue',
457 'mint_cream',
458 'misty_rose',
459 'moccasin',
460 'navajo_white',
461 'navy',
462 'old_lace',
463 'olive',
464 'olive_drab',
465 'orange',
466 'orange_red',
467 'orchid',
468 'pale_goldenrod',
469 'pale_green',
470 'pale_turquoise',
471 'pale_violet_red',
472 'papaya_whip',
473 'peach_puff',
474 'peru',
475 'pink',
476 'plum',
477 'powder_blue',
478 'purple',
479 'rebecca_purple',
480 'red',
481 'rosy_brown',
482 'royal_blue',
483 'saddle_brown',
484 'salmon',
485 'sandy_brown',
486 'sea_green',
487 'seashell',
488 'sienna',
489 'silver',
490 'sky_blue',
491 'slate_blue',
492 'slate_gray',
493 'snow',
494 'spring_green',
495 'steel_blue',
496 'tan',
497 'teal',
498 'thistle',
499 'tomato',
500 'turquoise',
501 'violet',
502 'wheat',
503 'white',
504 'white_smoke',
505 'yellow',
506 'yellow_green',
507 # Tableau colors
508 'tab:blue',
509 'tab:orange',
510 'tab:green',
511 'tab:red',
512 'tab:purple',
513 'tab:brown',
514 'tab:pink',
515 'tab:gray',
516 'tab:olive',
517 'tab:cyan',
518 # ParaView colors
519 'paraview_background',
520 'paraview_background_warm',
521 # VTK colors
522 'alizarin_crimson',
523 'aureoline_yellow',
524 'banana',
525 'brick',
526 'brown_madder',
527 'brown_ochre',
528 'burnt_sienna',
529 'burnt_umber',
530 'cadmium_lemon',
531 'cadmium_orange',
532 'cadmium_yellow',
533 'carrot',
534 'cerulean',
535 'chrome_oxide_green',
536 'cinnabar_green',
537 'cobalt',
538 'cobalt_green',
539 'cold_grey',
540 'deep_cadmium_red',
541 'deep_cobalt_violet',
542 'deep_naples_yellow',
543 'deep_ochre',
544 'eggshell',
545 'emerald_green',
546 'english_red',
547 'flesh',
548 'flesh_ochre',
549 'geranium_lake',
550 'gold_ochre',
551 'greenish_umber',
552 'ivory_black',
553 'lamp_black',
554 'light_cadmium_red',
555 'light_cadmium_yellow',
556 'light_slate_blue',
557 'light_viridian',
558 'madder_lake_deep',
559 'manganese_blue',
560 'mars_orange',
561 'mars_yellow',
562 'melon',
563 'mint',
564 'peacock',
565 'permanent_green',
566 'permanent_red_violet',
567 'raspberry',
568 'raw_sienna',
569 'raw_umber',
570 'rose_madder',
571 'sap_green',
572 'sepia',
573 'terre_verte',
574 'titanium_white',
575 'turquoise_blue',
576 'ultramarine',
577 'ultramarine_violet',
578 'van_dyke_brown',
579 'venetian_red',
580 'violet_red',
581 'warm_grey',
582 'yellow_ochre',
583 'zinc_white',
584 ]
585
586 matplotlib_default_colors = list(_TABLEAU_COLORS.values())
587
588 COLOR_SCHEMES = {
589 'spectrum': {
590 'id': _vtk.vtkColorSeries.SPECTRUM,
591 'descr': 'black, red, blue, green, purple, orange, brown',
592 },
593 'warm': {'id': _vtk.vtkColorSeries.WARM, 'descr': 'dark red → yellow'},
594 'cool': {'id': _vtk.vtkColorSeries.COOL, 'descr': 'green → blue → purple'},
595 'blues': {'id': _vtk.vtkColorSeries.BLUES, 'descr': 'Different shades of blue'},
596 'wild_flower': {
597 'id': _vtk.vtkColorSeries.WILD_FLOWER,
598 'descr': 'blue → purple → pink',
599 },
600 'citrus': {'id': _vtk.vtkColorSeries.CITRUS, 'descr': 'green → yellow → orange'},
601 'div_purple_orange11': {
602 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_11,
603 'descr': 'dark brown → white → dark purple',
604 },
605 'div_purple_orange10': {
606 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_10,
607 'descr': 'dark brown → white → dark purple',
608 },
609 'div_purple_orange9': {
610 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_9,
611 'descr': 'brown → white → purple',
612 },
613 'div_purple_orange8': {
614 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_8,
615 'descr': 'brown → white → purple',
616 },
617 'div_purple_orange7': {
618 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_7,
619 'descr': 'brown → white → purple',
620 },
621 'div_purple_orange6': {
622 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_6,
623 'descr': 'brown → white → purple',
624 },
625 'div_purple_orange5': {
626 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_5,
627 'descr': 'orange → white → purple',
628 },
629 'div_purple_orange4': {
630 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_4,
631 'descr': 'orange → white → purple',
632 },
633 'div_purple_orange3': {
634 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_3,
635 'descr': 'orange → white → purple',
636 },
637 'div_spectral11': {
638 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_11,
639 'descr': 'dark red → light yellow → dark blue',
640 },
641 'div_spectral10': {
642 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_10,
643 'descr': 'dark red → light yellow → dark blue',
644 },
645 'div_spectral9': {
646 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_9,
647 'descr': 'red → light yellow → blue',
648 },
649 'div_spectral8': {
650 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_8,
651 'descr': 'red → light yellow → blue',
652 },
653 'div_spectral7': {
654 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_7,
655 'descr': 'red → light yellow → blue',
656 },
657 'div_spectral6': {
658 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_6,
659 'descr': 'red → light yellow → blue',
660 },
661 'div_spectral5': {
662 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_5,
663 'descr': 'red → light yellow → blue',
664 },
665 'div_spectral4': {
666 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_4,
667 'descr': 'red → light yellow → blue',
668 },
669 'div_spectral3': {
670 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_3,
671 'descr': 'orange → light yellow → green',
672 },
673 'div_brown_blue_green11': {
674 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_11,
675 'descr': 'dark brown → white → dark blue-green',
676 },
677 'div_brown_blue_green10': {
678 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_10,
679 'descr': 'dark brown → white → dark blue-green',
680 },
681 'div_brown_blue_green9': {
682 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_9,
683 'descr': 'brown → white → blue-green',
684 },
685 'div_brown_blue_green8': {
686 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_8,
687 'descr': 'brown → white → blue-green',
688 },
689 'div_brown_blue_green7': {
690 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_7,
691 'descr': 'brown → white → blue-green',
692 },
693 'div_brown_blue_green6': {
694 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_6,
695 'descr': 'brown → white → blue-green',
696 },
697 'div_brown_blue_green5': {
698 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_5,
699 'descr': 'brown → white → blue-green',
700 },
701 'div_brown_blue_green4': {
702 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_4,
703 'descr': 'brown → white → blue-green',
704 },
705 'div_brown_blue_green3': {
706 'id': _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_3,
707 'descr': 'brown → white → blue-green',
708 },
709 'seq_blue_green9': {
710 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_9,
711 'descr': 'light blue → dark green',
712 },
713 'seq_blue_green8': {
714 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_8,
715 'descr': 'light blue → dark green',
716 },
717 'seq_blue_green7': {
718 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_7,
719 'descr': 'light blue → dark green',
720 },
721 'seq_blue_green6': {
722 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_6,
723 'descr': 'light blue → green',
724 },
725 'seq_blue_green5': {
726 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_5,
727 'descr': 'light blue → green',
728 },
729 'seq_blue_green4': {
730 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_4,
731 'descr': 'light blue → green',
732 },
733 'seq_blue_green3': {
734 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_3,
735 'descr': 'light blue → green',
736 },
737 'seq_yellow_orange_brown9': {
738 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_9,
739 'descr': 'light yellow → orange → dark brown',
740 },
741 'seq_yellow_orange_brown8': {
742 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_8,
743 'descr': 'light yellow → orange → brown',
744 },
745 'seq_yellow_orange_brown7': {
746 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_7,
747 'descr': 'light yellow → orange → brown',
748 },
749 'seq_yellow_orange_brown6': {
750 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_6,
751 'descr': 'light yellow → orange → brown',
752 },
753 'seq_yellow_orange_brown5': {
754 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_5,
755 'descr': 'light yellow → orange → brown',
756 },
757 'seq_yellow_orange_brown4': {
758 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_4,
759 'descr': 'light yellow → orange',
760 },
761 'seq_yellow_orange_brown3': {
762 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_3,
763 'descr': 'light yellow → orange',
764 },
765 'seq_blue_purple9': {
766 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_9,
767 'descr': 'light blue → dark purple',
768 },
769 'seq_blue_purple8': {
770 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_8,
771 'descr': 'light blue → purple',
772 },
773 'seq_blue_purple7': {
774 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_7,
775 'descr': 'light blue → purple',
776 },
777 'seq_blue_purple6': {
778 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_6,
779 'descr': 'light blue → purple',
780 },
781 'seq_blue_purple5': {
782 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_5,
783 'descr': 'light blue → purple',
784 },
785 'seq_blue_purple4': {
786 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_4,
787 'descr': 'light blue → purple',
788 },
789 'seq_blue_purple3': {
790 'id': _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_3,
791 'descr': 'light blue → purple',
792 },
793 'qual_accent': {
794 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_ACCENT,
795 'descr': 'pastel green, pastel purple, pastel orange, pastel yellow, blue, pink, '
796 'brown, gray',
797 },
798 'qual_dark2': {
799 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_DARK2,
800 'descr': 'darker shade of qual_set2',
801 },
802 'qual_set3': {
803 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET3,
804 'descr': 'pastel colors: blue green, light yellow, dark purple, red, blue, orange, green, '
805 'pink, gray, purple, light green, yellow',
806 },
807 'qual_set2': {
808 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET2,
809 'descr': 'blue green, orange, purple, pink, green, yellow, brown, gray',
810 },
811 'qual_set1': {
812 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET1,
813 'descr': 'red, blue, green, purple, orange, yellow, brown, pink, gray',
814 },
815 'qual_pastel2': {
816 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_PASTEL2,
817 'descr': 'pastel shade of qual_set2',
818 },
819 'qual_pastel1': {
820 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_PASTEL1,
821 'descr': 'pastel shade of qual_set1',
822 },
823 'qual_paired': {
824 'id': _vtk.vtkColorSeries.BREWER_QUALITATIVE_PAIRED,
825 'descr': 'light blue, blue, light green, green, light red, red, light orange, orange, '
826 'light purple, purple, light yellow',
827 },
828 'custom': {'id': _vtk.vtkColorSeries.CUSTOM, 'descr': None},
829 }
830
831 SCHEME_NAMES = {
832 scheme_info['id']: scheme_name # type: ignore[index]
833 for scheme_name, scheme_info in COLOR_SCHEMES.items()
834 }
835
836 # Define colormaps that require colorcet
837 # matches set(colorcet.cm.keys()) - set(mpl.colormaps)
838 _COLORCET_CMAPS_LITERAL = Literal[
839 'CET_C1',
840 'CET_C10',
841 'CET_C10_r',
842 'CET_C10s',
843 'CET_C10s_r',
844 'CET_C11',
845 'CET_C11_r',
846 'CET_C11s',
847 'CET_C11s_r',
848 'CET_C1_r',
849 'CET_C1s',
850 'CET_C1s_r',
851 'CET_C2',
852 'CET_C2_r',
853 'CET_C2s',
854 'CET_C2s_r',
855 'CET_C3',
856 'CET_C3_r',
857 'CET_C3s',
858 'CET_C3s_r',
859 'CET_C4',
860 'CET_C4_r',
861 'CET_C4s',
862 'CET_C4s_r',
863 'CET_C5',
864 'CET_C5_r',
865 'CET_C5s',
866 'CET_C5s_r',
867 'CET_C6',
868 'CET_C6_r',
869 'CET_C6s',
870 'CET_C6s_r',
871 'CET_C7',
872 'CET_C7_r',
873 'CET_C7s',
874 'CET_C7s_r',
875 'CET_C8',
876 'CET_C8_r',
877 'CET_C8s',
878 'CET_C8s_r',
879 'CET_C9',
880 'CET_C9_r',
881 'CET_C9s',
882 'CET_C9s_r',
883 'CET_CBC1',
884 'CET_CBC1_r',
885 'CET_CBC2',
886 'CET_CBC2_r',
887 'CET_CBD1',
888 'CET_CBD1_r',
889 'CET_CBD2',
890 'CET_CBD2_r',
891 'CET_CBL1',
892 'CET_CBL1_r',
893 'CET_CBL2',
894 'CET_CBL2_r',
895 'CET_CBL3',
896 'CET_CBL3_r',
897 'CET_CBL4',
898 'CET_CBL4_r',
899 'CET_CBTC1',
900 'CET_CBTC1_r',
901 'CET_CBTC2',
902 'CET_CBTC2_r',
903 'CET_CBTD1',
904 'CET_CBTD1_r',
905 'CET_CBTL1',
906 'CET_CBTL1_r',
907 'CET_CBTL2',
908 'CET_CBTL2_r',
909 'CET_CBTL3',
910 'CET_CBTL3_r',
911 'CET_CBTL4',
912 'CET_CBTL4_r',
913 'CET_D1',
914 'CET_D10',
915 'CET_D10_r',
916 'CET_D11',
917 'CET_D11_r',
918 'CET_D12',
919 'CET_D12_r',
920 'CET_D13',
921 'CET_D13_r',
922 'CET_D1A',
923 'CET_D1A_r',
924 'CET_D1_r',
925 'CET_D2',
926 'CET_D2_r',
927 'CET_D3',
928 'CET_D3_r',
929 'CET_D4',
930 'CET_D4_r',
931 'CET_D6',
932 'CET_D6_r',
933 'CET_D7',
934 'CET_D7_r',
935 'CET_D8',
936 'CET_D8_r',
937 'CET_D9',
938 'CET_D9_r',
939 'CET_I1',
940 'CET_I1_r',
941 'CET_I2',
942 'CET_I2_r',
943 'CET_I3',
944 'CET_I3_r',
945 'CET_L1',
946 'CET_L10',
947 'CET_L10_r',
948 'CET_L11',
949 'CET_L11_r',
950 'CET_L12',
951 'CET_L12_r',
952 'CET_L13',
953 'CET_L13_r',
954 'CET_L14',
955 'CET_L14_r',
956 'CET_L15',
957 'CET_L15_r',
958 'CET_L16',
959 'CET_L16_r',
960 'CET_L17',
961 'CET_L17_r',
962 'CET_L18',
963 'CET_L18_r',
964 'CET_L19',
965 'CET_L19_r',
966 'CET_L1_r',
967 'CET_L2',
968 'CET_L20',
969 'CET_L20_r',
970 'CET_L2_r',
971 'CET_L3',
972 'CET_L3_r',
973 'CET_L4',
974 'CET_L4_r',
975 'CET_L5',
976 'CET_L5_r',
977 'CET_L6',
978 'CET_L6_r',
979 'CET_L7',
980 'CET_L7_r',
981 'CET_L8',
982 'CET_L8_r',
983 'CET_L9',
984 'CET_L9_r',
985 'CET_R1',
986 'CET_R1_r',
987 'CET_R2',
988 'CET_R2_r',
989 'CET_R3',
990 'CET_R3_r',
991 'CET_R4',
992 'CET_R4_r',
993 'bgy',
994 'bgy_r',
995 'bgyw',
996 'bgyw_r',
997 'bjy',
998 'bjy_r',
999 'bkr',
1000 'bkr_r',
1001 'bky',
1002 'bky_r',
1003 'blues',
1004 'blues_r',
1005 'bmw',
1006 'bmw_r',
1007 'bmy',
1008 'bmy_r',
1009 'bwy',
1010 'bwy_r',
1011 'circle_mgbm_67_c31',
1012 'circle_mgbm_67_c31_r',
1013 'circle_mgbm_67_c31_s25',
1014 'circle_mgbm_67_c31_s25_r',
1015 'colorwheel',
1016 'colorwheel_r',
1017 'cwr',
1018 'cwr_r',
1019 'cyclic_bgrmb_35_70_c75',
1020 'cyclic_bgrmb_35_70_c75_r',
1021 'cyclic_bgrmb_35_70_c75_s25',
1022 'cyclic_bgrmb_35_70_c75_s25_r',
1023 'cyclic_grey_15_85_c0',
1024 'cyclic_grey_15_85_c0_r',
1025 'cyclic_grey_15_85_c0_s25',
1026 'cyclic_grey_15_85_c0_s25_r',
1027 'cyclic_isoluminant',
1028 'cyclic_isoluminant_r',
1029 'cyclic_mrybm_35_75_c68',
1030 'cyclic_mrybm_35_75_c68_r',
1031 'cyclic_mrybm_35_75_c68_s25',
1032 'cyclic_mrybm_35_75_c68_s25_r',
1033 'cyclic_mybm_20_100_c48',
1034 'cyclic_mybm_20_100_c48_r',
1035 'cyclic_mybm_20_100_c48_s25',
1036 'cyclic_mybm_20_100_c48_s25_r',
1037 'cyclic_mygbm_30_95_c78',
1038 'cyclic_mygbm_30_95_c78_r',
1039 'cyclic_mygbm_30_95_c78_s25',
1040 'cyclic_mygbm_30_95_c78_s25_r',
1041 'cyclic_mygbm_50_90_c46',
1042 'cyclic_mygbm_50_90_c46_r',
1043 'cyclic_mygbm_50_90_c46_s25',
1044 'cyclic_mygbm_50_90_c46_s25_r',
1045 'cyclic_protanopic_deuteranopic_bwyk_16_96_c31',
1046 'cyclic_protanopic_deuteranopic_bwyk_16_96_c31_r',
1047 'cyclic_protanopic_deuteranopic_wywb_55_96_c33',
1048 'cyclic_protanopic_deuteranopic_wywb_55_96_c33_r',
1049 'cyclic_rygcbmr_50_90_c64',
1050 'cyclic_rygcbmr_50_90_c64_r',
1051 'cyclic_rygcbmr_50_90_c64_s25',
1052 'cyclic_rygcbmr_50_90_c64_s25_r',
1053 'cyclic_tritanopic_cwrk_40_100_c20',
1054 'cyclic_tritanopic_cwrk_40_100_c20_r',
1055 'cyclic_tritanopic_wrwc_70_100_c20',
1056 'cyclic_tritanopic_wrwc_70_100_c20_r',
1057 'cyclic_wrkbw_10_90_c43',
1058 'cyclic_wrkbw_10_90_c43_r',
1059 'cyclic_wrkbw_10_90_c43_s25',
1060 'cyclic_wrkbw_10_90_c43_s25_r',
1061 'cyclic_wrwbw_40_90_c42',
1062 'cyclic_wrwbw_40_90_c42_r',
1063 'cyclic_wrwbw_40_90_c42_s25',
1064 'cyclic_wrwbw_40_90_c42_s25_r',
1065 'cyclic_ymcgy_60_90_c67',
1066 'cyclic_ymcgy_60_90_c67_r',
1067 'cyclic_ymcgy_60_90_c67_s25',
1068 'cyclic_ymcgy_60_90_c67_s25_r',
1069 'dimgray',
1070 'dimgray_r',
1071 'diverging_bkr_55_10_c35',
1072 'diverging_bkr_55_10_c35_r',
1073 'diverging_bky_60_10_c30',
1074 'diverging_bky_60_10_c30_r',
1075 'diverging_bwg_20_95_c41',
1076 'diverging_bwg_20_95_c41_r',
1077 'diverging_bwr_20_95_c54',
1078 'diverging_bwr_20_95_c54_r',
1079 'diverging_bwr_40_95_c42',
1080 'diverging_bwr_40_95_c42_r',
1081 'diverging_bwr_55_98_c37',
1082 'diverging_bwr_55_98_c37_r',
1083 'diverging_cwm_80_100_c22',
1084 'diverging_cwm_80_100_c22_r',
1085 'diverging_gkr_60_10_c40',
1086 'diverging_gkr_60_10_c40_r',
1087 'diverging_gwr_55_95_c38',
1088 'diverging_gwr_55_95_c38_r',
1089 'diverging_gwv_55_95_c39',
1090 'diverging_gwv_55_95_c39_r',
1091 'diverging_isoluminant_cjm_75_c23',
1092 'diverging_isoluminant_cjm_75_c23_r',
1093 'diverging_isoluminant_cjm_75_c24',
1094 'diverging_isoluminant_cjm_75_c24_r',
1095 'diverging_isoluminant_cjo_70_c25',
1096 'diverging_isoluminant_cjo_70_c25_r',
1097 'diverging_linear_bjr_30_55_c53',
1098 'diverging_linear_bjr_30_55_c53_r',
1099 'diverging_linear_bjy_30_90_c45',
1100 'diverging_linear_bjy_30_90_c45_r',
1101 'diverging_linear_protanopic_deuteranopic_bjy_57_89_c34',
1102 'diverging_linear_protanopic_deuteranopic_bjy_57_89_c34_r',
1103 'diverging_protanopic_deuteranopic_bwy_60_95_c32',
1104 'diverging_protanopic_deuteranopic_bwy_60_95_c32_r',
1105 'diverging_rainbow_bgymr_45_85_c67',
1106 'diverging_rainbow_bgymr_45_85_c67_r',
1107 'diverging_tritanopic_cwr_75_98_c20',
1108 'diverging_tritanopic_cwr_75_98_c20_r',
1109 'fire',
1110 'fire_r',
1111 'glasbey',
1112 'glasbey_bw',
1113 'glasbey_bw_minc_20',
1114 'glasbey_bw_minc_20_hue_150_280',
1115 'glasbey_bw_minc_20_hue_150_280_r',
1116 'glasbey_bw_minc_20_hue_330_100',
1117 'glasbey_bw_minc_20_hue_330_100_r',
1118 'glasbey_bw_minc_20_maxl_70',
1119 'glasbey_bw_minc_20_maxl_70_r',
1120 'glasbey_bw_minc_20_minl_30',
1121 'glasbey_bw_minc_20_minl_30_r',
1122 'glasbey_bw_minc_20_r',
1123 'glasbey_bw_r',
1124 'glasbey_category10',
1125 'glasbey_category10_r',
1126 'glasbey_cool',
1127 'glasbey_cool_r',
1128 'glasbey_dark',
1129 'glasbey_dark_r',
1130 'glasbey_hv',
1131 'glasbey_hv_r',
1132 'glasbey_light',
1133 'glasbey_light_r',
1134 'glasbey_r',
1135 'glasbey_warm',
1136 'glasbey_warm_r',
1137 'gouldian',
1138 'gouldian_r',
1139 'gwv',
1140 'gwv_r',
1141 'isolum',
1142 'isolum_r',
1143 'isoluminant_cgo_70_c39',
1144 'isoluminant_cgo_70_c39_r',
1145 'isoluminant_cgo_80_c38',
1146 'isoluminant_cgo_80_c38_r',
1147 'isoluminant_cm_70_c39',
1148 'isoluminant_cm_70_c39_r',
1149 'kb',
1150 'kb_r',
1151 'kbc',
1152 'kbc_r',
1153 'kbgyw',
1154 'kbgyw_r',
1155 'kg',
1156 'kg_r',
1157 'kgy',
1158 'kgy_r',
1159 'kr',
1160 'kr_r',
1161 'linear_bgy_10_95_c74',
1162 'linear_bgy_10_95_c74_r',
1163 'linear_bgyw_15_100_c67',
1164 'linear_bgyw_15_100_c67_r',
1165 'linear_bgyw_15_100_c68',
1166 'linear_bgyw_15_100_c68_r',
1167 'linear_bgyw_20_98_c66',
1168 'linear_bgyw_20_98_c66_r',
1169 'linear_blue_5_95_c73',
1170 'linear_blue_5_95_c73_r',
1171 'linear_blue_95_50_c20',
1172 'linear_blue_95_50_c20_r',
1173 'linear_bmw_5_95_c86',
1174 'linear_bmw_5_95_c86_r',
1175 'linear_bmw_5_95_c89',
1176 'linear_bmw_5_95_c89_r',
1177 'linear_bmy_10_95_c71',
1178 'linear_bmy_10_95_c71_r',
1179 'linear_bmy_10_95_c78',
1180 'linear_bmy_10_95_c78_r',
1181 'linear_gow_60_85_c27',
1182 'linear_gow_60_85_c27_r',
1183 'linear_gow_65_90_c35',
1184 'linear_gow_65_90_c35_r',
1185 'linear_green_5_95_c69',
1186 'linear_green_5_95_c69_r',
1187 'linear_grey_0_100_c0',
1188 'linear_grey_0_100_c0_r',
1189 'linear_grey_10_95_c0',
1190 'linear_grey_10_95_c0_r',
1191 'linear_kbc_5_95_c73',
1192 'linear_kbc_5_95_c73_r',
1193 'linear_kbgoy_20_95_c57',
1194 'linear_kbgoy_20_95_c57_r',
1195 'linear_kbgyw_10_98_c63',
1196 'linear_kbgyw_10_98_c63_r',
1197 'linear_kbgyw_5_98_c62',
1198 'linear_kbgyw_5_98_c62_r',
1199 'linear_kgy_5_95_c69',
1200 'linear_kgy_5_95_c69_r',
1201 'linear_kry_0_97_c73',
1202 'linear_kry_0_97_c73_r',
1203 'linear_kry_5_95_c72',
1204 'linear_kry_5_95_c72_r',
1205 'linear_kry_5_98_c75',
1206 'linear_kry_5_98_c75_r',
1207 'linear_kryw_0_100_c71',
1208 'linear_kryw_0_100_c71_r',
1209 'linear_kryw_5_100_c64',
1210 'linear_kryw_5_100_c64_r',
1211 'linear_kryw_5_100_c67',
1212 'linear_kryw_5_100_c67_r',
1213 'linear_protanopic_deuteranopic_kbjyw_5_95_c25',
1214 'linear_protanopic_deuteranopic_kbjyw_5_95_c25_r',
1215 'linear_protanopic_deuteranopic_kbw_5_95_c34',
1216 'linear_protanopic_deuteranopic_kbw_5_95_c34_r',
1217 'linear_protanopic_deuteranopic_kbw_5_98_c40',
1218 'linear_protanopic_deuteranopic_kbw_5_98_c40_r',
1219 'linear_protanopic_deuteranopic_kyw_5_95_c49',
1220 'linear_protanopic_deuteranopic_kyw_5_95_c49_r',
1221 'linear_ternary_blue_0_44_c57',
1222 'linear_ternary_blue_0_44_c57_r',
1223 'linear_ternary_green_0_46_c42',
1224 'linear_ternary_green_0_46_c42_r',
1225 'linear_ternary_red_0_50_c52',
1226 'linear_ternary_red_0_50_c52_r',
1227 'linear_tritanopic_kcw_5_95_c22',
1228 'linear_tritanopic_kcw_5_95_c22_r',
1229 'linear_tritanopic_krjcw_5_95_c24',
1230 'linear_tritanopic_krjcw_5_95_c24_r',
1231 'linear_tritanopic_krjcw_5_98_c46',
1232 'linear_tritanopic_krjcw_5_98_c46_r',
1233 'linear_tritanopic_krw_5_95_c46',
1234 'linear_tritanopic_krw_5_95_c46_r',
1235 'linear_wcmr_100_45_c42',
1236 'linear_wcmr_100_45_c42_r',
1237 'linear_worb_100_25_c53',
1238 'linear_worb_100_25_c53_r',
1239 'linear_wyor_100_45_c55',
1240 'linear_wyor_100_45_c55_r',
1241 'rainbow4',
1242 'rainbow4_r',
1243 'rainbow_bgyr_10_90_c83',
1244 'rainbow_bgyr_10_90_c83_r',
1245 'rainbow_bgyr_35_85_c72',
1246 'rainbow_bgyr_35_85_c72_r',
1247 'rainbow_bgyr_35_85_c73',
1248 'rainbow_bgyr_35_85_c73_r',
1249 'rainbow_bgyrm_35_85_c69',
1250 'rainbow_bgyrm_35_85_c69_r',
1251 'rainbow_bgyrm_35_85_c71',
1252 'rainbow_bgyrm_35_85_c71_r',
1253 ]
1254 _COLORCET_CMAPS = get_args(_COLORCET_CMAPS_LITERAL)
1255
1256 # Define colormaps that require cmocean
1257 # matches set(cmocean.cm.cmap_d.keys()) - set(mpl.colormaps)
1258 _CMOCEAN_CMAPS_LITERAL = Literal[
1259 'algae',
1260 'algae_i',
1261 'algae_i_r',
1262 'algae_r',
1263 'algae_r_i',
1264 'amp',
1265 'amp_i',
1266 'amp_i_r',
1267 'amp_r',
1268 'amp_r_i',
1269 'balance',
1270 'balance_i',
1271 'balance_i_r',
1272 'balance_r',
1273 'balance_r_i',
1274 'curl',
1275 'curl_i',
1276 'curl_i_r',
1277 'curl_r',
1278 'curl_r_i',
1279 'deep',
1280 'deep_i',
1281 'deep_i_r',
1282 'deep_r',
1283 'deep_r_i',
1284 'delta',
1285 'delta_i',
1286 'delta_i_r',
1287 'delta_r',
1288 'delta_r_i',
1289 'dense',
1290 'dense_i',
1291 'dense_i_r',
1292 'dense_r',
1293 'dense_r_i',
1294 'diff',
1295 'diff_i',
1296 'diff_i_r',
1297 'diff_r',
1298 'diff_r_i',
1299 'gray_i',
1300 'gray_i_r',
1301 'gray_r_i',
1302 'haline',
1303 'haline_i',
1304 'haline_i_r',
1305 'haline_r',
1306 'haline_r_i',
1307 'ice',
1308 'ice_i',
1309 'ice_i_r',
1310 'ice_r',
1311 'ice_r_i',
1312 'matter',
1313 'matter_i',
1314 'matter_i_r',
1315 'matter_r',
1316 'matter_r_i',
1317 'oxy',
1318 'oxy_i',
1319 'oxy_i_r',
1320 'oxy_r',
1321 'oxy_r_i',
1322 'phase',
1323 'phase_i',
1324 'phase_i_r',
1325 'phase_r',
1326 'phase_r_i',
1327 'rain',
1328 'rain_i',
1329 'rain_i_r',
1330 'rain_r',
1331 'rain_r_i',
1332 'solar',
1333 'solar_i',
1334 'solar_i_r',
1335 'solar_r',
1336 'solar_r_i',
1337 'speed',
1338 'speed_i',
1339 'speed_i_r',
1340 'speed_r',
1341 'speed_r_i',
1342 'tarn',
1343 'tarn_i',
1344 'tarn_i_r',
1345 'tarn_r',
1346 'tarn_r_i',
1347 'tempo',
1348 'tempo_i',
1349 'tempo_i_r',
1350 'tempo_r',
1351 'tempo_r_i',
1352 'thermal',
1353 'thermal_i',
1354 'thermal_i_r',
1355 'thermal_r',
1356 'thermal_r_i',
1357 'topo',
1358 'topo_i',
1359 'topo_i_r',
1360 'topo_r',
1361 'topo_r_i',
1362 'turbid',
1363 'turbid_i',
1364 'turbid_i_r',
1365 'turbid_r',
1366 'turbid_r_i',
1367 ]
1368 _CMOCEAN_CMAPS = get_args(_CMOCEAN_CMAPS_LITERAL)
1369
1370 _CMCRAMERI_CMAPS_LITERAL = Literal[
1371 'acton',
1372 'actonS',
1373 'acton_r',
1374 'bam',
1375 'bamO',
1376 'bamO_r',
1377 'bam_r',
1378 'bamako',
1379 'bamakoS',
1380 'bamako_r',
1381 'batlow',
1382 'batlowK',
1383 'batlowKS',
1384 'batlowK_r',
1385 'batlowS',
1386 'batlowW',
1387 'batlowWS',
1388 'batlowW_r',
1389 'batlow_r',
1390 'bilbao',
1391 'bilbaoS',
1392 'bilbao_r',
1393 'broc',
1394 'brocO',
1395 'brocO_r',
1396 'broc_r',
1397 'buda',
1398 'budaS',
1399 'buda_r',
1400 'bukavu',
1401 'bukavu_r',
1402 'cork',
1403 'corkO',
1404 'corkO_r',
1405 'cork_r',
1406 'davos',
1407 'davosS',
1408 'davos_r',
1409 'devon',
1410 'devonS',
1411 'devon_r',
1412 'fes',
1413 'fes_r',
1414 'glasgow',
1415 'glasgowS',
1416 'glasgow_r',
1417 'grayC',
1418 'grayCS',
1419 'grayC_r',
1420 'hawaii',
1421 'hawaiiS',
1422 'hawaii_r',
1423 'imola',
1424 'imolaS',
1425 'imola_r',
1426 'lajolla',
1427 'lajollaS',
1428 'lajolla_r',
1429 'lapaz',
1430 'lapazS',
1431 'lapaz_r',
1432 'lipari',
1433 'lipariS',
1434 'lipari_r',
1435 'lisbon',
1436 'lisbon_r',
1437 'navia',
1438 'naviaS',
1439 'navia_r',
1440 'nuuk',
1441 'nuukS',
1442 'nuuk_r',
1443 'oleron',
1444 'oleron_r',
1445 'oslo',
1446 'osloS',
1447 'oslo_r',
1448 'roma',
1449 'romaO',
1450 'romaO_r',
1451 'roma_r',
1452 'tofino',
1453 'tofino_r',
1454 'tokyo',
1455 'tokyoS',
1456 'tokyo_r',
1457 'turku',
1458 'turkuS',
1459 'turku_r',
1460 'vik',
1461 'vikO',
1462 'vikO_r',
1463 'vik_r',
1464 ]
1465 _CMCRAMERI_CMAPS = get_args(_CMCRAMERI_CMAPS_LITERAL)
1466
1467 _MATPLOTLIB_CMAPS_LITERAL = Literal[
1468 'Accent',
1469 'Accent_r',
1470 'Blues',
1471 'Blues_r',
1472 'BrBG',
1473 'BrBG_r',
1474 'BuGn',
1475 'BuGn_r',
1476 'BuPu',
1477 'BuPu_r',
1478 'CMRmap',
1479 'CMRmap_r',
1480 'Dark2',
1481 'Dark2_r',
1482 'GnBu',
1483 'GnBu_r',
1484 'Grays',
1485 'Grays_r',
1486 'Greens',
1487 'Greens_r',
1488 'Greys',
1489 'Greys_r',
1490 'OrRd',
1491 'OrRd_r',
1492 'Oranges',
1493 'Oranges_r',
1494 'PRGn',
1495 'PRGn_r',
1496 'Paired',
1497 'Paired_r',
1498 'Pastel1',
1499 'Pastel1_r',
1500 'Pastel2',
1501 'Pastel2_r',
1502 'PiYG',
1503 'PiYG_r',
1504 'PuBu',
1505 'PuBuGn',
1506 'PuBuGn_r',
1507 'PuBu_r',
1508 'PuOr',
1509 'PuOr_r',
1510 'PuRd',
1511 'PuRd_r',
1512 'Purples',
1513 'Purples_r',
1514 'RdBu',
1515 'RdBu_r',
1516 'RdGy',
1517 'RdGy_r',
1518 'RdPu',
1519 'RdPu_r',
1520 'RdYlBu',
1521 'RdYlBu_r',
1522 'RdYlGn',
1523 'RdYlGn_r',
1524 'Reds',
1525 'Reds_r',
1526 'Set1',
1527 'Set1_r',
1528 'Set2',
1529 'Set2_r',
1530 'Set3',
1531 'Set3_r',
1532 'Spectral',
1533 'Spectral_r',
1534 'Wistia',
1535 'Wistia_r',
1536 'YlGn',
1537 'YlGnBu',
1538 'YlGnBu_r',
1539 'YlGn_r',
1540 'YlOrBr',
1541 'YlOrBr_r',
1542 'YlOrRd',
1543 'YlOrRd_r',
1544 'afmhot',
1545 'afmhot_r',
1546 'autumn',
1547 'autumn_r',
1548 'berlin',
1549 'berlin_r',
1550 'binary',
1551 'binary_r',
1552 'bone',
1553 'bone_r',
1554 'brg',
1555 'brg_r',
1556 'bwr',
1557 'bwr_r',
1558 'cividis',
1559 'cividis_r',
1560 'cool',
1561 'cool_r',
1562 'coolwarm',
1563 'coolwarm_r',
1564 'copper',
1565 'copper_r',
1566 'cubehelix',
1567 'cubehelix_r',
1568 'flag',
1569 'flag_r',
1570 'gist_earth',
1571 'gist_earth_r',
1572 'gist_gray',
1573 'gist_gray_r',
1574 'gist_grey',
1575 'gist_grey_r',
1576 'gist_heat',
1577 'gist_heat_r',
1578 'gist_ncar',
1579 'gist_ncar_r',
1580 'gist_rainbow',
1581 'gist_rainbow_r',
1582 'gist_stern',
1583 'gist_stern_r',
1584 'gist_yarg',
1585 'gist_yarg_r',
1586 'gist_yerg',
1587 'gist_yerg_r',
1588 'gnuplot',
1589 'gnuplot2',
1590 'gnuplot2_r',
1591 'gnuplot_r',
1592 'gray',
1593 'gray_r',
1594 'grey',
1595 'grey_r',
1596 'hot',
1597 'hot_r',
1598 'hsv',
1599 'hsv_r',
1600 'inferno',
1601 'inferno_r',
1602 'jet',
1603 'jet_r',
1604 'magma',
1605 'magma_r',
1606 'managua',
1607 'managua_r',
1608 'nipy_spectral',
1609 'nipy_spectral_r',
1610 'ocean',
1611 'ocean_r',
1612 'okabe_ito',
1613 'okabe_ito_r',
1614 'pink',
1615 'pink_r',
1616 'plasma',
1617 'plasma_r',
1618 'prism',
1619 'prism_r',
1620 'rainbow',
1621 'rainbow_r',
1622 'seismic',
1623 'seismic_r',
1624 'spring',
1625 'spring_r',
1626 'summer',
1627 'summer_r',
1628 'tab10',
1629 'tab10_r',
1630 'tab20',
1631 'tab20_r',
1632 'tab20b',
1633 'tab20b_r',
1634 'tab20c',
1635 'tab20c_r',
1636 'terrain',
1637 'terrain_r',
1638 'turbo',
1639 'turbo_r',
1640 'twilight',
1641 'twilight_r',
1642 'twilight_shifted',
1643 'twilight_shifted_r',
1644 'vanimo',
1645 'vanimo_r',
1646 'viridis',
1647 'viridis_r',
1648 'winter',
1649 'winter_r',
1650 ]
1651
1652 _MATPLOTLIB_CMAPS = get_args(_MATPLOTLIB_CMAPS_LITERAL)
1653
1654
1655 class Color(_NoNewAttrMixin):
1656 """Helper class to convert between different color representations used in the pyvista library.
1657
1658 Many pyvista methods accept :data:`ColorLike` parameters. This helper class
1659 is used to convert such parameters to the necessary format, used by
1660 underlying (VTK) methods. Any color name (``str``), hex string (``str``)
1661 or RGB(A) sequence (``tuple``, ``list`` or ``numpy.ndarray`` of ``int``
1662 or ``float``) is considered a :data:`ColorLike` parameter and can be converted
1663 by this class.
1664
1665 See :ref:`named_colors` for a list of supported colors.
1666
1667 .. note:
1668
1669 The internally used representation is an integer RGBA sequence (values
1670 between 0 and 255). This might however change in future releases.
1671
1672 Parameters
1673 ----------
1674 color : ColorLike, optional
1675 Either a string, RGB sequence, RGBA sequence, or hex color string.
1676 RGB(A) sequences should either be provided as floats between 0 and 1
1677 or as ints between 0 and 255. Hex color strings can contain optional
1678 ``'#'`` or ``'0x'`` prefixes. If no opacity is provided, the
1679 ``default_opacity`` will be used. If ``color`` is ``None``, the
1680 ``default_color`` is used instead.
1681 The following examples all denote the color 'white':
1682
1683 * ``'white'``
1684 * ``'w'``
1685 * ``[1.0, 1.0, 1.0]``
1686 * ``[255, 255, 255, 255]``
1687 * ``'#FFFFFF'``
1688
1689 opacity : int | float | str, optional
1690 Opacity of the represented color. Overrides any opacity associated
1691 with the provided ``color``. Allowed opacities are floats between 0
1692 and 1, ints between 0 and 255 or hexadecimal strings of length 2
1693 (plus the length of the optional prefix).
1694 The following examples all denote a fully opaque color:
1695
1696 * ``1.0``
1697 * ``255``
1698 * ``'#ff'``
1699
1700 default_color : ColorLike, optional
1701 Default color to use when ``color`` is ``None``. If this value is
1702 ``None``, then defaults to the global theme color. Format is
1703 identical to ``color``.
1704
1705 default_opacity : int | float | str, optional
1706 Default opacity of the represented color. Used when ``color``
1707 does not specify an opacity and ``opacity`` is ``None``. Format
1708 is identical to ``opacity``.
1709
1710 Examples
1711 --------
1712 Create a transparent green color using a color name, float RGBA sequence,
1713 integer RGBA sequence and RGBA hexadecimal string.
1714
1715 >>> import pyvista as pv
1716 >>> pv.Color('green', opacity=0.5)
1717 Color(name='green', hex='#00800080', opacity=128)
1718 >>> pv.Color([0.0, 0.5, 0.0, 0.5])
1719 Color(name='green', hex='#00800080', opacity=128)
1720 >>> pv.Color([0, 128, 0, 128])
1721 Color(name='green', hex='#00800080', opacity=128)
1722 >>> pv.Color('#00800080')
1723 Color(name='green', hex='#00800080', opacity=128)
1724
1725 """
1726
1727 # Supported names for each color channel.
1728 CHANNEL_NAMES = (
1729 {'red', 'r'}, # 0
1730 {'green', 'g'}, # 1
1731 {'blue', 'b'}, # 2
1732 {'alpha', 'a', 'opacity'}, # 3
1733 )
1734
1735 @_deprecate_positional_args(allowed=['color', 'opacity'])
1736 def __init__( # noqa: PLR0917
1737 self,
1738 color: ColorLike | None = None,
1739 opacity: float | str | None = None,
1740 default_color: ColorLike | None = None,
1741 default_opacity: float | str = 255,
1742 ):
1743 """Initialize new instance."""
1744 self._red, self._green, self._blue, self._opacity = 0, 0, 0, 0
1745 self._opacity = self.convert_color_channel(default_opacity)
1746 self._name = None
1747
1748 # Use default color if no color is provided
1749 if color is None:
1750 color = pv.global_theme.color if default_color is None else default_color
1751
1752 _validation.check_instance(
1753 color, (Color, str, dict, list, tuple, np.ndarray, _vtk.vtkColor3ub), name='color'
1754 )
1755 try:
1756 if isinstance(color, Color):
1757 # Create copy of color instance
1758 self._red, self._green, self._blue, self._opacity = color.int_rgba
1759 elif isinstance(color, str):
1760 # From named color or hex string
1761 self._from_str(color)
1762 elif isinstance(color, dict):
1763 # From dictionary
1764 self._from_dict(color)
1765 elif isinstance(color, (list, tuple, np.ndarray)):
1766 # From RGB(A) sequence
1767 self._from_rgba(color)
1768 elif isinstance(color, _vtk.vtkColor3ub):
1769 # From vtkColor3ub instance (can be unpacked as rgb tuple)
1770 self._from_rgba(color)
1771 else: # pragma: no cover
1772 msg = f'Unexpected color type: {type(color)}'
1773 raise TypeError(msg)
1774 self._name = color_names.get(self.hex_rgb)
1775 except ValueError as e:
1776 msg = (
1777 '\n'
1778 f'\tInvalid color input: ({color})\n'
1779 '\tMust be a string, rgb(a) sequence, or hex color string. For example:\n'
1780 "\t\tcolor='white'\n"
1781 "\t\tcolor='w'\n"
1782 '\t\tcolor=[1.0, 1.0, 1.0]\n'
1783 '\t\tcolor=[255, 255, 255]\n'
1784 "\t\tcolor='#FFFFFF'"
1785 )
1786 raise ValueError(msg) from e
1787
1788 # Overwrite opacity if it is provided
1789 try:
1790 if opacity is not None:
1791 self._opacity = self.convert_color_channel(opacity)
1792 except ValueError as e:
1793 msg = (
1794 '\n'
1795 f'\tInvalid opacity input: ({opacity})'
1796 '\tMust be an integer, float or string. For example:\n'
1797 "\t\topacity='1.0'\n"
1798 "\t\topacity='255'\n"
1799 "\t\topacity='#FF'"
1800 )
1801 raise ValueError(msg) from e
1802
1803 @staticmethod
1804 def strip_hex_prefix(h: str) -> str:
1805 """Strip any ``'#'`` or ``'0x'`` prefix from a hexadecimal string.
1806
1807 Parameters
1808 ----------
1809 h : str
1810 Hexadecimal string to strip.
1811
1812 Returns
1813 -------
1814 str
1815 Stripped hexadecimal string.
1816
1817 """
1818 h = h.lstrip('#')
1819 return h.removeprefix('0x')
1820
1821 @staticmethod
1822 def convert_color_channel(
1823 val: float | np.floating[Any] | np.integer[Any] | str,
1824 ) -> int:
1825 """Convert the given color channel value to the integer representation.
1826
1827 Parameters
1828 ----------
1829 val : int | float | str
1830 Color channel value to convert. Supported input values are a
1831 hex string of length 2 (``'00'`` to ``'ff'``) with an optional
1832 prefix (``'#'`` or ``'0x'``), a float (``0.0`` to ``1.0``) or
1833 an integer (``0`` to ``255``).
1834
1835 Returns
1836 -------
1837 int
1838 Color channel value in the integer representation (values between
1839 ``0`` and ``255``).
1840
1841 """
1842 # Check for numpy inputs to avoid unnecessary calls to np.issubdtype
1843 arr = None
1844 if isinstance(val, (np.ndarray, np.generic)):
1845 arr = np.asanyarray(val)
1846
1847 # Convert non-integers to int
1848 if isinstance(val, str):
1849 # From hexadecimal value
1850 val = int(Color.strip_hex_prefix(val), 16)
1851 elif isinstance(val, float) or (
1852 arr is not None and np.issubdtype(arr.dtype, np.floating) and arr.ndim == 0
1853 ):
1854 val = round(255 * val)
1855
1856 # Check integers
1857 if isinstance(val, int) and 0 <= val <= 255:
1858 return val # type: ignore[return-value]
1859 elif isinstance(val, np.uint8) or (
1860 arr is not None
1861 and np.issubdtype(arr.dtype, np.integer)
1862 and arr.ndim == 0
1863 and 0 <= val <= 255
1864 ):
1865 return int(val)
1866 else:
1867 msg = f'Unsupported color channel value provided: {val}'
1868 raise ValueError(msg)
1869
1870 def _from_rgba(self, rgba):
1871 """Construct color from an RGB(A) sequence."""
1872 arg = rgba
1873 if len(rgba) == 3:
1874 # Keep using current opacity if it is not provided.
1875 rgba = [*rgba, self._opacity]
1876 try:
1877 if len(rgba) != 4:
1878 msg = 'Invalid length for RGBA sequence.'
1879 raise ValueError(msg)
1880 self._red, self._green, self._blue, self._opacity = (
1881 self.convert_color_channel(c) for c in rgba
1882 )
1883 except ValueError:
1884 msg = f'Invalid RGB(A) sequence: {arg}'
1885 raise ValueError(msg) from None
1886
1887 def _from_dict(self, dct):
1888 """Construct color from an RGB(A) dictionary."""
1889 # Get any of the keys associated with each color channel (or None).
1890 rgba = [
1891 next((dct[key] for key in cnames if key in dct), None) for cnames in self.CHANNEL_NAMES
1892 ]
1893 self._from_rgba(rgba)
1894
1895 def _from_hex(self, h):
1896 """Construct color from a hex string."""
1897 arg = h
1898 h = self.strip_hex_prefix(h)
1899 try:
1900 self._from_rgba(
1901 [self.convert_color_channel(h[i : i + 2]) for i in range(0, len(h), 2)]
1902 )
1903 except ValueError:
1904 msg = f'Invalid hex string: {arg}'
1905 raise ValueError(msg) from None
1906
1907 def _from_str(self, n: str):
1908 """Construct color from a name or hex string."""
1909 arg = n
1910 n = _format_color_name(n)
1911 if n in _formatted_color_synonyms:
1912 # Synonym of registered color name
1913 # Convert from synonym to full hex
1914 n = _formatted_color_synonyms[n]
1915 self._from_hex(_formatted_hex_colors[n])
1916 elif n in _formatted_hex_colors:
1917 # Color name
1918 self._from_hex(_formatted_hex_colors[n])
1919 else:
1920 # Otherwise, try conversion to hex
1921 try:
1922 self._from_hex(n)
1923 except ValueError:
1924 msg = f'Invalid color name or hex string: {arg}'
1925 raise ValueError(msg) from None
1926
1927 @property
1928 def int_rgba(self) -> tuple[int, int, int, int]: # numpydoc ignore=RT01
1929 """Get the color value as an RGBA integer tuple.
1930
1931 Examples
1932 --------
1933 Create a blue color with half opacity.
1934
1935 >>> import pyvista as pv
1936 >>> c = pv.Color('blue', opacity=128)
1937 >>> c
1938 Color(name='blue', hex='#0000ff80', opacity=128)
1939 >>> c.int_rgba
1940 (0, 0, 255, 128)
1941
1942 Create a transparent red color using an integer RGBA sequence.
1943
1944 >>> c = pv.Color([255, 0, 0, 64])
1945 >>> c
1946 Color(name='red', hex='#ff000040', opacity=64)
1947 >>> c.int_rgba
1948 (255, 0, 0, 64)
1949
1950 """
1951 return self._red, self._green, self._blue, self._opacity
1952
1953 @property
1954 def int_rgb(self) -> tuple[int, int, int]: # numpydoc ignore=RT01
1955 """Get the color value as an RGB integer tuple.
1956
1957 Examples
1958 --------
1959 Create a blue color with half opacity.
1960
1961 >>> import pyvista as pv
1962 >>> c = pv.Color('blue', opacity=128)
1963 >>> c
1964 Color(name='blue', hex='#0000ff80', opacity=128)
1965 >>> c.int_rgb
1966 (0, 0, 255)
1967
1968 Create a red color using an integer RGB sequence.
1969
1970 >>> c = pv.Color([255, 0, 0])
1971 >>> c
1972 Color(name='red', hex='#ff0000ff', opacity=255)
1973 >>> c.int_rgb
1974 (255, 0, 0)
1975
1976 """
1977 return self.int_rgba[:3]
1978
1979 @property
1980 def float_rgba(self) -> tuple[float, float, float, float]: # numpydoc ignore=RT01
1981 """Get the color value as an RGBA float tuple.
1982
1983 Examples
1984 --------
1985 Create a blue color with custom opacity.
1986
1987 >>> import pyvista as pv
1988 >>> c = pv.Color('blue', opacity=0.6)
1989 >>> c
1990 Color(name='blue', hex='#0000ff99', opacity=153)
1991 >>> c.float_rgba
1992 (0.0, 0.0, 1.0, 0.6)
1993
1994 Create a transparent red color using a float RGBA sequence.
1995
1996 >>> c = pv.Color([1.0, 0.0, 0.0, 0.2])
1997 >>> c
1998 Color(name='red', hex='#ff000033', opacity=51)
1999 >>> c.float_rgba
2000 (1.0, 0.0, 0.0, 0.2)
2001
2002 """
2003 return (
2004 self._red / 255.0,
2005 self._green / 255.0,
2006 self._blue / 255.0,
2007 self._opacity / 255.0,
2008 )
2009
2010 @property
2011 def float_rgb(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
2012 """Get the color value as an RGB float tuple.
2013
2014 Examples
2015 --------
2016 Create a blue color with custom opacity.
2017
2018 >>> import pyvista as pv
2019 >>> c = pv.Color('blue', default_opacity=0.6)
2020 >>> c
2021 Color(name='blue', hex='#0000ff99', opacity=153)
2022 >>> c.float_rgb
2023 (0.0, 0.0, 1.0)
2024
2025 Create a red color using a float RGB sequence.
2026
2027 >>> c = pv.Color([1.0, 0.0, 0.0])
2028 >>> c
2029 Color(name='red', hex='#ff0000ff', opacity=255)
2030 >>> c.float_rgb
2031 (1.0, 0.0, 0.0)
2032
2033 """
2034 return self.float_rgba[:3]
2035
2036 @property
2037 def _float_hls(self) -> tuple[float, float, float]:
2038 """Get the color as Hue, Lightness, Saturation (HLS) in range [0.0, 1.0]."""
2039 return rgb_to_hls(*self.float_rgb)
2040
2041 @property
2042 def hex_rgba(self) -> str: # numpydoc ignore=RT01
2043 """Get the color value as an RGBA hexadecimal value.
2044
2045 Examples
2046 --------
2047 Create a blue color with half opacity.
2048
2049 >>> import pyvista as pv
2050 >>> c = pv.Color('blue', default_opacity='#80')
2051 >>> c
2052 Color(name='blue', hex='#0000ff80', opacity=128)
2053 >>> c.hex_rgba
2054 '#0000ff80'
2055
2056 Create a transparent red color using an RGBA hexadecimal value.
2057
2058 >>> c = pv.Color('0xff000040')
2059 >>> c
2060 Color(name='red', hex='#ff000040', opacity=64)
2061 >>> c.hex_rgba
2062 '#ff000040'
2063
2064 """
2065 return '#' + ''.join(
2066 f'{c:0>2x}' for c in (self._red, self._green, self._blue, self._opacity)
2067 )
2068
2069 @property
2070 def hex_rgb(self) -> str: # numpydoc ignore=RT01
2071 """Get the color value as an RGB hexadecimal value.
2072
2073 Examples
2074 --------
2075 Create a blue color with half opacity.
2076
2077 >>> import pyvista as pv
2078 >>> c = pv.Color('blue', default_opacity='#80')
2079 >>> c
2080 Color(name='blue', hex='#0000ff80', opacity=128)
2081 >>> c.hex_rgb
2082 '#0000ff'
2083
2084 Create a red color using an RGB hexadecimal value.
2085
2086 >>> c = pv.Color('0xff0000')
2087 >>> c
2088 Color(name='red', hex='#ff0000ff', opacity=255)
2089 >>> c.hex_rgb
2090 '#ff0000'
2091
2092 """
2093 return self.hex_rgba[:-2]
2094
2095 @property
2096 def name(self) -> str | None: # numpydoc ignore=RT01
2097 """Get the color name.
2098
2099 The name is always formatted as a lower case string with
2100 underscore delimiters between words.
2101
2102 See :ref:`named_colors` for a list of supported colors.
2103
2104 .. versionchanged:: 0.48
2105
2106 Multi-word names are now delimited with ``_`` e.g. ``'alice_blue'`` instead of
2107 ``'aliceblue'``.
2108
2109 Returns
2110 -------
2111 output : str | None
2112 The color name, in case this color has a name; otherwise ``None``.
2113
2114 Examples
2115 --------
2116 Create a dark blue color with half opacity.
2117
2118 >>> import pyvista as pv
2119 >>> c = pv.Color('darkblue', default_opacity=0.5)
2120 >>> c
2121 Color(name='dark_blue', hex='#00008b80', opacity=128)
2122
2123 When creating a new ``Color``, the name may be delimited with a space,
2124 hyphen, underscore, or written as a single word.
2125
2126 >>> c = pv.Color('dark blue', default_opacity=0.5)
2127
2128 Upper-case letters are also supported.
2129
2130 >>> c = pv.Color('DarkBlue', default_opacity=0.5)
2131
2132 However, the name is always standardized as lower-case with an underscore between words.
2133
2134 >>> c
2135 Color(name='dark_blue', hex='#00008b80', opacity=128)
2136
2137 """
2138 return self._name
2139
2140 @property
2141 def vtk_c3ub(self) -> _vtk.vtkColor3ub: # numpydoc ignore=RT01
2142 """Get the color value as a VTK Color3ub instance.
2143
2144 Examples
2145 --------
2146 Create a blue color with half opacity.
2147
2148 >>> import pyvista as pv
2149 >>> c = pv.Color('blue', default_opacity=0.5)
2150 >>> c
2151 Color(name='blue', hex='#0000ff80', opacity=128)
2152 >>> c.vtk_c3ub
2153 vtkmodules.vtkCommonDataModel.vtkColor3ub([0, 0, 255])
2154
2155 """
2156 return _vtk.vtkColor3ub(self._red, self._green, self._blue)
2157
2158 def linear_to_srgb(self):
2159 """Convert from linear color values to sRGB color values.
2160
2161 Returns
2162 -------
2163 Color
2164 A new ``Color`` instance with sRGB color values.
2165
2166 """
2167 rgba = np.array(self.float_rgba)
2168 mask = rgba < 0.0031308
2169 rgba[mask] *= 12.92
2170 rgba[~mask] = 1.055 * rgba[~mask] ** (1 / 2.4) - 0.055
2171 return Color(rgba)
2172
2173 def srgb_to_linear(self):
2174 """Convert from sRGB color values to linear color values.
2175
2176 Returns
2177 -------
2178 Color
2179 A new ``Color`` instance with linear color values.
2180
2181 """
2182 rgba = np.array(self.float_rgba)
2183 mask = rgba < 0.04045
2184 rgba[mask] /= 12.92
2185 rgba[~mask] = ((rgba[~mask] + 0.055) / 1.055) ** 2.4
2186 return Color(rgba)
2187
2188 @classmethod
2189 def from_dict(cls, dict_): # numpydoc ignore=RT01
2190 """Construct from dictionary for JSON deserialization."""
2191 return Color(dict_)
2192
2193 def to_dict(self): # numpydoc ignore=RT01
2194 """Convert to dictionary for JSON serialization."""
2195 return {'r': self._red, 'g': self._green, 'b': self._blue, 'a': self._opacity}
2196
2197 @property
2198 def opacity(self): # numpydoc ignore=RT01
2199 """Return the opacity of this color in the range of ``(0-255)``.
2200
2201 Examples
2202 --------
2203 >>> import pyvista as pv
2204 >>> color = pv.Color('r', opacity=0.5)
2205 >>> color.opacity
2206 128
2207 >>> color
2208 Color(name='red', hex='#ff000080', opacity=128)
2209
2210 """
2211 return self._opacity
2212
2213 def __eq__(self, other):
2214 """Equality comparison."""
2215 try:
2216 return self.int_rgba == Color(other).int_rgba
2217 except ValueError: # pragma: no cover
2218 return NotImplemented
2219
2220 def __hash__(self): # pragma: no cover
2221 """Hash calculation."""
2222 return hash((self._red, self._green, self._blue, self._opacity))
2223
2224 def __getitem__(self, item):
2225 """Support indexing the float RGBA representation for backward compatibility."""
2226 if not isinstance(item, (str, slice, int, np.integer)):
2227 msg = 'Invalid index specified, only strings and integers are supported.'
2228 raise TypeError(msg)
2229 if isinstance(item, str):
2230 for i, cnames in enumerate(self.CHANNEL_NAMES):
2231 if item in cnames:
2232 item = i
2233 break
2234 else:
2235 msg = f'Invalid string index {item!r}.'
2236 raise ValueError(msg)
2237 return self.float_rgba[item]
2238
2239 def __iter__(self):
2240 """Support iteration over the float RGBA representation for backward compatibility."""
2241 return iter(self.float_rgba)
2242
2243 def __repr__(self) -> str: # pragma: no cover
2244 """Human readable representation."""
2245 kwargs = f'hex={self.hex_rgba!r}, opacity={self.opacity}'
2246 if self._name is not None:
2247 kwargs = f'name={self._name!r}, ' + kwargs
2248 return f'Color({kwargs})'
2249
2250
2251 PARAVIEW_BACKGROUND = Color('paraview').float_rgb
2252
2253
2254 def get_cmap_safe(cmap: ColormapOptions) -> colors.Colormap:
2255 """Fetch a colormap by name from matplotlib, colorcet, cmocean, or cmcrameri.
2256
2257 See :ref:`named_colormaps` for supported colormaps.
2258
2259 Parameters
2260 ----------
2261 cmap : str | list[str] | matplotlib.colors.Colormap
2262 Name of the colormap to fetch. If the input is a list of strings, the
2263 strings must be color names (from :ref:`named_colors`), and
2264 it will create a ``ListedColormap`` with the input list.
2265
2266 Returns
2267 -------
2268 matplotlib.colors.Colormap
2269 The requested colormap if available.
2270
2271 Raises
2272 ------
2273 ValueError
2274 If the input colormap name is not valid.
2275 TypeError
2276 If the input is a list of items that are not strings.
2277
2278 """
2279 _validation.check_instance(cmap, (str, list, colors.Colormap), name='cmap')
2280
2281 def get_3rd_party_cmap(cmap_):
2282 cmap_sources = {
2283 'colorcet.cm': _COLORCET_CMAPS,
2284 'cmocean.cm.cmap_d': _CMOCEAN_CMAPS,
2285 'cmcrameri.cm.cmaps': _CMCRAMERI_CMAPS,
2286 }
2287
2288 def get_nested_attr(obj, attr_path):
2289 for attr in attr_path:
2290 obj = getattr(obj, attr)
2291 return obj
2292
2293 # Try importing and returning cmap from each package. Restrict lookup to
2294 # the curated set of names unique to each package so matplotlib
2295 # colormaps are never shadowed by a third-party package that happens to
2296 # define the same name (e.g. colorcet's ``coolwarm`` vs matplotlib's).
2297 for cmap_import, known_cmaps in cmap_sources.items():
2298 if cmap_ not in known_cmaps:
2299 continue
2300
2301 parts = cmap_import.split('.')
2302 top_module = parts[0]
2303
2304 try:
2305 mod = importlib.import_module(top_module)
2306 except ImportError:
2307 msg = (
2308 f'Package `{top_module}` is required to use colormap {cmap_!r}.\n'
2309 'Install PyVista with `pyvista[colormaps]` to install it by default.'
2310 )
2311 raise ModuleNotFoundError(msg) from None
2312
2313 cmap_dict = get_nested_attr(mod, parts[1:])
2314 with contextlib.suppress(KeyError):
2315 return cmap_dict[cmap_]
2316 return None
2317
2318 if isinstance(cmap, colors.Colormap):
2319 return cmap
2320 if isinstance(cmap, str):
2321 # check if this colormap has been mapped between ipygany
2322 if cmap in IPYGANY_MAP:
2323 cmap = IPYGANY_MAP[cmap] # type: ignore[assignment]
2324
2325 cmap_3rd_party = get_3rd_party_cmap(cmap)
2326 if cmap_3rd_party:
2327 return cmap_3rd_party
2328 elif not isinstance(cmap, colors.Colormap):
2329 if inspect.ismodule(colormaps): # pragma: no cover
2330 # Backwards compatibility with matplotlib<3.5.0
2331 if not hasattr(colormaps, cmap):
2332 msg = f'Invalid colormap "{cmap}"'
2333 raise ValueError(msg)
2334 cmap_obj = getattr(colormaps, cmap)
2335 else:
2336 try:
2337 cmap_obj = colormaps[cmap]
2338 except KeyError:
2339 msg = f"Invalid colormap '{cmap}'"
2340 raise ValueError(msg) from None
2341
2342 else: # input is a list
2343 for item in cmap:
2344 if not isinstance(item, str):
2345 msg = 'When inputting a list as a cmap, each item should be a string.' # type: ignore[unreachable]
2346 raise TypeError(msg)
2347
2348 cmap_obj = ListedColormap(cmap)
2349
2350 return cmap_obj
2351
2352
2353 def get_default_cycler():
2354 """Return the default color cycler (matches matplotlib's default).
2355
2356 Returns
2357 -------
2358 cycler.Cycler
2359 A cycler object for color that matches matplotlib's default colors.
2360
2361 """
2362 return cycler('color', matplotlib_default_colors)
2363
2364
2365 def get_hexcolors_cycler():
2366 """Return a color cycler for all of the available hex colors.
2367
2368 See ``pyvista.plotting.colors.hex_colors``.
2369
2370 Returns
2371 -------
2372 cycler.Cycler
2373 A cycler object for color using all the available hex colors from
2374 ``pyvista.plotting.colors.hexc_olors``.
2375
2376 """
2377 return cycler('color', hex_colors.keys())
2378
2379
2380 def get_matplotlib_theme_cycler():
2381 """Return the color cycler of the current matplotlib theme.
2382
2383 Returns
2384 -------
2385 cycler.Cycler
2386 Color cycler of the current matplotlib theme.
2387
2388 """
2389 return plt.rcParams['axes.prop_cycle']
2390
2391
2392 def color_scheme_to_cycler(scheme):
2393 """Convert a color scheme to a Cycler.
2394
2395 Parameters
2396 ----------
2397 scheme : str | int | :vtk:`vtkColorSeries`
2398 Color scheme to be converted. If a string, it should correspond to a
2399 valid color scheme name (e.g., 'viridis'). If an integer, it should
2400 correspond to a valid color scheme ID. If an instance of
2401 :vtk:`vtkColorSeries`, it should be a valid color series.
2402
2403 Returns
2404 -------
2405 cycler.Cycler
2406 A Cycler object with the color scheme.
2407
2408 Raises
2409 ------
2410 ValueError
2411 If the provided `scheme` is not a valid color scheme.
2412
2413 """
2414 if not isinstance(scheme, _vtk.vtkColorSeries):
2415 series = _vtk.vtkColorSeries()
2416 if isinstance(scheme, str):
2417 series.SetColorScheme(COLOR_SCHEMES.get(scheme.lower())['id']) # type: ignore[index]
2418 elif isinstance(scheme, int):
2419 series.SetColorScheme(scheme)
2420 else:
2421 msg = f'Color scheme not understood: {scheme}'
2422 raise TypeError(msg)
2423 else:
2424 series = scheme
2425 colors = (series.GetColor(i) for i in range(series.GetNumberOfColors()))
2426 return cycler('color', colors)
2427
2428
2429 def get_cycler(color_cycler):
2430 """Return a color cycler based on the input value.
2431
2432 Parameters
2433 ----------
2434 color_cycler : str, list, tuple, or Cycler
2435 Specifies the desired color cycler. The value must be one of the following:
2436 - A list or tuple of color-like objects
2437 - A Cycler object with color-like objects
2438 - One of the following string values:
2439 - ``'default'``: Use the default color cycler (matches matplotlib's default)
2440 - ``'matplotlib'``: Dynamically get matplotlib's current theme's color cycler.
2441 - ``'all'``: Cycle through all available colors in
2442 ``pyvista.plotting.colors.hexcolors``
2443 - A named color scheme from ``pyvista.plotting.colors.COLOR_SCHEMES``
2444
2445 Returns
2446 -------
2447 Cycler
2448 The color cycler corresponding to the input value.
2449
2450 Raises
2451 ------
2452 ValueError
2453 Raised if the input is a string not found in named color schemes.
2454 TypeError
2455 Raised if the input is of an unsupported type.
2456
2457 """
2458 if color_cycler is None:
2459 cycler_ = None
2460 elif isinstance(color_cycler, str):
2461 if color_cycler == 'default':
2462 cycler_ = get_default_cycler()
2463 elif color_cycler == 'matplotlib':
2464 cycler_ = get_matplotlib_theme_cycler()
2465 elif color_cycler == 'all':
2466 cycler_ = get_hexcolors_cycler()
2467 elif color_cycler in COLOR_SCHEMES:
2468 cycler_ = color_scheme_to_cycler(color_cycler)
2469 else:
2470 msg = f'color cycler of name `{color_cycler}` not found.'
2471 raise ValueError(msg)
2472 elif isinstance(color_cycler, (tuple, list)):
2473 cycler_ = cycler('color', color_cycler)
2474 elif isinstance(color_cycler, Cycler):
2475 cycler_ = color_cycler
2476 else:
2477 msg = f'color cycler of type {type(color_cycler)} not supported.'
2478 raise TypeError(msg)
2479 return cycler_