FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
matplotlib/lib/matplotlib/colors.py at v3.11.2 · matplotlib/matplotlib · GitHub
matplotlib/lib/matplotlib/colors.py at v3.11.2 · matplotlib/matplotlib · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
matplotlib
/
matplotlib
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
8.5k
Star
23.3k
Code
Issues
1.1k
Pull requests
430
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
colors.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
4282 lines (3613 loc) · 155 KB
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
colors.py
Copy path
File metadata and controls
4282 lines (3613 loc) · 155 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
A module for converting numbers or color arguments to *RGB* or *RGBA*.
*RGB* and *RGBA* are sequences of, respectively, 3 or 4 floats in the
range 0-1.
This module includes functions and classes for color specification conversions,
and for mapping numbers to colors in a 1-D array of colors called a colormap.
Mapping data onto colors using a colormap typically involves two steps: a data
array is first mapped onto the range 0-1 using a subclass of `Normalize`,
then this number is mapped to a color using a subclass of `Colormap`. Two
subclasses of `Colormap` provided here: `LinearSegmentedColormap`, which uses
piecewise-linear interpolation to define colormaps, and `ListedColormap`, which
makes a colormap from a list of colors.
.. seealso::
:ref:`colormap-manipulation` for examples of how to
make colormaps and
:ref:`colormaps` for a list of built-in colormaps.
:ref:`colormapnorms` for more details about data
normalization
More colormaps are available at palettable_.
The module also provides functions for checking whether an object can be
interpreted as a color (`is_color_like`), for converting such an object
to an RGBA tuple (`to_rgba`) or to an HTML-like hex string in the
"#rrggbb" format (`to_hex`), and a sequence of colors to an (n, 4)
RGBA array (`to_rgba_array`). Caching is used for efficiency.
Colors that Matplotlib recognizes are listed at
:ref:`colors_def`.
.. _palettable: https://jiffyclub.github.io/palettable/
.. _xkcd color survey: https://xkcd.com/color/rgb/
"""
import
base64
from
collections
.
abc
import
Sequence
,
Mapping
from
abc
import
ABC
,
abstractmethod
import
functools
import
importlib
import
inspect
import
io
import
itertools
from
numbers
import
Real
import
re
from
PIL
import
Image
from
PIL
.
PngImagePlugin
import
PngInfo
import
matplotlib
as
mpl
import
numpy
as
np
from
matplotlib
import
_api
,
_cm
,
cbook
,
scale
from
.
_color_data
import
BASE_COLORS
,
TABLEAU_COLORS
,
CSS4_COLORS
,
XKCD_COLORS
class
_ColorMapping
(
dict
):
def
__init__
(
self
,
mapping
):
super
().
__init__
(
mapping
)
self
.
cache
=
{}
def
__setitem__
(
self
,
key
,
value
):
super
().
__setitem__
(
key
,
value
)
self
.
cache
.
clear
()
def
__delitem__
(
self
,
key
):
super
().
__delitem__
(
key
)
self
.
cache
.
clear
()
_colors_full_map
=
{}
# Set by reverse priority order.
_colors_full_map
.
update
(
XKCD_COLORS
)
_colors_full_map
.
update
({
k
.
replace
(
'grey'
,
'gray'
):
v
for
k
,
v
in
XKCD_COLORS
.
items
()
if
'grey'
in
k
})
_colors_full_map
.
update
(
CSS4_COLORS
)
_colors_full_map
.
update
(
TABLEAU_COLORS
)
_colors_full_map
.
update
({
k
.
replace
(
'gray'
,
'grey'
):
v
for
k
,
v
in
TABLEAU_COLORS
.
items
()
if
'gray'
in
k
})
_colors_full_map
.
update
(
BASE_COLORS
)
_colors_full_map
=
_ColorMapping
(
_colors_full_map
)
_REPR_PNG_SIZE
=
(
512
,
64
)
_BIVAR_REPR_PNG_SIZE
=
256
def
get_named_colors_mapping
():
"""Return the global mapping of names to named colors."""
return
_colors_full_map
class
ColorSequenceRegistry
(
Mapping
):
r"""
Container for sequences of colors that are known to Matplotlib by name.
The universal registry instance is `matplotlib.color_sequences`. There
should be no need for users to instantiate `.ColorSequenceRegistry`
themselves.
Read access uses a dict-like interface mapping names to lists of colors::
import matplotlib as mpl
colors = mpl.color_sequences['tab10']
For a list of built in color sequences, see :doc:`/gallery/color/color_sequences`.
The returned lists are copies, so that their modification does not change
the global definition of the color sequence.
Additional color sequences can be added via
`.ColorSequenceRegistry.register`::
mpl.color_sequences.register('rgb', ['r', 'g', 'b'])
"""
_BUILTIN_COLOR_SEQUENCES
=
{
'tab10'
:
_cm
.
_tab10_data
,
'tab20'
:
_cm
.
_tab20_data
,
'tab20b'
:
_cm
.
_tab20b_data
,
'tab20c'
:
_cm
.
_tab20c_data
,
'Pastel1'
:
_cm
.
_Pastel1_data
,
'Pastel2'
:
_cm
.
_Pastel2_data
,
'Paired'
:
_cm
.
_Paired_data
,
'Accent'
:
_cm
.
_Accent_data
,
'okabe_ito'
:
_cm
.
_okabe_ito_data
,
'Dark2'
:
_cm
.
_Dark2_data
,
'Set1'
:
_cm
.
_Set1_data
,
'Set2'
:
_cm
.
_Set2_data
,
'Set3'
:
_cm
.
_Set3_data
,
'petroff6'
:
_cm
.
_petroff6_data
,
'petroff8'
:
_cm
.
_petroff8_data
,
'petroff10'
:
_cm
.
_petroff10_data
,
}
def
__init__
(
self
):
self
.
_color_sequences
=
{
**
self
.
_BUILTIN_COLOR_SEQUENCES
}
def
__getitem__
(
self
,
item
):
return
list
(
_api
.
getitem_checked
(
self
.
_color_sequences
,
_error_cls
=
KeyError
,
sequence_name
=
item
))
def
__iter__
(
self
):
return
iter
(
self
.
_color_sequences
)
def
__len__
(
self
):
return
len
(
self
.
_color_sequences
)
def
__str__
(
self
):
return
(
'ColorSequenceRegistry; available colormaps:
\n
'
+
', '
.
join
(
f"'
{
name
}
'"
for
name
in
self
))
def
register
(
self
,
name
,
color_list
):
"""
Register a new color sequence.
The color sequence registry stores a copy of the given *color_list*, so
that future changes to the original list do not affect the registered
color sequence. Think of this as the registry taking a snapshot
of *color_list* at registration.
Parameters
----------
name : str
The name for the color sequence.
color_list : list of :mpltype:`color`
An iterable returning valid Matplotlib colors when iterating over.
Note however that the returned color sequence will always be a
list regardless of the input type.
"""
if
name
in
self
.
_BUILTIN_COLOR_SEQUENCES
:
raise
ValueError
(
f"
{
name
!r
}
is a reserved name for a builtin "
"color sequence"
)
color_list
=
list
(
color_list
)
# force copy and coerce type to list
for
color
in
color_list
:
try
:
to_rgba
(
color
)
except
ValueError
:
raise
ValueError
(
f"
{
color
!r
}
is not a valid color specification"
)
self
.
_color_sequences
[
name
]
=
color_list
def
unregister
(
self
,
name
):
"""
Remove a sequence from the registry.
You cannot remove built-in color sequences.
If the name is not registered, returns with no error.
"""
if
name
in
self
.
_BUILTIN_COLOR_SEQUENCES
:
raise
ValueError
(
f"Cannot unregister builtin color sequence
{
name
!r
}
"
)
self
.
_color_sequences
.
pop
(
name
,
None
)
_color_sequences
=
ColorSequenceRegistry
()
def
_sanitize_extrema
(
ex
):
if
ex
is
None
:
return
ex
try
:
ret
=
ex
.
item
()
except
AttributeError
:
ret
=
float
(
ex
)
return
ret
_nth_color_re
=
re
.
compile
(
r"\AC[0-9]+\Z"
)
def
_is_nth_color
(
c
):
"""Return whether *c* can be interpreted as an item in the color cycle."""
return
isinstance
(
c
,
str
)
and
_nth_color_re
.
match
(
c
)
def
is_color_like
(
c
):
"""Return whether *c* as a valid Matplotlib :mpltype:`color` specifier."""
# Special-case nth color syntax because it cannot be parsed during setup.
if
_is_nth_color
(
c
):
return
True
try
:
to_rgba
(
c
)
except
(
TypeError
,
ValueError
):
return
False
else
:
return
True
def
_has_alpha_channel
(
c
):
"""
Return whether *c* is a color with an alpha channel.
If *c* is not a valid color specifier, then the result is undefined.
"""
# The following logic uses the assumption that c is a valid color spec.
# For speed and simplicity, we intentionally don't care about other inputs.
# Anything can happen with them.
# if c is a hex, it has an alpha channel when it has 4 (or 8) digits after '#'
if
isinstance
(
c
,
str
):
if
c
[
0
]
==
'#'
and
(
len
(
c
)
==
5
or
len
(
c
)
==
9
):
# example: '#fff8' or '#0f0f0f80'
return
True
else
:
# if c isn't a string, it can be an RGB(A) or a color-alpha tuple
# if it has length 4, it has an alpha channel
if
len
(
c
)
==
4
:
# example: [0.5, 0.5, 0.5, 0.5]
return
True
# if it has length 2, it's a color/alpha tuple
# if the second element isn't None or the first element has length = 4
if
len
(
c
)
==
2
and
(
c
[
1
]
is
not
None
or
_has_alpha_channel
(
c
[
0
])):
# example: ([0.5, 0.5, 0.5, 0.5], None) or ('r', 0.5)
return
True
# otherwise it doesn't have an alpha channel
return
False
def
_check_color_like
(
**
kwargs
):
"""
For each *key, value* pair in *kwargs*, check that *value* is color-like.
"""
for
k
,
v
in
kwargs
.
items
():
if
not
is_color_like
(
v
):
raise
ValueError
(
f"
{
v
!r
}
is not a valid value for
{
k
}
: supported inputs are "
f"(r, g, b) and (r, g, b, a) 0-1 float tuples; "
f"'#rrggbb', '#rrggbbaa', '#rgb', '#rgba' strings; "
f"named color strings; "
f"string reprs of 0-1 floats for grayscale values; "
f"'C0', 'C1', ... strings for colors of the color cycle; "
f"and pairs combining one of the above with an alpha value"
)
def
same_color
(
c1
,
c2
):
"""
Return whether the colors *c1* and *c2* are the same.
Parameters
----------
c1, c2 : :mpltype:`color` or list of :mpltype:`color` or RGB(A) array
If passing multiple colors, *c1* and *c2* must be of the same length. RGB(A)
arrays must be of shape (ncolors, 3) or (ncolors, 4).
Returns
-------
bool
"""
c1
=
to_rgba_array
(
c1
)
c2
=
to_rgba_array
(
c2
)
n1
=
max
(
c1
.
shape
[
0
],
1
)
# 'none' results in shape (0, 4), but is 1-elem
n2
=
max
(
c2
.
shape
[
0
],
1
)
# 'none' results in shape (0, 4), but is 1-elem
if
n1
!=
n2
:
raise
ValueError
(
'Different number of elements passed.'
)
# The following shape test is needed to correctly handle comparisons with
# 'none', which results in a shape (0, 4) array and thus cannot be tested
# via value comparison.
return
c1
.
shape
==
c2
.
shape
and
(
c1
==
c2
).
all
()
def
to_rgba
(
c
,
alpha
=
None
):
"""
Convert *c* to an RGBA color.
Parameters
----------
c : :mpltype:`color` or ``np.ma.masked``
alpha : float, optional
If *alpha* is given, force the alpha value of the returned RGBA tuple
to *alpha*.
If None, the alpha value from *c* is used. If *c* does not have an
alpha channel, then alpha defaults to 1.
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
which always maps to ``(0, 0, 0, 0)``.
Returns
-------
tuple
Tuple of floats ``(r, g, b, a)``, where each channel (red, green, blue,
alpha) can assume values between 0 and 1.
"""
if
isinstance
(
c
,
tuple
)
and
len
(
c
)
==
2
:
if
alpha
is
None
:
c
,
alpha
=
c
else
:
c
=
c
[
0
]
# Special-case nth color syntax because it should not be cached.
if
_is_nth_color
(
c
):
prop_cycler
=
mpl
.
rcParams
[
'axes.prop_cycle'
]
colors
=
prop_cycler
.
by_key
().
get
(
'color'
, [
'k'
])
c
=
colors
[
int
(
c
[
1
:])
%
len
(
colors
)]
try
:
rgba
=
_colors_full_map
.
cache
[
c
,
alpha
]
except
(
KeyError
,
TypeError
):
# Not in cache, or unhashable.
rgba
=
None
if
rgba
is
None
:
# Suppress exception chaining of cache lookup failure.
rgba
=
_to_rgba_no_colorcycle
(
c
,
alpha
)
try
:
_colors_full_map
.
cache
[
c
,
alpha
]
=
rgba
except
TypeError
:
pass
return
rgba
def
_to_rgba_no_colorcycle
(
c
,
alpha
=
None
):
"""
Convert *c* to an RGBA color, with no support for color-cycle syntax.
If *alpha* is given, force the alpha value of the returned RGBA tuple
to *alpha*. Otherwise, the alpha value from *c* is used, if it has alpha
information, or defaults to 1.
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
which always maps to ``(0, 0, 0, 0)``.
"""
if
alpha
is
not
None
and
not
0
<=
alpha
<=
1
:
raise
ValueError
(
"'alpha' must be between 0 and 1, inclusive"
)
orig_c
=
c
if
c
is
np
.
ma
.
masked
:
return
(
0.
,
0.
,
0.
,
0.
)
if
isinstance
(
c
,
str
):
if
c
.
lower
()
==
"none"
:
return
(
0.
,
0.
,
0.
,
0.
)
# Named color.
try
:
# This may turn c into a non-string, so we check again below.
c
=
_colors_full_map
[
c
]
except
KeyError
:
if
len
(
c
)
!=
1
:
try
:
c
=
_colors_full_map
[
c
.
lower
()]
except
KeyError
:
pass
if
isinstance
(
c
,
str
):
if
re
.
fullmatch
(
"#[a-fA-F0-9]+"
,
c
):
if
len
(
c
)
==
7
:
# #rrggbb hex format.
return
(
*
[
n
/
0xff
for
n
in
bytes
.
fromhex
(
c
[
1
:])],
alpha
if
alpha
is
not
None
else
1.
)
elif
len
(
c
)
==
4
:
# #rgb hex format, shorthand for #rrggbb.
return
(
*
[
int
(
n
,
16
)
/
0xf
for
n
in
c
[
1
:]],
alpha
if
alpha
is
not
None
else
1.
)
elif
len
(
c
)
==
9
:
# #rrggbbaa hex format.
color
=
[
n
/
0xff
for
n
in
bytes
.
fromhex
(
c
[
1
:])]
if
alpha
is
not
None
:
color
[
-
1
]
=
alpha
return
tuple
(
color
)
elif
len
(
c
)
==
5
:
# #rgba hex format, shorthand for #rrggbbaa.
color
=
[
int
(
n
,
16
)
/
0xf
for
n
in
c
[
1
:]]
if
alpha
is
not
None
:
color
[
-
1
]
=
alpha
return
tuple
(
color
)
else
:
raise
ValueError
(
f"Invalid hex color specifier:
{
orig_c
!r
}
"
)
# string gray.
try
:
c
=
float
(
c
)
except
ValueError
:
pass
else
:
if
not
(
0
<=
c
<=
1
):
raise
ValueError
(
f"Invalid string grayscale value
{
orig_c
!r
}
. "
f"Value must be within 0-1 range"
)
return
c
,
c
,
c
,
alpha
if
alpha
is
not
None
else
1.
raise
ValueError
(
f"Invalid RGBA argument:
{
orig_c
!r
}
"
)
# turn 2-D array into 1-D array
if
isinstance
(
c
,
np
.
ndarray
):
if
c
.
ndim
==
2
and
c
.
shape
[
0
]
==
1
:
c
=
c
.
reshape
(
-
1
)
# tuple color.
if
not
np
.
iterable
(
c
):
raise
ValueError
(
f"Invalid RGBA argument:
{
orig_c
!r
}
"
)
if
len
(
c
)
not
in
[
3
,
4
]:
raise
ValueError
(
"RGBA sequence should have length 3 or 4"
)
if
not
all
(
isinstance
(
x
,
Real
)
for
x
in
c
):
# Checks that don't work: `map(float, ...)`, `np.array(..., float)` and
# `np.array(...).astype(float)` would all convert "0.5" to 0.5.
raise
ValueError
(
f"Invalid RGBA argument:
{
orig_c
!r
}
"
)
# Return a tuple to prevent the cached value from being modified.
c
=
tuple
(
map
(
float
,
c
))
if
len
(
c
)
==
3
and
alpha
is
None
:
alpha
=
1
if
alpha
is
not
None
:
c
=
c
[:
3
]
+
(
alpha
,)
if
any
(
elem
<
0
or
elem
>
1
for
elem
in
c
):
raise
ValueError
(
"RGBA values should be within 0-1 range"
)
return
c
def
to_rgba_array
(
c
,
alpha
=
None
):
"""
Convert *c* to a (n, 4) array of RGBA colors.
Parameters
----------
c : :mpltype:`color` or list of :mpltype:`color` or RGB(A) array
If *c* is a masked array, an `~numpy.ndarray` is returned with a
(0, 0, 0, 0) row for each masked value or row in *c*.
alpha : float or sequence of floats, optional
If *alpha* is given, force the alpha value of the returned RGBA tuple
to *alpha*.
If None, the alpha value from *c* is used. If *c* does not have an
alpha channel, then alpha defaults to 1.
*alpha* is ignored for the color value ``"none"`` (case-insensitive),
which always maps to ``(0, 0, 0, 0)``.
If *alpha* is a sequence and *c* is a single color, *c* will be
repeated to match the length of *alpha*.
Returns
-------
array
(n, 4) array of RGBA colors, where each channel (red, green, blue,
alpha) can assume values between 0 and 1.
"""
if
isinstance
(
c
,
tuple
)
and
len
(
c
)
==
2
and
isinstance
(
c
[
1
],
Real
):
if
alpha
is
None
:
c
,
alpha
=
c
else
:
c
=
c
[
0
]
# Special-case inputs that are already arrays, for performance. (If the
# array has the wrong kind or shape, raise the error during one-at-a-time
# conversion.)
if
np
.
iterable
(
alpha
):
alpha
=
np
.
asarray
(
alpha
).
ravel
()
if
(
isinstance
(
c
,
np
.
ndarray
)
and
c
.
dtype
.
kind
in
"if"
and
c
.
ndim
==
2
and
c
.
shape
[
1
]
in
[
3
,
4
]):
mask
=
c
.
mask
.
any
(
axis
=
1
)
if
np
.
ma
.
is_masked
(
c
)
else
None
c
=
np
.
ma
.
getdata
(
c
)
if
np
.
iterable
(
alpha
):
if
c
.
shape
[
0
]
==
1
and
alpha
.
shape
[
0
]
>
1
:
c
=
np
.
tile
(
c
, (
alpha
.
shape
[
0
],
1
))
elif
c
.
shape
[
0
]
!=
alpha
.
shape
[
0
]:
raise
ValueError
(
"The number of colors must match the number"
" of alpha values if there are more than one"
" of each."
)
if
c
.
shape
[
1
]
==
3
:
result
=
np
.
column_stack
([
c
,
np
.
zeros
(
len
(
c
))])
result
[:,
-
1
]
=
alpha
if
alpha
is
not
None
else
1.
elif
c
.
shape
[
1
]
==
4
:
result
=
c
.
copy
()
if
alpha
is
not
None
:
result
[:,
-
1
]
=
alpha
if
mask
is
not
None
:
result
[
mask
]
=
0
if
np
.
any
((
result
<
0
)
|
(
result
>
1
)):
raise
ValueError
(
"RGBA values should be within 0-1 range"
)
return
result
# Handle single values.
# Note that this occurs *after* handling inputs that are already arrays, as
# `to_rgba(c, alpha)` (below) is expensive for such inputs, due to the need
# to format the array in the ValueError message(!).
if
cbook
.
_str_lower_equal
(
c
,
"none"
):
return
np
.
zeros
((
0
,
4
),
float
)
try
:
if
np
.
iterable
(
alpha
):
return
np
.
array
([
to_rgba
(
c
,
a
)
for
a
in
alpha
],
float
)
else
:
return
np
.
array
([
to_rgba
(
c
,
alpha
)],
float
)
except
TypeError
:
pass
except
ValueError
as
e
:
if
e
.
args
==
(
"'alpha' must be between 0 and 1, inclusive"
, ):
# ValueError is from _to_rgba_no_colorcycle().
raise
e
if
isinstance
(
c
,
str
):
raise
ValueError
(
f"
{
c
!r
}
is not a valid color value."
)
if
len
(
c
)
==
0
:
return
np
.
zeros
((
0
,
4
),
float
)
# Quick path if the whole sequence can be directly converted to a numpy
# array in one shot.
if
isinstance
(
c
,
Sequence
):
lens
=
{
len
(
cc
)
if
isinstance
(
cc
, (
list
,
tuple
))
else
-
1
for
cc
in
c
}
if
lens
==
{
3
}:
rgba
=
np
.
column_stack
([
c
,
np
.
ones
(
len
(
c
))])
elif
lens
==
{
4
}:
rgba
=
np
.
array
(
c
)
else
:
rgba
=
np
.
array
([
to_rgba
(
cc
)
for
cc
in
c
])
else
:
rgba
=
np
.
array
([
to_rgba
(
cc
)
for
cc
in
c
])
if
alpha
is
not
None
:
rgba
[:,
3
]
=
alpha
if
isinstance
(
c
,
Sequence
):
# ensure that an explicit alpha does not overwrite full transparency
# for "none"
none_mask
=
[
cbook
.
_str_equal
(
cc
,
"none"
)
for
cc
in
c
]
rgba
[:,
3
][
none_mask
]
=
0
return
rgba
def
to_rgb
(
c
):
"""
Convert the :mpltype:`color` *c* to an RGB color tuple.
If c has an alpha channel value specified, that is silently dropped.
"""
return
to_rgba
(
c
)[:
3
]
def
to_hex
(
c
,
keep_alpha
=
False
):
"""
Convert *c* to a hex color.
Parameters
----------
c : :mpltype:`color` or `numpy.ma.masked`
keep_alpha : bool, default: False
If False, use the ``#rrggbb`` format, otherwise use ``#rrggbbaa``.
Returns
-------
str
``#rrggbb`` or ``#rrggbbaa`` hex color string
"""
c
=
to_rgba
(
c
)
if
not
keep_alpha
:
c
=
c
[:
3
]
return
"#"
+
""
.
join
(
format
(
round
(
val
*
255
),
"02x"
)
for
val
in
c
)
### Backwards-compatible color-conversion API
cnames
=
CSS4_COLORS
#: :meta private:
hexColorPattern
=
re
.
compile
(
r"\A#[a-fA-F0-9]{6}\Z"
)
#: :meta private:
rgb2hex
=
to_hex
#: :meta private:
hex2color
=
to_rgb
#: :meta private:
class
ColorConverter
:
"""
A class only kept for backwards compatibility.
Its functionality is entirely provided by module-level functions.
:meta private:
"""
colors
=
_colors_full_map
cache
=
_colors_full_map
.
cache
to_rgb
=
staticmethod
(
to_rgb
)
to_rgba
=
staticmethod
(
to_rgba
)
to_rgba_array
=
staticmethod
(
to_rgba_array
)
colorConverter
=
ColorConverter
()
### End of backwards-compatible color-conversion API
def
_create_lookup_table
(
N
,
data
,
gamma
=
1.0
):
r"""
Create an *N* -element 1D lookup table.
This assumes a mapping :math:`f : [0, 1] \rightarrow [0, 1]`. The returned
data is an array of N values :math:`y = f(x)` where x is sampled from
[0, 1].
By default (*gamma* = 1) x is equidistantly sampled from [0, 1]. The
*gamma* correction factor :math:`\gamma` distorts this equidistant
sampling by :math:`x \rightarrow x^\gamma`.
Parameters
----------
N : int
The number of elements of the created lookup table; at least 1.
data : (M, 3) array-like or callable
Defines the mapping :math:`f`.
If a (M, 3) array-like, the rows define values (x, y0, y1). The x
values must start with x=0, end with x=1, and all x values be in
increasing order.
A value between :math:`x_i` and :math:`x_{i+1}` is mapped to the range
:math:`y^1_{i-1} \ldots y^0_i` by linear interpolation.
For the simple case of a y-continuous mapping, y0 and y1 are identical.
The two values of y are to allow for discontinuous mapping functions.
E.g. a sawtooth with a period of 0.2 and an amplitude of 1 would be::
[(0, 1, 0), (0.2, 1, 0), (0.4, 1, 0), ..., [(1, 1, 0)]
In the special case of ``N == 1``, by convention the returned value
is y0 for x == 1.
If *data* is a callable, it must accept and return numpy arrays::
data(x : ndarray) -> ndarray
and map values between 0 - 1 to 0 - 1.
gamma : float
Gamma correction factor for input distribution x of the mapping.
See also https://en.wikipedia.org/wiki/Gamma_correction.
Returns
-------
array
The lookup table where ``lut[x * (N-1)]`` gives the closest value
for values of x between 0 and 1.
Notes
-----
This function is internally used for `.LinearSegmentedColormap`.
"""
if
callable
(
data
):
xind
=
np
.
linspace
(
0
,
1
,
N
)
**
gamma
lut
=
np
.
clip
(
np
.
array
(
data
(
xind
),
dtype
=
float
),
0
,
1
)
return
lut
try
:
adata
=
np
.
array
(
data
)
except
Exception
as
err
:
raise
TypeError
(
"data must be convertible to an array"
)
from
err
_api
.
check_shape
((
None
,
3
),
data
=
adata
)
x
=
adata
[:,
0
]
y0
=
adata
[:,
1
]
y1
=
adata
[:,
2
]
if
x
[
0
]
!=
0.
or
x
[
-
1
]
!=
1.0
:
raise
ValueError
(
"data mapping points must start with x=0 and end with x=1"
)
if
(
np
.
diff
(
x
)
<
0
).
any
():
raise
ValueError
(
"data mapping points must have x in increasing order"
)
# begin generation of lookup table
if
N
==
1
:
# convention: use the y = f(x=1) value for a 1-element lookup table
lut
=
np
.
array
(
y0
[
-
1
])
else
:
x
=
x
*
(
N
-
1
)
xind
=
(
N
-
1
)
*
np
.
linspace
(
0
,
1
,
N
)
**
gamma
ind
=
np
.
searchsorted
(
x
,
xind
)[
1
:
-
1
]
distance
=
(
xind
[
1
:
-
1
]
-
x
[
ind
-
1
])
/
(
x
[
ind
]
-
x
[
ind
-
1
])
lut
=
np
.
concatenate
([
[
y1
[
0
]],
distance
*
(
y0
[
ind
]
-
y1
[
ind
-
1
])
+
y1
[
ind
-
1
],
[
y0
[
-
1
]],
])
# ensure that the lut is confined to values between 0 and 1 by clipping it
return
np
.
clip
(
lut
,
0.0
,
1.0
)
class
Colormap
:
"""
Baseclass for all scalar to RGBA mappings.
Typically, Colormap instances are used to convert data values (floats)
from the interval ``[0, 1]`` to the RGBA color that the respective
Colormap represents. For scaling of data into the ``[0, 1]`` interval see
`matplotlib.colors.Normalize`. Subclasses of `matplotlib.cm.ScalarMappable`
make heavy use of this ``data -> normalize -> map-to-color`` processing
chain.
"""
def
__init__
(
self
,
name
,
N
=
256
,
*
,
bad
=
None
,
under
=
None
,
over
=
None
):
"""
Parameters
----------
name : str
The name of the colormap.
N : int
The number of RGB quantization levels.
bad : :mpltype:`color`, default: transparent
The color for invalid values (NaN or masked).
.. versionadded:: 3.11
under : :mpltype:`color`, default: color of the lowest value
The color for low out-of-range values.
.. versionadded:: 3.11
over : :mpltype:`color`, default: color of the highest value
The color for high out-of-range values.
.. versionadded:: 3.11
"""
self
.
name
=
name
self
.
N
=
int
(
N
)
# ensure that N is always int
self
.
_rgba_bad
=
(
0.0
,
0.0
,
0.0
,
0.0
)
if
bad
is
None
else
to_rgba
(
bad
)
self
.
_rgba_under
=
None
if
under
is
None
else
to_rgba
(
under
)
self
.
_rgba_over
=
None
if
over
is
None
else
to_rgba
(
over
)
self
.
_i_under
=
self
.
N
self
.
_i_over
=
self
.
N
+
1
self
.
_i_bad
=
self
.
N
+
2
self
.
_isinit
=
False
self
.
n_variates
=
1
#: When this colormap exists on a scalar mappable and colorbar_extend
#: is not False, colorbar creation will pick up ``colorbar_extend`` as
#: the default value for the ``extend`` keyword in the
#: `matplotlib.colorbar.Colorbar` constructor.
self
.
colorbar_extend
=
False
def
__call__
(
self
,
X
,
alpha
=
None
,
bytes
=
False
):
r"""
Parameters
----------
X : float or int or array-like
The data value(s) to convert to RGBA.
For floats, *X* should be in the interval ``[0.0, 1.0]`` to
return the RGBA values ``X*100`` percent along the Colormap line.
For integers, *X* should be in the interval ``[0, Colormap.N)`` to
return RGBA values *indexed* from the Colormap with index ``X``.
alpha : float or array-like or None
Alpha must be a scalar between 0 and 1, a sequence of such
floats with shape matching X, or None.
bytes : bool, default: False
If False (default), the returned RGBA values will be floats in the
interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
interval ``[0, 255]``.
Returns
-------
Tuple of RGBA values if X is scalar, otherwise an array of
RGBA values with a shape of ``X.shape + (4, )``.
"""
rgba
,
mask
=
self
.
_get_rgba_and_mask
(
X
,
alpha
=
alpha
,
bytes
=
bytes
)
if
not
np
.
iterable
(
X
):
rgba
=
tuple
(
rgba
)
return
rgba
def
_get_rgba_and_mask
(
self
,
X
,
alpha
=
None
,
bytes
=
False
):
r"""
Parameters
----------
X : float or int or array-like
The data value(s) to convert to RGBA.
For floats, *X* should be in the interval ``[0.0, 1.0]`` to
return the RGBA values ``X*100`` percent along the Colormap line.
For integers, *X* should be in the interval ``[0, Colormap.N)`` to
return RGBA values *indexed* from the Colormap with index ``X``.
alpha : float or array-like or None
Alpha must be a scalar between 0 and 1, a sequence of such
floats with shape matching X, or None.
bytes : bool, default: False
If False (default), the returned RGBA values will be floats in the
interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
interval ``[0, 255]``.
Returns
-------
colors : np.ndarray
Array of RGBA values with a shape of ``X.shape + (4, )``.
mask : np.ndarray
Boolean array with True where the input is ``np.nan`` or masked.
"""
self
.
_ensure_inited
()
xa
=
np
.
array
(
X
,
copy
=
True
)
if
not
xa
.
dtype
.
isnative
:
# Native byteorder is faster.
xa
=
xa
.
byteswap
().
view
(
xa
.
dtype
.
newbyteorder
())
if
xa
.
dtype
.
kind
==
"f"
:
xa
*=
self
.
N
# xa == 1 (== N after multiplication) is not out of range.
xa
[
xa
==
self
.
N
]
=
self
.
N
-
1
# Pre-compute the masks before casting to int (which can truncate
# negative values to zero or wrap large floats to negative ints).
mask_under
=
xa
<
0
mask_over
=
xa
>=
self
.
N
# If input was masked, get the bad mask from it; else mask out nans.
mask_bad
=
X
.
mask
if
np
.
ma
.
is_masked
(
X
)
else
np
.
isnan
(
xa
)
with
np
.
errstate
(
invalid
=
"ignore"
):
# We need this cast for unsigned ints as well as floats
xa
=
xa
.
astype
(
int
)
xa
[
mask_under
]
=
self
.
_i_under
xa
[
mask_over
]
=
self
.
_i_over
xa
[
mask_bad
]
=
self
.
_i_bad
lut
=
self
.
_lut
if
bytes
:
lut
=
(
lut
*
255
).
astype
(
np
.
uint8
)
rgba
=
lut
.
take
(
xa
,
axis
=
0
,
mode
=
'clip'
)
if
alpha
is
not
None
:
alpha
=
np
.
clip
(
alpha
,
0
,
1
)
if
bytes
:
alpha
*=
255
# Will be cast to uint8 upon assignment.
if
alpha
.
shape
not
in
[(),
xa
.
shape
]:
raise
ValueError
(
f"alpha is array-like but its shape
{
alpha
.
shape
}
does "
f"not match that of X
{
xa
.
shape
}
"
)
rgba
[...,
-
1
]
=
alpha
# If the "bad" color is all zeros, then ignore alpha input.
if
(
lut
[
-
1
]
==
0
).
all
():
rgba
[
mask_bad
]
=
(
0
,
0
,
0
,
0
)
return
rgba
,
mask_bad
def
__copy__
(
self
):
cls
=
self
.
__class__
cmapobject
=
cls
.
__new__
(
cls
)
cmapobject
.
__dict__
.
update
(
self
.
__dict__
)
if
self
.
_isinit
:
cmapobject
.
_lut
=
np
.
copy
(
self
.
_lut
)
return
cmapobject
def
__eq__
(
self
,
other
):
if
(
not
isinstance
(
other
,
Colormap
)
or
self
.
colorbar_extend
!=
other
.
colorbar_extend
):
return
False
# To compare lookup tables the Colormaps have to be initialized
self
.
_ensure_inited
()
other
.
_ensure_inited
()
return
np
.
array_equal
(
self
.
_lut
,
other
.
_lut
)
def
get_bad
(
self
):
"""Get the color for masked values."""
self
.
_ensure_inited
()
return
np
.
array
(
self
.
_lut
[
self
.
_i_bad
])
@
_api
.
deprecated
(
"3.11"
,
pending
=
True
,
alternative
=
"cmap.with_extremes(bad=...) or Colormap(bad=...)"
)
def
set_bad
(
self
,
color
=
'k'
,
alpha
=
None
):
"""Set the color for masked values."""
self
.
_set_extremes
(
bad
=
(
color
,
alpha
))
def
get_under
(
self
):
"""Get the color for low out-of-range values."""
self
.
_ensure_inited
()
return
np
.
array
(
self
.
_lut
[
self
.
_i_under
])
@
_api
.
deprecated
(
"3.11"
,
pending
=
True
,
alternative
=
"cmap.with_extremes(under=...) or Colormap(under=...)"
)
def
set_under
(
self
,
color
=
'k'
,
alpha
=
None
):
"""Set the color for low out-of-range values."""
self
.
_set_extremes
(
under
=
(
color
,
alpha
))
def
get_over
(
self
):
"""Get the color for high out-of-range values."""
self
.
_ensure_inited
()
return
np
.
array
(
self
.
_lut
[
self
.
_i_over
])
@
_api
.
deprecated
(
"3.11"
,
pending
=
True
,
alternative
=
"cmap.with_extremes(over=...) or Colormap(over=...)"
)
def
set_over
(
self
,
color
=
'k'
,
alpha
=
None
):
"""Set the color for high out-of-range values."""
self
.
_set_extremes
(
over
=
(
color
,
alpha
))
@
_api
.
deprecated
(
"3.11"
,
pending
=
True
,
alternative
=
"cmap.with_extremes(bad=..., under=..., over=...) or "
"Colormap(bad=..., under=..., over=...)"
)
def
set_extremes
(
self
,
*
,
bad
=
None
,
under
=
None
,
over
=
None
):
"""
Set the colors for masked (*bad*) values and, when ``norm.clip =
False``, low (*under*) and high (*over*) out-of-range values.
"""
self
.
_set_extremes
(
bad
=
bad
,
under
=
under
,
over
=
over
)
def
with_extremes
(
self
,
*
,
bad
=
None
,
under
=
None
,
over
=
None
):
"""
Return a copy of the colormap, for which the colors for masked (*bad*)
values and, when ``norm.clip = False``, low (*under*) and high (*over*)
out-of-range values, have been set accordingly.
"""
new_cm
=
self
.
copy
()
new_cm
.
_set_extremes
(
bad
=
bad
,
under
=
under
,
over
=
over
)
return
new_cm
def
_set_extremes
(
self
,
bad
=
None
,
under
=
None
,
over
=
None
):
"""
Set the colors for masked (*bad*) and out-of-range (*under* and *over*) values.
Parameters that are None are left unchanged.
"""
if
bad
is
not
None
:
self
.
_rgba_bad
=
to_rgba
(
bad
)
if
under
is
not
None
:
self
.
_rgba_under
=
to_rgba
(
under
)
if
over
is
not
None
:
self
.
_rgba_over
=
to_rgba
(
over
)
if
self
.
_isinit
:
self
.
_update_lut_extremes
()
def
_update_lut_extremes
(
self
):
"""Ensure than an existing lookup table has the correct extreme values."""
if
self
.
_rgba_under
:
self
.
_lut
[
self
.
_i_under
]
=
self
.
_rgba_under
else
:
self
.
_lut
[
self
.
_i_under
]
=
self
.
_lut
[
0
]
if
self
.
_rgba_over
:
self
.
_lut
[
self
.
_i_over
]
=
self
.
_rgba_over
else
:
self
.
_lut
[
self
.
_i_over
]
=
self
.
_lut
[
self
.
N
-
1
]
self
.
_lut
[
self
.
_i_bad
]
=
self
.
_rgba_bad
def
with_alpha
(
self
,
alpha
):
"""
Return a copy of the colormap with a new uniform transparency.
Parameters
----------
alpha : float
The alpha blending value, between 0 (transparent) and 1 (opaque).
"""
if
not
isinstance
(
alpha
,
Real
):
raise
TypeError
(
f"'alpha' must be numeric or None, not
{
type
(
alpha
)
}
"
)
if
not
0
<=
alpha
<=
1
:
raise
ValueError
(
"'alpha' must be between 0 and 1, inclusive"
)
new_cm
=
self
.
copy
()
new_cm
.
_ensure_inited
()
new_cm
.
_lut
[:,
3
]
=
alpha
return
new_cm
def
_init
(
self
):
"""Generate the lookup table, ``self._lut``."""
raise
NotImplementedError
(
"Abstract class only"
)
def
_ensure_inited
(
self
):
if
not
self
.
_isinit
:
self
.
_init
()
def
is_gray
(
self
):
"""Return whether the colormap is grayscale."""
self
.
_ensure_inited
()
return
(
np
.
all
(
self
.
_lut
[:,
0
]
==
self
.
_lut
[:,
1
])
and
np
.
all
(
self
.
_lut
[:,
0
]
==
self
.
_lut
[:,
2
]))
def
resampled
(
self
,
lutsize
):
"""Return a new colormap with *lutsize* entries."""
if
hasattr
(
self
,
'_resample'
):
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
You can’t perform that action at this time.
Back
|
FazBrowse Home
|
New Git URL