1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
|
"""Color module supporting plotting module.
Used code from matplotlib.colors. Thanks for your work.
SUPPORTED COLORS
aliceblue
antiquewhite
aqua
aquamarine
azure
beige
bisque
black
blanchedalmond
blue
blueviolet
brown
burlywood
cadetblue
chartreuse
chocolate
coral
cornflowerblue
cornsilk
crimson
cyan
darkblue
darkcyan
darkgoldenrod
darkgray
darkgreen
darkgrey
darkkhaki
darkmagenta
darkolivegreen
darkorange
darkorchid
darkred
darksalmon
darkseagreen
darkslateblue
darkslategray
darkslategrey
darkturquoise
darkviolet
deeppink
deepskyblue
dimgray
dimgrey
dodgerblue
firebrick
floralwhite
forestgreen
fuchsia
gainsboro
ghostwhite
gold
goldenrod
gray
green
greenyellow
grey
honeydew
hotpink
indianred
indigo
ivory
khaki
lavender
lavenderblush
lawngreen
lemonchiffon
lightblue
lightcoral
lightcyan
lightgoldenrodyellow
lightgray
lightgreen
lightgrey
lightpink
lightsalmon
lightseagreen
lightskyblue
lightslategray
lightslategrey
lightsteelblue
lightyellow
lime
limegreen
linen
magenta
maroon
mediumaquamarine
mediumblue
mediumorchid
mediumpurple
mediumseagreen
mediumslateblue
mediumspringgreen
mediumturquoise
mediumvioletred
midnightblue
mintcream
mistyrose
moccasin
navajowhite
navy
oldlace
olive
olivedrab
orange
orangered
orchid
palegoldenrod
palegreen
paleturquoise
palevioletred
papayawhip
peachpuff
peru
pink
plum
powderblue
purple
rebeccapurple
red
rosybrown
royalblue
saddlebrown
salmon
sandybrown
seagreen
seashell
sienna
silver
skyblue
slateblue
slategray
slategrey
snow
springgreen
steelblue
tan
teal
thistle
tomato
turquoise
violet
wheat
white
whitesmoke
yellow
yellowgreen
tab:blue
tab:orange
tab:green
tab:red
tab:purple
tab:brown
tab:pink
tab:gray
tab:olive
tab:cyan
"""
# Necessary for autodoc_type_aliases to recognize the type aliases used in the signatures
# of methods defined in this module.
from __future__ import annotations
import inspect
from cycler import Cycler
from cycler import cycler
try:
from matplotlib import colormaps
from matplotlib import colors
except ImportError: # pragma: no cover
# typing for newer versions of matplotlib
# in newer versions cm is a module
from matplotlib import cm as colormaps # type: ignore[assignment]
from matplotlib import colors
from typing import TYPE_CHECKING
from typing import Any
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
import pyvista
from pyvista.core.utilities.misc import has_module
from . import _vtk
if TYPE_CHECKING: # pragma: no cover
from ._typing import ColorLike
IPYGANY_MAP = {
'reds': 'Reds',
'spectral': 'Spectral',
}
# Following colors are copied from matplotlib.colors, synonyms (colors with a
# different name but same hex value) are removed and put in the `color_synonyms`
# dictionary. An extra `paraview_background` color is added.
hexcolors = {
'aliceblue': '#F0F8FF',
'antiquewhite': '#FAEBD7',
'aquamarine': '#7FFFD4',
'azure': '#F0FFFF',
'beige': '#F5F5DC',
'bisque': '#FFE4C4',
'black': '#000000',
'blanchedalmond': '#FFEBCD',
'blue': '#0000FF',
'blueviolet': '#8A2BE2',
'brown': '#654321',
'burlywood': '#DEB887',
'cadetblue': '#5F9EA0',
'chartreuse': '#7FFF00',
'chocolate': '#D2691E',
'coral': '#FF7F50',
'cornflowerblue': '#6495ED',
'cornsilk': '#FFF8DC',
'crimson': '#DC143C',
'cyan': '#00FFFF',
'darkblue': '#00008B',
'darkcyan': '#008B8B',
'darkgoldenrod': '#B8860B',
'darkgray': '#A9A9A9',
'darkgreen': '#006400',
'darkkhaki': '#BDB76B',
'darkmagenta': '#8B008B',
'darkolivegreen': '#556B2F',
'darkorange': '#FF8C00',
'darkorchid': '#9932CC',
'darkred': '#8B0000',
'darksalmon': '#E9967A',
'darkseagreen': '#8FBC8F',
'darkslateblue': '#483D8B',
'darkslategray': '#2F4F4F',
'darkturquoise': '#00CED1',
'darkviolet': '#9400D3',
'deeppink': '#FF1493',
'deepskyblue': '#00BFFF',
'dimgray': '#696969',
'dodgerblue': '#1E90FF',
'firebrick': '#B22222',
'floralwhite': '#FFFAF0',
'forestgreen': '#228B22',
'gainsboro': '#DCDCDC',
'ghostwhite': '#F8F8FF',
'gold': '#FFD700',
'goldenrod': '#DAA520',
'gray': '#808080',
'green': '#008000',
'greenyellow': '#ADFF2F',
'honeydew': '#F0FFF0',
'hotpink': '#FF69B4',
'indianred': '#CD5C5C',
'indigo': '#4B0082',
'ivory': '#FFFFF0',
'khaki': '#F0E68C',
'lavender': '#E6E6FA',
'lavenderblush': '#FFF0F5',
'lawngreen': '#7CFC00',
'lemonchiffon': '#FFFACD',
'lightblue': '#ADD8E6',
'lightcoral': '#F08080',
'lightcyan': '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgray': '#D3D3D3',
'lightgreen': '#90EE90',
'lightpink': '#FFB6C1',
'lightsalmon': '#FFA07A',
'lightseagreen': '#20B2AA',
'lightskyblue': '#87CEFA',
'lightslategray': '#778899',
'lightsteelblue': '#B0C4DE',
'lightyellow': '#FFFFE0',
'lime': '#00FF00',
'limegreen': '#32CD32',
'linen': '#FAF0E6',
'magenta': '#FF00FF',
'maroon': '#800000',
'mediumaquamarine': '#66CDAA',
'mediumblue': '#0000CD',
'mediumorchid': '#BA55D3',
'mediumpurple': '#9370DB',
'mediumseagreen': '#3CB371',
'mediumslateblue': '#7B68EE',
'mediumspringgreen': '#00FA9A',
'mediumturquoise': '#48D1CC',
'mediumvioletred': '#C71585',
'midnightblue': '#191970',
'mintcream': '#F5FFFA',
'mistyrose': '#FFE4E1',
'moccasin': '#FFE4B5',
'navajowhite': '#FFDEAD',
'navy': '#000080',
'oldlace': '#FDF5E6',
'olive': '#808000',
'olivedrab': '#6B8E23',
'orange': '#FFA500',
'orangered': '#FF4500',
'orchid': '#DA70D6',
'palegoldenrod': '#EEE8AA',
'palegreen': '#98FB98',
'paleturquoise': '#AFEEEE',
'palevioletred': '#DB7093',
'papayawhip': '#FFEFD5',
'paraview_background': '#52576e',
'peachpuff': '#FFDAB9',
'peru': '#CD853F',
'pink': '#FFC0CB',
'plum': '#DDA0DD',
'powderblue': '#B0E0E6',
'purple': '#800080',
'raw_sienna': '#965434',
'rebeccapurple': '#663399',
'red': '#FF0000',
'rosybrown': '#BC8F8F',
'royalblue': '#4169E1',
'saddlebrown': '#8B4513',
'salmon': '#FA8072',
'sandybrown': '#F4A460',
'seagreen': '#2E8B57',
'seashell': '#FFF5EE',
'sienna': '#A0522D',
'silver': '#C0C0C0',
'skyblue': '#87CEEB',
'slateblue': '#6A5ACD',
'slategray': '#708090',
'snow': '#FFFAFA',
'springgreen': '#00FF7F',
'steelblue': '#4682B4',
'tan': '#D2B48C',
'teal': '#008080',
'thistle': '#D8BFD8',
'tomato': '#FF6347',
'turquoise': '#40E0D0',
'violet': '#EE82EE',
'wheat': '#F5DEB3',
'white': '#FFFFFF',
'whitesmoke': '#F5F5F5',
'yellow': '#FFFF00',
'yellowgreen': '#9ACD32',
'tab:blue': '#1f77b4',
'tab:orange': '#ff7f0e',
'tab:green': '#2ca02c',
'tab:red': '#d62728',
'tab:purple': '#9467bd',
'tab:brown': '#8c564b',
'tab:pink': '#e377c2',
'tab:gray': '#7f7f7f',
'tab:olive': '#bcbd22',
'tab:cyan': '#17becf',
}
color_names = {h.lower(): n for n, h in hexcolors.items()}
color_char_to_word = {
'b': 'blue',
'g': 'green',
'r': 'red',
'c': 'cyan',
'm': 'magenta',
'y': 'yellow',
'k': 'black',
'w': 'white',
}
color_synonyms = {
**color_char_to_word,
'aqua': 'cyan',
'darkgrey': 'darkgray',
'darkslategrey': 'darkslategray',
'dimgrey': 'dimgray',
'fuchsia': 'magenta',
'grey': 'gray',
'lightgrey': 'lightgray',
'lightslategrey': 'lightslategray',
'pv': 'paraview_background',
'paraview': 'paraview_background',
'slategrey': 'slategray',
}
matplotlib_default_colors = [
'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf',
]
COLOR_SCHEMES = {
"spectrum": {
"id": _vtk.vtkColorSeries.SPECTRUM,
"descr": "black, red, blue, green, purple, orange, brown",
},
"warm": {"id": _vtk.vtkColorSeries.WARM, "descr": "dark red → yellow"},
"cool": {"id": _vtk.vtkColorSeries.COOL, "descr": "green → blue → purple"},
"blues": {"id": _vtk.vtkColorSeries.BLUES, "descr": "Different shades of blue"},
"wild_flower": {"id": _vtk.vtkColorSeries.WILD_FLOWER, "descr": "blue → purple → pink"},
"citrus": {"id": _vtk.vtkColorSeries.CITRUS, "descr": "green → yellow → orange"},
"div_purple_orange11": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_11,
"descr": "dark brown → white → dark purple",
},
"div_purple_orange10": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_10,
"descr": "dark brown → white → dark purple",
},
"div_purple_orange9": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_9,
"descr": "brown → white → purple",
},
"div_purple_orange8": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_8,
"descr": "brown → white → purple",
},
"div_purple_orange7": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_7,
"descr": "brown → white → purple",
},
"div_purple_orange6": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_6,
"descr": "brown → white → purple",
},
"div_purple_orange5": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_5,
"descr": "orange → white → purple",
},
"div_purple_orange4": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_4,
"descr": "orange → white → purple",
},
"div_purple_orange3": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_PURPLE_ORANGE_3,
"descr": "orange → white → purple",
},
"div_spectral11": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_11,
"descr": "dark red → light yellow → dark blue",
},
"div_spectral10": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_10,
"descr": "dark red → light yellow → dark blue",
},
"div_spectral9": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_9,
"descr": "red → light yellow → blue",
},
"div_spectral8": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_8,
"descr": "red → light yellow → blue",
},
"div_spectral7": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_7,
"descr": "red → light yellow → blue",
},
"div_spectral6": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_6,
"descr": "red → light yellow → blue",
},
"div_spectral5": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_5,
"descr": "red → light yellow → blue",
},
"div_spectral4": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_4,
"descr": "red → light yellow → blue",
},
"div_spectral3": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_SPECTRAL_3,
"descr": "orange → light yellow → green",
},
"div_brown_blue_green11": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_11,
"descr": "dark brown → white → dark blue-green",
},
"div_brown_blue_green10": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_10,
"descr": "dark brown → white → dark blue-green",
},
"div_brown_blue_green9": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_9,
"descr": "brown → white → blue-green",
},
"div_brown_blue_green8": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_8,
"descr": "brown → white → blue-green",
},
"div_brown_blue_green7": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_7,
"descr": "brown → white → blue-green",
},
"div_brown_blue_green6": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_6,
"descr": "brown → white → blue-green",
},
"div_brown_blue_green5": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_5,
"descr": "brown → white → blue-green",
},
"div_brown_blue_green4": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_4,
"descr": "brown → white → blue-green",
},
"div_brown_blue_green3": {
"id": _vtk.vtkColorSeries.BREWER_DIVERGING_BROWN_BLUE_GREEN_3,
"descr": "brown → white → blue-green",
},
"seq_blue_green9": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_9,
"descr": "light blue → dark green",
},
"seq_blue_green8": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_8,
"descr": "light blue → dark green",
},
"seq_blue_green7": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_7,
"descr": "light blue → dark green",
},
"seq_blue_green6": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_6,
"descr": "light blue → green",
},
"seq_blue_green5": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_5,
"descr": "light blue → green",
},
"seq_blue_green4": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_4,
"descr": "light blue → green",
},
"seq_blue_green3": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_GREEN_3,
"descr": "light blue → green",
},
"seq_yellow_orange_brown9": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_9,
"descr": "light yellow → orange → dark brown",
},
"seq_yellow_orange_brown8": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_8,
"descr": "light yellow → orange → brown",
},
"seq_yellow_orange_brown7": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_7,
"descr": "light yellow → orange → brown",
},
"seq_yellow_orange_brown6": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_6,
"descr": "light yellow → orange → brown",
},
"seq_yellow_orange_brown5": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_5,
"descr": "light yellow → orange → brown",
},
"seq_yellow_orange_brown4": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_4,
"descr": "light yellow → orange",
},
"seq_yellow_orange_brown3": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_3,
"descr": "light yellow → orange",
},
"seq_blue_purple9": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_9,
"descr": "light blue → dark purple",
},
"seq_blue_purple8": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_8,
"descr": "light blue → purple",
},
"seq_blue_purple7": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_7,
"descr": "light blue → purple",
},
"seq_blue_purple6": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_6,
"descr": "light blue → purple",
},
"seq_blue_purple5": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_5,
"descr": "light blue → purple",
},
"seq_blue_purple4": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_4,
"descr": "light blue → purple",
},
"seq_blue_purple3": {
"id": _vtk.vtkColorSeries.BREWER_SEQUENTIAL_BLUE_PURPLE_3,
"descr": "light blue → purple",
},
"qual_accent": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_ACCENT,
"descr": "pastel green, pastel purple, pastel orange, pastel yellow, blue, pink, brown, gray",
},
"qual_dark2": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_DARK2,
"descr": "darker shade of qual_set2",
},
"qual_set3": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET3,
"descr": "pastel colors: blue green, light yellow, dark purple, red, blue, orange, green, pink, gray, purple, light green, yellow",
},
"qual_set2": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET2,
"descr": "blue green, orange, purple, pink, green, yellow, brown, gray",
},
"qual_set1": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_SET1,
"descr": "red, blue, green, purple, orange, yellow, brown, pink, gray",
},
"qual_pastel2": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_PASTEL2,
"descr": "pastel shade of qual_set2",
},
"qual_pastel1": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_PASTEL1,
"descr": "pastel shade of qual_set1",
},
"qual_paired": {
"id": _vtk.vtkColorSeries.BREWER_QUALITATIVE_PAIRED,
"descr": "light blue, blue, light green, green, light red, red, light orange, orange, light purple, purple, light yellow",
},
"custom": {"id": _vtk.vtkColorSeries.CUSTOM, "descr": None},
}
SCHEME_NAMES = {
scheme_info["id"]: scheme_name for scheme_name, scheme_info in COLOR_SCHEMES.items()
}
class Color:
"""Helper class to convert between different color representations used in the pyvista library.
Many pyvista methods accept :data:`ColorLike` parameters. This helper class
is used to convert such parameters to the necessary format, used by
underlying (VTK) methods. Any color name (``str``), hex string (``str``)
or RGB(A) sequence (``tuple``, ``list`` or ``numpy.ndarray`` of ``int``
or ``float``) is considered a :data:`ColorLike` parameter and can be converted
by this class.
See :attr:`Color.name` for a list of supported color names.
Parameters
----------
color : ColorLike, optional
Either a string, RGB sequence, RGBA sequence, or hex color string.
RGB(A) sequences should either be provided as floats between 0 and 1
or as ints between 0 and 255. Hex color strings can contain optional
``'#'`` or ``'0x'`` prefixes. If no opacity is provided, the
``default_opacity`` will be used. If ``color`` is ``None``, the
``default_color`` is used instead.
The following examples all denote the color 'white':
* ``'white'``
* ``'w'``
* ``[1.0, 1.0, 1.0]``
* ``[255, 255, 255, 255]``
* ``'#FFFFFF'``
opacity : int | float | str, optional
Opacity of the represented color. Overrides any opacity associated
with the provided ``color``. Allowed opacities are floats between 0
and 1, ints between 0 and 255 or hexadecimal strings of length 2
(plus the length of the optional prefix).
The following examples all denote a fully opaque color:
* ``1.0``
* ``255``
* ``'#ff'``
default_color : ColorLike, optional
Default color to use when ``color`` is ``None``. If this value is
``None``, then defaults to the global theme color. Format is
identical to ``color``.
default_opacity : int | float | str, optional
Default opacity of the represented color. Used when ``color``
does not specify an opacity and ``opacity`` is ``None``. Format
is identical to ``opacity``.
Notes
-----
The internally used representation is an integer RGBA sequence (values
between 0 and 255). This might however change in future releases.
.. raw:: html
<details><summary>Refer to the table below for a list of supported colors.</summary>
.. include:: ../color_table/color_table.rst
.. raw:: html
</details>
Examples
--------
Create a transparent green color using a color name, float RGBA sequence,
integer RGBA sequence and RGBA hexadecimal string.
>>> import pyvista as pv
>>> pv.Color("green", opacity=0.5)
Color(name='green', hex='#00800080', opacity=128)
>>> pv.Color([0.0, 0.5, 0.0, 0.5])
Color(name='green', hex='#00800080', opacity=128)
>>> pv.Color([0, 128, 0, 128])
Color(name='green', hex='#00800080', opacity=128)
>>> pv.Color("#00800080")
Color(name='green', hex='#00800080', opacity=128)
"""
# Supported names for each color channel.
CHANNEL_NAMES = (
{'red', 'r'}, # 0
{'green', 'g'}, # 1
{'blue', 'b'}, # 2
{'alpha', 'a', 'opacity'}, # 3
)
def __init__(
self,
color: ColorLike | None = None,
opacity: float | str | None = None,
default_color: ColorLike | None = None,
default_opacity: float | str = 255,
):
"""Initialize new instance."""
self._red, self._green, self._blue, self._opacity = 0, 0, 0, 0
self._opacity = self.convert_color_channel(default_opacity)
self._name = None
# Use default color if no color is provided
if color is None:
color = pyvista.global_theme.color if default_color is None else default_color
try:
if isinstance(color, Color):
# Create copy of color instance
self._red, self._green, self._blue, self._opacity = color.int_rgba
elif isinstance(color, str):
# From named color or hex string
self._from_str(color)
elif isinstance(color, dict):
# From dictionary
self._from_dict(color)
elif isinstance(color, (list, tuple, np.ndarray)):
# From RGB(A) sequence
self._from_rgba(color)
elif isinstance(color, _vtk.vtkColor3ub):
# From vtkColor3ub instance (can be unpacked as rgb tuple)
self._from_rgba(color)
else:
raise ValueError(f"Unsupported color type: {type(color)}")
self._name = color_names.get(self.hex_rgb, None)
except ValueError as e:
raise ValueError(
"\n"
f"\tInvalid color input: ({color})\n"
"\tMust be a string, rgb(a) sequence, or hex color string. For example:\n"
"\t\tcolor='white'\n"
"\t\tcolor='w'\n"
"\t\tcolor=[1.0, 1.0, 1.0]\n"
"\t\tcolor=[255, 255, 255]\n"
"\t\tcolor='#FFFFFF'",
) from e
# Overwrite opacity if it is provided
try:
if opacity is not None:
self._opacity = self.convert_color_channel(opacity)
except ValueError as e:
raise ValueError(
"\n"
f"\tInvalid opacity input: ({opacity})"
"\tMust be an integer, float or string. For example:\n"
"\t\topacity='1.0'\n"
"\t\topacity='255'\n"
"\t\topacity='#FF'",
) from e
@staticmethod
def strip_hex_prefix(h: str) -> str:
"""Strip any ``'#'`` or ``'0x'`` prefix from a hexadecimal string.
Parameters
----------
h : str
Hexadecimal string to strip.
Returns
-------
str
Stripped hexadecimal string.
"""
h = h.lstrip('#')
if h.startswith('0x'):
h = h[2:]
return h
@staticmethod
def convert_color_channel(
val: float | np.floating[Any] | str,
) -> int:
"""Convert the given color channel value to the integer representation.
Parameters
----------
val : int | float | str
Color channel value to convert. Supported input values are a
hex string of length 2 (``'00'`` to ``'ff'``) with an optional
prefix (``'#'`` or ``'0x'``), a float (``0.0`` to ``1.0``) or
an integer (``0`` to ``255``).
Returns
-------
int
Color channel value in the integer representation (values between
``0`` and ``255``).
"""
if isinstance(val, str):
# From hexadecimal value
val = int(Color.strip_hex_prefix(val), 16)
elif np.issubdtype(np.asarray(val).dtype, np.floating) and np.ndim(val) == 0:
# From float
val = int(round(255 * val))
if (
np.issubdtype(np.asarray(val).dtype, np.integer)
and np.size(val) == 1
and 0 <= val <= 255
):
# From integer
return int(val)
else:
raise ValueError(f"Unsupported color channel value provided: {val}")
def _from_rgba(self, rgba):
"""Construct color from an RGB(A) sequence."""
arg = rgba
if len(rgba) == 3:
# Keep using current opacity if it is not provided.
rgba = [*rgba, self._opacity]
try:
if len(rgba) != 4:
raise ValueError("Invalid length for RGBA sequence.")
self._red, self._green, self._blue, self._opacity = (
self.convert_color_channel(c) for c in rgba
)
except ValueError:
raise ValueError(f"Invalid RGB(A) sequence: {arg}") from None
def _from_dict(self, dct):
"""Construct color from an RGB(A) dictionary."""
# Get any of the keys associated with each color channel (or None).
rgba = [
next((dct[key] for key in cnames if key in dct), None) for cnames in self.CHANNEL_NAMES
]
self._from_rgba(rgba)
def _from_hex(self, h):
"""Construct color from a hex string."""
arg = h
h = self.strip_hex_prefix(h)
try:
self._from_rgba([self.convert_color_channel(h[i : i + 2]) for i in range(0, len(h), 2)])
except ValueError:
raise ValueError(f"Invalid hex string: {arg}") from None
def _from_str(self, n: str):
"""Construct color from a name or hex string."""
arg = n
n = n.lower()
if n in color_synonyms:
# Synonym of registered color name
# Convert from synonym to full hex
n = color_synonyms[n]
self._from_hex(hexcolors[n])
elif n in hexcolors:
# Color name
self._from_hex(hexcolors[n])
else:
# Otherwise, try conversion to hex
try:
self._from_hex(n)
except ValueError:
raise ValueError(f"Invalid color name or hex string: {arg}") from None
@property
def int_rgba(self) -> tuple[int, int, int, int]: # numpydoc ignore=RT01
"""Get the color value as an RGBA integer tuple.
Examples
--------
Create a blue color with half opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", opacity=128)
>>> c
Color(name='blue', hex='#0000ff80', opacity=128)
>>> c.int_rgba
(0, 0, 255, 128)
Create a transparent red color using an integer RGBA sequence.
>>> c = pv.Color([255, 0, 0, 64])
>>> c
Color(name='red', hex='#ff000040', opacity=64)
>>> c.int_rgba
(255, 0, 0, 64)
"""
return self._red, self._green, self._blue, self._opacity
@property
def int_rgb(self) -> tuple[int, int, int]: # numpydoc ignore=RT01
"""Get the color value as an RGB integer tuple.
Examples
--------
Create a blue color with half opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", opacity=128)
>>> c
Color(name='blue', hex='#0000ff80', opacity=128)
>>> c.int_rgb
(0, 0, 255)
Create a red color using an integer RGB sequence.
>>> c = pv.Color([255, 0, 0])
>>> c
Color(name='red', hex='#ff0000ff', opacity=255)
>>> c.int_rgb
(255, 0, 0)
"""
return self.int_rgba[:3]
@property
def float_rgba(self) -> tuple[float, float, float, float]: # numpydoc ignore=RT01
"""Get the color value as an RGBA float tuple.
Examples
--------
Create a blue color with custom opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", opacity=0.6)
>>> c
Color(name='blue', hex='#0000ff99', opacity=153)
>>> c.float_rgba
(0.0, 0.0, 1.0, 0.6)
Create a transparent red color using a float RGBA sequence.
>>> c = pv.Color([1.0, 0.0, 0.0, 0.2])
>>> c
Color(name='red', hex='#ff000033', opacity=51)
>>> c.float_rgba
(1.0, 0.0, 0.0, 0.2)
"""
return self._red / 255.0, self._green / 255.0, self._blue / 255.0, self._opacity / 255.0
@property
def float_rgb(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
"""Get the color value as an RGB float tuple.
Examples
--------
Create a blue color with custom opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", default_opacity=0.6)
>>> c
Color(name='blue', hex='#0000ff99', opacity=153)
>>> c.float_rgb
(0.0, 0.0, 1.0)
Create a red color using a float RGB sequence.
>>> c = pv.Color([1.0, 0.0, 0.0])
>>> c
Color(name='red', hex='#ff0000ff', opacity=255)
>>> c.float_rgb
(1.0, 0.0, 0.0)
"""
return self.float_rgba[:3]
@property
def hex_rgba(self) -> str: # numpydoc ignore=RT01
"""Get the color value as an RGBA hexadecimal value.
Examples
--------
Create a blue color with half opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", default_opacity="#80")
>>> c
Color(name='blue', hex='#0000ff80', opacity=128)
>>> c.hex_rgba
'#0000ff80'
Create a transparent red color using an RGBA hexadecimal value.
>>> c = pv.Color("0xff000040")
>>> c
Color(name='red', hex='#ff000040', opacity=64)
>>> c.hex_rgba
'#ff000040'
"""
return '#' + ''.join(
f"{c:0>2x}" for c in (self._red, self._green, self._blue, self._opacity)
)
@property
def hex_rgb(self) -> str: # numpydoc ignore=RT01
"""Get the color value as an RGB hexadecimal value.
Examples
--------
Create a blue color with half opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", default_opacity="#80")
>>> c
Color(name='blue', hex='#0000ff80', opacity=128)
>>> c.hex_rgb
'#0000ff'
Create a red color using an RGB hexadecimal value.
>>> c = pv.Color("0xff0000")
>>> c
Color(name='red', hex='#ff0000ff', opacity=255)
>>> c.hex_rgb
'#ff0000'
"""
return self.hex_rgba[:-2]
@property
def name(self) -> str | None: # numpydoc ignore=RT01
"""Get the color name.
Returns
-------
str | None
The color name, in case this color has a name; otherwise ``None``.
Notes
-----
Refer to the table below for a list of supported colors.
.. include:: ../colors.rst
Examples
--------
Create a blue color with half opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", default_opacity=0.5)
>>> c
Color(name='blue', hex='#0000ff80', opacity=128)
"""
return self._name
@property
def vtk_c3ub(self) -> _vtk.vtkColor3ub: # numpydoc ignore=RT01
"""Get the color value as a VTK Color3ub instance.
Examples
--------
Create a blue color with half opacity.
>>> import pyvista as pv
>>> c = pv.Color("blue", default_opacity=0.5)
>>> c
Color(name='blue', hex='#0000ff80', opacity=128)
>>> c.vtk_c3ub
vtkmodules.vtkCommonDataModel.vtkColor3ub([0, 0, 255])
"""
return _vtk.vtkColor3ub(self._red, self._green, self._blue)
def linear_to_srgb(self):
"""Convert from linear color values to sRGB color values.
Returns
-------
Color
A new ``Color`` instance with sRGB color values.
"""
rgba = np.array(self.float_rgba)
mask = rgba < 0.0031308
rgba[mask] *= 12.92
rgba[~mask] = 1.055 * rgba[~mask] ** (1 / 2.4) - 0.055
return Color(rgba)
def srgb_to_linear(self):
"""Convert from sRGB color values to linear color values.
Returns
-------
Color
A new ``Color`` instance with linear color values.
"""
rgba = np.array(self.float_rgba)
mask = rgba < 0.04045
rgba[mask] /= 12.92
rgba[~mask] = ((rgba[~mask] + 0.055) / 1.055) ** 2.4
return Color(rgba)
@classmethod
def from_dict(cls, dict_):
"""Construct from dictionary for JSON deserialization."""
return Color(dict_)
def to_dict(self):
"""Convert to dictionary for JSON serialization."""
return {'r': self._red, 'g': self._green, 'b': self._blue, 'a': self._opacity}
@property
def opacity(self): # numpydoc ignore=RT01
"""Return the opacity of this color in the range of ``(0-255)``.
Examples
--------
>>> import pyvista as pv
>>> color = pv.Color('r', opacity=0.5)
>>> color.opacity
128
>>> color
Color(name='red', hex='#ff000080', opacity=128)
"""
return self._opacity
def __eq__(self, other):
"""Equality comparison."""
try:
return self.int_rgba == Color(other).int_rgba
except ValueError: # pragma: no cover
return NotImplemented
def __hash__(self): # pragma: no cover
"""Hash calculation."""
return hash((self._red, self._green, self._blue, self._opacity))
def __getitem__(self, item):
"""Support indexing the float RGBA representation for backward compatibility."""
if not isinstance(item, (str, slice, int, np.integer)):
raise TypeError("Invalid index specified, only strings and integers are supported.")
if isinstance(item, str):
for i, cnames in enumerate(self.CHANNEL_NAMES):
if item in cnames:
item = i
break
else:
raise ValueError(f"Invalid string index {item!r}.")
return self.float_rgba[item]
def __iter__(self):
"""Support iteration over the float RGBA representation for backward compatibility."""
return iter(self.float_rgba)
def __repr__(self): # pragma: no cover
"""Human readable representation."""
kwargs = f"hex={self.hex_rgba!r}, opacity={self.opacity}"
if self._name is not None:
kwargs = f"name={self._name!r}, " + kwargs
return f"Color({kwargs})"
PARAVIEW_BACKGROUND = Color('paraview').float_rgb # [82, 87, 110] / 255
def get_cmap_safe(cmap):
"""
Fetch a colormap by name from matplotlib, colorcet, or cmocean.
Parameters
----------
cmap : str or list of str
Name of the colormap to fetch. If the input is a list of strings,
it will create a ``ListedColormap`` with the input list.
Returns
-------
matplotlib.colors.Colormap
The requested colormap if available.
Raises
------
ValueError
If the input colormap name is not valid.
TypeError
If the input is a list of items that are not strings.
"""
if isinstance(cmap, str):
# check if this colormap has been mapped between ipygany
if cmap in IPYGANY_MAP:
cmap = IPYGANY_MAP[cmap]
# Try colorcet first
if has_module('colorcet'):
import colorcet
try:
return colorcet.cm[cmap]
except KeyError:
pass
# Try cmocean second
if has_module('cmocean'):
import cmocean
try:
return getattr(cmocean.cm, cmap)
except AttributeError:
pass
if not isinstance(cmap, colors.Colormap):
if inspect.ismodule(colormaps): # pragma: no cover
# Backwards compatibility with matplotlib<3.5.0
if not hasattr(colormaps, cmap):
raise ValueError(f'Invalid colormap "{cmap}"')
cmap = getattr(colormaps, cmap)
else:
try:
cmap = colormaps[cmap]
except KeyError:
raise ValueError(f'Invalid colormap "{cmap}"') from None
elif isinstance(cmap, list):
for item in cmap:
if not isinstance(item, str):
raise TypeError('When inputting a list as a cmap, each item should be a string.')
cmap = ListedColormap(cmap)
return cmap
def get_default_cycler():
"""Return the default color cycler (matches matplotlib's default).
Returns
-------
cycler.Cycler
A cycler object for color that matches matplotlib's default colors.
"""
return cycler('color', matplotlib_default_colors)
def get_hexcolors_cycler():
"""Return a color cycler for all of the available hexcolors.
See ``pyvista.plotting.colors.hexcolors``.
Returns
-------
cycler.Cycler
A cycler object for color using all the available hexcolors from
``pyvista.plotting.colors.hexcolors``.
"""
return cycler('color', hexcolors.keys())
def get_matplotlib_theme_cycler():
"""
Return the color cycler of the current matplotlib theme.
Returns
-------
cycler.Cycler
Color cycler of the current matplotlib theme.
"""
return plt.rcParams['axes.prop_cycle']
def color_scheme_to_cycler(scheme):
"""Convert a color scheme to a Cycler.
Parameters
----------
scheme : str, int, or _vtk.vtkColorSeries
Color scheme to be converted. If a string, it should correspond to a
valid color scheme name (e.g., 'viridis'). If an integer, it should
correspond to a valid color scheme ID. If an instance of
`_vtk.vtkColorSeries`, it should be a valid color series.
Returns
-------
cycler.Cycler
A Cycler object with the color scheme.
Raises
------
ValueError
If the provided `scheme` is not a valid color scheme.
"""
if not isinstance(scheme, _vtk.vtkColorSeries):
series = _vtk.vtkColorSeries()
if isinstance(scheme, str):
series.SetColorScheme(COLOR_SCHEMES.get(scheme.lower())["id"])
elif isinstance(scheme, int):
series.SetColorScheme(scheme)
else:
raise ValueError(f'Color scheme not understood: {scheme}')
else:
series = scheme
colors = (series.GetColor(i) for i in range(series.GetNumberOfColors()))
return cycler('color', colors)
def get_cycler(color_cycler):
"""Return a color cycler based on the input value.
Parameters
----------
color_cycler : str, list, tuple, or Cycler
Specifies the desired color cycler. The value must be one of the following:
- A list or tuple of color-like objects
- A Cycler object with color-like objects
- One of the following string values:
- ``'default'``: Use the default color cycler (matches matplotlib's default)
- ``'matplotlib'``: Dynamically get matplotlib's current theme's color cycler.
- ``'all'``: Cycle through all available colors in ``pyvista.plotting.colors.hexcolors``
- A named color scheme from ``pyvista.plotting.colors.COLOR_SCHEMES``
Returns
-------
Cycler
The color cycler corresponding to the input value.
Raises
------
ValueError
Raised if the input is a string not found in named color schemes.
TypeError
Raised if the input is of an unsupported type.
"""
if color_cycler is None:
return None
elif isinstance(color_cycler, str):
if color_cycler == 'default':
return get_default_cycler()
elif color_cycler == 'matplotlib':
return get_matplotlib_theme_cycler()
elif color_cycler == 'all':
return get_hexcolors_cycler()
elif color_cycler in COLOR_SCHEMES:
return color_scheme_to_cycler(color_cycler)
else:
raise ValueError(f'color cycler of name `{color_cycler}` not found.')
elif isinstance(color_cycler, (tuple, list)):
return cycler('color', color_cycler)
elif isinstance(color_cycler, Cycler):
return color_cycler
else:
raise TypeError(f'color cycler of type {type(color_cycler)} not supported.')
|