/
colors.py
2669 lines (2248 loc) · 94.3 KB
/
colors.py
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::
:doc:`/tutorials/colors/colormap-manipulation` for examples of how to
make colormaps and
:doc:`/tutorials/colors/colormaps` for a list of built-in colormaps.
:doc:`/tutorials/colors/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
:doc:`/tutorials/colors/colors`.
.. _palettable: https://jiffyclub.github.io/palettable/
.. _xkcd color survey: https://xkcd.com/color/rgb/
"""
import base64
from collections.abc import Sized, Sequence, Mapping
import functools
import importlib
import inspect
import io
import itertools
from numbers import Number
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)
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
cmap = mpl.color_sequences['tab10']
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,
'Dark2': _cm._Dark2_data,
'Set1': _cm._Set1_data,
'Set2': _cm._Set1_data,
'Set3': _cm._Set1_data,
}
def __init__(self):
self._color_sequences = {**self._BUILTIN_COLOR_SEQUENCES}
def __getitem__(self, item):
try:
return list(self._color_sequences[item])
except KeyError:
raise KeyError(f"{item!r} is not a known color sequence name")
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 colors
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
def _is_nth_color(c):
"""Return whether *c* can be interpreted as an item in the color cycle."""
return isinstance(c, str) and re.match(r"\AC[0-9]+\Z", c)
def is_color_like(c):
"""Return whether *c* can be interpreted as an RGB(A) color."""
# Special-case nth color syntax because it cannot be parsed during setup.
if _is_nth_color(c):
return True
try:
to_rgba(c)
except ValueError:
return False
else:
return True
def _has_alpha_channel(c):
"""Return whether *c* is a color with an alpha channel."""
# 4-element sequences are interpreted as r, g, b, a
return not isinstance(c, str) and len(c) == 4
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}")
def same_color(c1, c2):
"""
Return whether the colors *c1* and *c2* are the same.
*c1*, *c2* can be single colors or lists/arrays of colors.
"""
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 : Matplotlib 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.
"""
# 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)``.
"""
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(orig_c) != 1:
try:
c = _colors_full_map[c.lower()]
except KeyError:
pass
if isinstance(c, str):
# hex color in #rrggbb format.
match = re.match(r"\A#[a-fA-F0-9]{6}\Z", c)
if match:
return (tuple(int(n, 16) / 255
for n in [c[1:3], c[3:5], c[5:7]])
+ (alpha if alpha is not None else 1.,))
# hex color in #rgb format, shorthand for #rrggbb.
match = re.match(r"\A#[a-fA-F0-9]{3}\Z", c)
if match:
return (tuple(int(n, 16) / 255
for n in [c[1]*2, c[2]*2, c[3]*2])
+ (alpha if alpha is not None else 1.,))
# hex color with alpha in #rrggbbaa format.
match = re.match(r"\A#[a-fA-F0-9]{8}\Z", c)
if match:
color = [int(n, 16) / 255
for n in [c[1:3], c[3:5], c[5:7], c[7:9]]]
if alpha is not None:
color[-1] = alpha
return tuple(color)
# hex color with alpha in #rgba format, shorthand for #rrggbbaa.
match = re.match(r"\A#[a-fA-F0-9]{4}\Z", c)
if match:
color = [int(n, 16) / 255
for n in [c[1]*2, c[2]*2, c[3]*2, c[4]*2]]
if alpha is not None:
color[-1] = alpha
return tuple(color)
# 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, Number) 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 : Matplotlib color or array of colors
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.
"""
# 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 (ValueError, TypeError):
pass
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
return rgba
def to_rgb(c):
"""Convert *c* to an RGB color, silently dropping the alpha channel."""
return to_rgba(c)[:3]
def to_hex(c, keep_alpha=False):
"""
Convert *c* to a hex color.
Parameters
----------
c : :doc:`color </tutorials/colors/colors>` 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
hexColorPattern = re.compile(r"\A#[a-fA-F0-9]{6}\Z")
rgb2hex = to_hex
hex2color = to_rgb
class ColorConverter:
"""
A class only kept for backwards compatibility.
Its functionality is entirely provided by module-level functions.
"""
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):
"""
Parameters
----------
name : str
The name of the colormap.
N : int
The number of RGB quantization levels.
"""
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, don't paint anything.
self._rgba_under = None
self._rgba_over = None
self._i_under = self.N
self._i_over = self.N + 1
self._i_bad = self.N + 2
self._isinit = False
#: 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):
"""
Parameters
----------
X : float or int, `~numpy.ndarray` or scalar
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
If False (default), the returned RGBA values will be floats in the
interval ``[0, 1]`` otherwise they will be uint8s 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, )``.
"""
if not self._isinit:
self._init()
# Take the bad mask from a masked array, or in all other cases defer
# np.isnan() to after we have converted to an array.
mask_bad = X.mask if np.ma.is_masked(X) else None
xa = np.array(X, copy=True)
if mask_bad is None:
mask_bad = np.isnan(xa)
if not xa.dtype.isnative:
xa = xa.byteswap().newbyteorder() # Native byteorder is faster.
if xa.dtype.kind == "f":
xa *= self.N
# Negative values are out of range, but astype(int) would
# truncate them towards zero.
xa[xa < 0] = -1
# xa == 1 (== N after multiplication) is not out of range.
xa[xa == self.N] = self.N - 1
# Avoid converting large positive values to negative integers.
np.clip(xa, -1, self.N, out=xa)
with np.errstate(invalid="ignore"):
# We need this cast for unsigned ints as well as floats
xa = xa.astype(int)
# Set the over-range indices before the under-range;
# otherwise the under-range values get converted to over-range.
xa[xa > self.N - 1] = self._i_over
xa[xa < 0] = self._i_under
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() and np.any(mask_bad):
if np.iterable(mask_bad) and mask_bad.shape == xa.shape:
rgba[mask_bad] = (0, 0, 0, 0)
else:
rgba[..., :] = (0, 0, 0, 0)
if not np.iterable(X):
rgba = tuple(rgba)
return rgba
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.name != other.name or
self.colorbar_extend != other.colorbar_extend):
return False
# To compare lookup tables the Colormaps have to be initialized
if not self._isinit:
self._init()
if not other._isinit:
other._init()
return np.array_equal(self._lut, other._lut)
def get_bad(self):
"""Get the color for masked values."""
if not self._isinit:
self._init()
return np.array(self._lut[self._i_bad])
def set_bad(self, color='k', alpha=None):
"""Set the color for masked values."""
self._rgba_bad = to_rgba(color, alpha)
if self._isinit:
self._set_extremes()
def get_under(self):
"""Get the color for low out-of-range values."""
if not self._isinit:
self._init()
return np.array(self._lut[self._i_under])
def set_under(self, color='k', alpha=None):
"""Set the color for low out-of-range values."""
self._rgba_under = to_rgba(color, alpha)
if self._isinit:
self._set_extremes()
def get_over(self):
"""Get the color for high out-of-range values."""
if not self._isinit:
self._init()
return np.array(self._lut[self._i_over])
def set_over(self, color='k', alpha=None):
"""Set the color for high out-of-range values."""
self._rgba_over = to_rgba(color, alpha)
if self._isinit:
self._set_extremes()
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.
"""
if bad is not None:
self.set_bad(bad)
if under is not None:
self.set_under(under)
if over is not None:
self.set_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):
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 _init(self):
"""Generate the lookup table, ``self._lut``."""
raise NotImplementedError("Abstract class only")
def is_gray(self):
"""Return whether the colormap is grayscale."""
if not self._isinit:
self._init()
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'):
_api.warn_external(
"The ability to resample a color map is now public API "
f"However the class {type(self)} still only implements "
"the previous private _resample method. Please update "
"your class."
)
return self._resample(lutsize)
raise NotImplementedError()
def reversed(self, name=None):
"""
Return a reversed instance of the Colormap.
.. note:: This function is not implemented for the base class.
Parameters
----------
name : str, optional
The name for the reversed colormap. If None, the
name is set to ``self.name + "_r"``.
See Also
--------
LinearSegmentedColormap.reversed
ListedColormap.reversed
"""
raise NotImplementedError()
def _repr_png_(self):
"""Generate a PNG representation of the Colormap."""
X = np.tile(np.linspace(0, 1, _REPR_PNG_SIZE[0]),
(_REPR_PNG_SIZE[1], 1))
pixels = self(X, bytes=True)
png_bytes = io.BytesIO()
title = self.name + ' colormap'
author = f'Matplotlib v{mpl.__version__}, https://matplotlib.org'
pnginfo = PngInfo()
pnginfo.add_text('Title', title)
pnginfo.add_text('Description', title)
pnginfo.add_text('Author', author)
pnginfo.add_text('Software', author)
Image.fromarray(pixels).save(png_bytes, format='png', pnginfo=pnginfo)
return png_bytes.getvalue()
def _repr_html_(self):
"""Generate an HTML representation of the Colormap."""
png_bytes = self._repr_png_()
png_base64 = base64.b64encode(png_bytes).decode('ascii')
def color_block(color):
hex_color = to_hex(color, keep_alpha=True)
return (f'<div title="{hex_color}" '
'style="display: inline-block; '
'width: 1em; height: 1em; '
'margin: 0; '
'vertical-align: middle; '
'border: 1px solid #555; '
f'background-color: {hex_color};"></div>')
return ('<div style="vertical-align: middle;">'
f'<strong>{self.name}</strong> '
'</div>'
'<div class="cmap"><img '
f'alt="{self.name} colormap" '
f'title="{self.name}" '
'style="border: 1px solid #555;" '
f'src="data:image/png;base64,{png_base64}"></div>'
'<div style="vertical-align: middle; '
f'max-width: {_REPR_PNG_SIZE[0]+2}px; '
'display: flex; justify-content: space-between;">'
'<div style="float: left;">'
f'{color_block(self.get_under())} under'
'</div>'
'<div style="margin: 0 auto; display: inline-block;">'
f'bad {color_block(self.get_bad())}'
'</div>'
'<div style="float: right;">'
f'over {color_block(self.get_over())}'
'</div>')
def copy(self):
"""Return a copy of the colormap."""
return self.__copy__()
class LinearSegmentedColormap(Colormap):
"""
Colormap objects based on lookup tables using linear segments.
The lookup table is generated using linear interpolation for each
primary color, with the 0-1 domain divided into any number of
segments.
"""
def __init__(self, name, segmentdata, N=256, gamma=1.0):
"""
Create colormap from linear mapping segments
segmentdata argument is a dictionary with a red, green and blue
entries. Each entry should be a list of *x*, *y0*, *y1* tuples,
forming rows in a table. Entries for alpha are optional.
Example: suppose you want red to increase from 0 to 1 over
the bottom half, green to do the same over the middle half,
and blue over the top half. Then you would use::
cdict = {'red': [(0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'green': [(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0)]}
Each row in the table for a given color is a sequence of
*x*, *y0*, *y1* tuples. In each sequence, *x* must increase
monotonically from 0 to 1. For any input value *z* falling
between *x[i]* and *x[i+1]*, the output value of a given color
will be linearly interpolated between *y1[i]* and *y0[i+1]*::
row i: x y0 y1
/
/
row i+1: x y0 y1
Hence y0 in the first row and y1 in the last row are never used.
See Also
--------
LinearSegmentedColormap.from_list
Static method; factory function for generating a smoothly-varying
LinearSegmentedColormap.