-
Notifications
You must be signed in to change notification settings - Fork 4
/
colors.py
1275 lines (1074 loc) · 38.9 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
"""Utilities related to manipulating colors.
Colormaps
---------
In addition to the default `matplotlib
<https://matplotlib.org/stable/tutorials/colors/colormaps.html>`_ colormaps, `cmasher
<https://cmasher.readthedocs.io>`_, `cmocean <https://matplotlib.org/cmocean/>`_, and
`colorcet <https://colorcet.holoviz.org>`_ packages can be installed to extend the
available colormaps. If these packages are installed, they will be automatically
imported upon importing `erlab.plotting`.
Colormap Normalization
----------------------
.. plot:: norms.py example_1
:width: 65 %
Demonstration of `InversePowerNorm`.
.. plot:: norms.py example_2
:width: 65 %
Demonstration of `CenteredPowerNorm` and `CenteredInversePowerNorm`.
"""
__all__ = [
"CenteredInversePowerNorm",
"CenteredPowerNorm",
"InversePowerNorm",
"TwoSlopeInversePowerNorm",
"TwoSlopePowerNorm",
"axes_textcolor",
"close_to_white",
"color_distance",
"combined_cmap",
"flatten_transparency",
"gen_2d_colormap",
"get_mappable",
"image_is_light",
"nice_colorbar",
"prominent_color",
"proportional_colorbar",
"unify_clim",
]
from collections.abc import Iterable, Sequence
from numbers import Number
from typing import Any, Literal, cast
import matplotlib
import matplotlib.axes
import matplotlib.cm
import matplotlib.collections
import matplotlib.colorbar
import matplotlib.colors
import matplotlib.image
import matplotlib.pyplot as plt
import matplotlib.transforms
import numpy as np
import numpy.typing as npt
from matplotlib.typing import ColorType, RGBColorType
class InversePowerNorm(matplotlib.colors.Normalize):
r"""Inverse power-law normalization.
Linearly map a given value to the 0-1 range and then apply an inverse power-law
normalization over that range.
For values :math:`x`, `matplotlib.colors.PowerNorm` calculates :math:`x^\gamma`,
whereas `InversePowerNorm` calculates :math:`1-x^{1/\gamma}`. This provides higher
contrast for values closer to ``vmin``.
Parameters
----------
gamma
Power law normalization parameter. If equal to 1, the colormap is linear.
vmin, vmax
If ``vmin`` and/or ``vmax`` is not given, they are initialized from the minimum
and maximum value, respectively, of the first input processed; i.e.,
``__call__(A)`` calls ``autoscale_None(A)``
clip
If ``True`` values falling outside the range ``[vmin, vmax]``, are mapped to 0
or 1, whichever is closer, and masked values are set to 1. If ``False`` masked
values remain masked.
Clipping silently defeats the purpose of setting the over, under, and masked
colors in a colormap, so it is likely to lead to surprises; therefore the
default is ``clip=False``.
"""
def __init__(
self,
gamma: float,
vmin: float | None = None,
vmax: float | None = None,
clip: bool = False,
):
super().__init__(vmin, vmax, clip)
self.gamma = gamma
def __call__(self, value, clip=None):
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
self.autoscale_None(result)
gamma = self.gamma
vmin, vmax = self.vmin, self.vmax
if vmin > vmax:
raise ValueError("minvalue must be less than or equal to maxvalue")
elif vmin == vmax:
result.fill(0)
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(
np.clip(result.filled(vmax), vmin, vmax), mask=mask
)
resdat = result.data
resdat *= -1
resdat += vmax
resdat /= vmax - vmin
resdat[resdat < 0] = 0
np.power(resdat, 1.0 / gamma, resdat)
resdat *= -1
resdat += 1
result = np.ma.array(resdat, mask=result.mask, copy=False)
if is_scalar:
result = result[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
gamma = self.gamma
vmin, vmax = self.vmin, self.vmax
if np.iterable(value):
val = np.ma.asarray(value)
return np.ma.power(1 - val, gamma) * (vmin - vmax) + vmax
else:
return pow(1 - value, gamma) * (vmin - vmax) + vmax
def _diverging_powernorm(result, gamma, vmin, vmax, vcenter):
resdat = result.data
resdat_ = resdat.copy()
resdat_l = resdat[resdat_ < vcenter]
resdat_l -= vcenter
resdat_l[resdat_l >= 0] = 0
np.power(-resdat_l, gamma, resdat_l)
resdat_l /= (vcenter - vmin) ** gamma
resdat_l *= -0.5
resdat_l += 0.5
resdat[resdat_ < vcenter] = resdat_l
resdat_u = resdat[resdat_ >= vcenter]
resdat_u -= vcenter
resdat_u[resdat_u < 0] = 0
np.power(resdat_u, gamma, resdat_u)
resdat_u /= (vmax - vcenter) ** gamma
resdat_u *= 0.5
resdat_u += 0.5
resdat[resdat_ >= vcenter] = resdat_u
result = np.ma.array(resdat, mask=result.mask, copy=False)
return result
def _diverging_powernorm_inv(value, gamma, vmin, vmax, vcenter):
if np.iterable(value):
val = np.ma.asarray(value)
val_ = val.copy()
val_l = val_[val < 0.5]
val_u = val_[val >= 0.5]
val_[val < 0.5] = (
np.ma.power(1 - 2 * val_l, 1.0 / gamma) * (vmin - vcenter) + vcenter
)
val_[val >= 0.5] = (
np.ma.power(2 * val_u - 1, 1.0 / gamma) * (vmax - vcenter) + vcenter
)
return np.ma.asarray(val_)
elif value < 0.5:
return pow(1 - 2 * value, 1.0 / gamma) * (vmin - vcenter) + vcenter
else:
return pow(2 * value - 1, 1.0 / gamma) * (vmax - vcenter) + vcenter
def _diverging_inversepowernorm(result, gamma, vmin, vmax, vcenter):
resdat = result.data
resdat_ = resdat.copy()
resdat_l = resdat[resdat_ < vcenter]
resdat_l *= -1
resdat_l += vmin
resdat_l /= vmin - vcenter
resdat_l[resdat_l < 0] = 0
np.power(resdat_l, 1.0 / gamma, resdat_l)
resdat_l *= 0.5
resdat[resdat_ < vcenter] = resdat_l
resdat_u = resdat[resdat_ >= vcenter]
resdat_u *= -1
resdat_u += vmax
resdat_u /= vmax - vcenter
resdat_u[resdat_u < 0] = 0
np.power(resdat_u, 1.0 / gamma, resdat_u)
resdat_u *= -0.5
resdat_u += 1
resdat[resdat_ >= vcenter] = resdat_u
result = np.ma.array(resdat, mask=result.mask, copy=False)
return result
def _diverging_inversepowernorm_inv(value, gamma, vmin, vmax, vcenter):
if np.iterable(value):
val = np.ma.asarray(value)
val_ = val.copy()
val_l = val_[val < 0.5]
val_u = val_[val >= 0.5]
val_[val < 0.5] = np.ma.power(2 * val_l, gamma) * (vcenter - vmin) + vmin
val_[val >= 0.5] = np.ma.power(2 - 2 * val_u, gamma) * (vcenter - vmax) + vmax
return np.ma.asarray(val_)
elif value < 0.5:
return pow(2 * value, gamma) * (vcenter - vcenter) + vmin
else:
return pow(2 - 2 * value, gamma) * (vcenter - vmax) + vmax
class TwoSlopePowerNorm(matplotlib.colors.TwoSlopeNorm):
r"""Power-law normalization of data with a set center.
Useful when mapping data with an unequal rates of change around a
conceptual center, e.g., data that range from -2 to 4, with 0 as
the midpoint.
Parameters
----------
gamma
Power law exponent.
vcenter
The data value that defines ``0.5`` in the normalization.
Defaults to ``0``.
vmin
The data value that defines ``0.0`` in the normalization.
Defaults to the min value of the dataset.
vmax
The data value that defines ``1.0`` in the normalization.
Defaults to the max value of the dataset.
"""
def __init__(
self,
gamma: float,
vcenter: float = 0.0,
vmin: float | None = None,
vmax: float | None = None,
):
super().__init__(vcenter=vcenter, vmin=vmin, vmax=vmax)
self.gamma = gamma
self._func = _diverging_powernorm
self._func_i = _diverging_powernorm_inv
def __call__(self, value, clip=None):
"""Map value to the interval [0, 1]. The clip argument is unused."""
result, is_scalar = self.process_value(value)
self.autoscale_None(result)
gamma = self.gamma
vmin, vcenter, vmax = self.vmin, self.vcenter, self.vmax
if not vmin <= vcenter <= vmax:
raise ValueError("vmin, vcenter, vmax must increase monotonically")
if vmin == vmax:
result.fill(0)
else:
result = self._func(result, gamma, vmin, vmax, vcenter)
if is_scalar:
result = np.atleast_1d(result)[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
gamma = self.gamma
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
(vcenter,), _ = self.process_value(self.vcenter)
return self._func_i(value, gamma, vmin, vmax, vcenter)
class CenteredPowerNorm(matplotlib.colors.CenteredNorm):
r"""Power-law normalization of symmetrical data around a center.
Unlike `TwoSlopePowerNorm`, `CenteredPowerNorm` applies an equal rate of
change around the center.
Useful when mapping symmetrical data around a conceptual center e.g., data that
range from -2 to 4, with 0 as the midpoint, and with equal rates of change
around that midpoint.
Parameters
----------
gamma
Power law exponent.
vcenter
The data value that defines ``0.5`` in the normalization. Defaults to ``0``.
halfrange
The range of data values that defines a range of ``0.5`` in the
normalization, so that `vcenter` - `halfrange` is ``0.0`` and `vcenter` +
`halfrange` is ``1.0`` in the normalization. Defaults to the largest
absolute difference to `vcenter` for the values in the dataset.
clip
If ``True`` values falling outside the range ``[vmin, vmax]``,
are mapped to 0 or 1, whichever is closer, and masked values are
set to 1. If ``False`` masked values remain masked.
Clipping silently defeats the purpose of setting the over, under,
and masked colors in a colormap, so it is likely to lead to
surprises; therefore the default is ``clip=False``.
"""
def __init__(
self,
gamma: float,
vcenter: float = 0,
halfrange: float | None = None,
clip: bool = False,
):
super().__init__(vcenter=vcenter, halfrange=halfrange, clip=clip)
self.gamma = gamma
self._func = _diverging_powernorm
self._func_i = _diverging_powernorm_inv
def __call__(self, value, clip=None):
"""Map value to the interval [0, 1]."""
if clip is None:
clip = self.clip
result, is_scalar = self.process_value(value)
self.autoscale_None(result)
gamma = self.gamma
vmin, vcenter, vmax = self.vmin, self.vcenter, self.vmax
if not vmin <= vcenter <= vmax:
raise ValueError("vmin, vcenter, vmax must increase monotonically")
if vmin == vmax:
result.fill(0)
else:
if clip:
mask = np.ma.getmask(result)
result = np.ma.array(
np.clip(result.filled(vmax), vmin, vmax), mask=mask
)
result = self._func(result, gamma, vmin, vmax, vcenter)
if is_scalar:
result = np.atleast_1d(result)[0]
return result
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
gamma = self.gamma
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
(vcenter,), _ = self.process_value(self.vcenter)
return self._func_i(value, gamma, vmin, vmax, vcenter)
class TwoSlopeInversePowerNorm(TwoSlopePowerNorm):
r"""Inverse power-law normalization of data with a set center.
Useful when mapping data with an unequal rates of change around a
conceptual center, e.g., data that range from -2 to 4, with 0 as
the midpoint.
Parameters
----------
gamma
Power law exponent.
vcenter
The data value that defines ``0.5`` in the normalization.
Defaults to ``0``.
vmin
The data value that defines ``0.0`` in the normalization.
Defaults to the min value of the dataset.
vmax
The data value that defines ``1.0`` in the normalization.
Defaults to the max value of the dataset.
"""
def __init__(
self,
gamma: float,
vcenter: float = 0.0,
vmin: float | None = None,
vmax: float | None = None,
):
super().__init__(gamma, vcenter, vmin, vmax)
self._func = _diverging_inversepowernorm
self._func_i = _diverging_inversepowernorm_inv
class CenteredInversePowerNorm(CenteredPowerNorm):
r"""Inverse power-law normalization of symmetrical data around a center.
Unlike `TwoSlopeInversePowerNorm`, `CenteredInversePowerNorm` applies an
equal rate of change around the center.
Useful when mapping symmetrical data around a conceptual center e.g., data that
range from -2 to 4, with 0 as the midpoint, and with equal rates of change
around that midpoint.
Parameters
----------
gamma
Power law exponent.
vcenter
The data value that defines ``0.5`` in the normalization. Defaults to ``0``.
halfrange
The range of data values that defines a range of ``0.5`` in the
normalization, so that `vcenter` - `halfrange` is ``0.0`` and `vcenter` +
`halfrange` is ``1.0`` in the normalization. Defaults to the largest
absolute difference to `vcenter` for the values in the dataset.
clip
If ``True`` values falling outside the range ``[vmin, vmax]``,
are mapped to 0 or 1, whichever is closer, and masked values are
set to 1. If ``False`` masked values remain masked.
Clipping silently defeats the purpose of setting the over, under,
and masked colors in a colormap, so it is likely to lead to
surprises; therefore the default is ``clip=False``.
"""
def __init__(
self,
gamma: float,
vcenter: float = 0,
halfrange: float | None = None,
clip: bool = False,
):
super().__init__(gamma, vcenter, halfrange, clip)
self._func = _diverging_inversepowernorm
self._func_i = _diverging_inversepowernorm_inv
def get_mappable(
ax: matplotlib.axes.Axes, image_only: bool = False, silent: bool = False
) -> matplotlib.cm.ScalarMappable | None:
"""Get the `matplotlib.cm.ScalarMappable` from a given `matplotlib.axes.Axes`.
Parameters
----------
ax
Parent axes.
image_only
Only consider images as a valid mappable, by default `False`.
silent
If `False`, raises a `RuntimeError` when no mappable is found. If `True`,
silently returns `None`.
Returns
-------
matplotlib.cm.ScalarMappable or None
"""
if not image_only:
try:
mappable: Any = ax.collections[-1]
except (IndexError, AttributeError):
mappable = None
if image_only or mappable is None:
try:
mappable = ax.get_images()[-1]
except (IndexError, AttributeError):
mappable = None
if mappable is None:
if not silent:
raise RuntimeError(
"No mappable was found to use for colorbar "
"creation. First define a mappable such as "
"an image (with imshow) or a contour set ("
"with contourf)."
)
return mappable
def unify_clim(
axes: np.ndarray,
target: matplotlib.axes.Axes | None = None,
image_only: bool = False,
) -> None:
"""Unify the color limits for mappables in multiple axes.
Parameters
----------
axes
Array of :class:`matplotlib.axes.Axes` to unify the color limits.
target
The target axis to unify the color limits. If provided, the target color limits
will be taken from this axes. Otherwise, the color limits will be set to include
all mappables in the ``axes``.
image_only
If `True`, only consider mappables that are images. Default is `False`.
"""
vmn: float | None
vmx: float | None
if target is None:
vmn_list, vmx_list = [], []
for ax in axes.flat:
mappable = get_mappable(ax, image_only=image_only, silent=True)
if mappable is not None:
if mappable.norm.vmin is not None:
vmn_list.append(mappable.norm.vmin)
if mappable.norm.vmax is not None:
vmx_list.append(mappable.norm.vmax)
vmn, vmx = min(vmn_list), max(vmx_list)
else:
mappable = get_mappable(target, image_only=image_only, silent=True)
if mappable is not None:
vmn, vmx = mappable.norm.vmin, mappable.norm.vmax
# Apply color limits
for ax in axes.flat:
mappable = get_mappable(ax, image_only=image_only, silent=True)
if mappable is not None:
mappable.norm.vmin, mappable.norm.vmax = vmn, vmx
def proportional_colorbar(
mappable: matplotlib.cm.ScalarMappable | None = None,
cax: matplotlib.axes.Axes | None = None,
ax: matplotlib.axes.Axes | Iterable[matplotlib.axes.Axes] | None = None,
**kwargs,
) -> matplotlib.colorbar.Colorbar:
"""
Replace the current colorbar or creates a new colorbar with proportional spacing.
The default behavior of colorbars in `matplotlib` does not support colors
proportional to data in different norms. This function circumvents this behavior.
Parameters
----------
mappable
The `matplotlib.cm.ScalarMappable` described by this colorbar.
cax
Axes into which the colorbar will be drawn.
ax
One or more parent axes from which space for a new colorbar axes
will be stolen, if `cax` is `None`. This has no effect if `cax`
is set. If `mappable` is `None` and `ax` is given with more than
one Axes, the function will try to infer the mappable from the
first one.
**kwargs
Extra arguments to `matplotlib.pyplot.colorbar`: refer to the `matplotlib`
documentation for a list of all possible arguments.
Returns
-------
cbar : matplotlib.colorbar.Colorbar
The created colorbar.
Examples
--------
::
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
# Create example data and plot
X, Y = np.mgrid[0 : 3 : complex(0, 100), 0 : 2 : complex(0, 100)]
pcm = plt.pcolormesh(
X,
Y,
(1 + np.sin(Y * 10.0)) * X**2,
norm=matplotlib.colors.PowerNorm(gamma=0.5),
cmap="Blues_r",
shading="auto",
)
# Plot evenly spaced colorbar
proportional_colorbar()
"""
fontsize = kwargs.pop("fontsize", None)
if ax is None:
if cax is None:
ax = plt.gca()
if mappable is None:
mappable = get_mappable(ax)
elif isinstance(ax, Iterable):
if not isinstance(ax, np.ndarray):
ax = np.array(ax, dtype=object)
i = 0
while mappable is None and i < len(ax.flat):
mappable = get_mappable(ax.flatten()[i], silent=(i != (len(ax.flat) - 1)))
i += 1
elif mappable is None:
mappable = get_mappable(ax)
if mappable is None:
raise RuntimeError("No mappable was found to use for colorbar creation")
if mappable.colorbar is None:
plt.colorbar(mappable=mappable, cax=cax, ax=ax, **kwargs)
mappable.colorbar = cast(matplotlib.colorbar.Colorbar, mappable.colorbar)
ticks = mappable.colorbar.get_ticks()
if cax is None:
mappable.colorbar.remove()
kwargs.setdefault("ticks", ticks)
kwargs.setdefault("cmap", mappable.cmap)
kwargs.setdefault("norm", mappable.norm)
cbar = plt.colorbar(
mappable=mappable,
cax=cax,
ax=ax,
spacing="proportional",
boundaries=kwargs["norm"].inverse(np.linspace(0, 1, kwargs["cmap"].N)),
**kwargs,
)
if fontsize is not None:
cbar.ax.tick_params(labelsize=fontsize)
return cbar
def _size_to_bounds(ax, width, height, loc):
fig = ax.get_figure()
sizes = [width, height]
ax_sizes = (
ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()).bounds[2:]
)
sizes = [
float(size[:-1]) / 100 if isinstance(size, str) else size / ax_sizes[i]
for i, size in enumerate(sizes)
]
origin = [1 - sizes[0], 1 - sizes[1]]
if "center" in loc:
origin[0] /= 2
origin[1] /= 2
if "upper" in loc or "lower" in loc:
origin[1] *= 2
elif "left" in loc or "right" in loc:
origin[0] *= 2
if "left" in loc:
origin[0] = 0
if "lower" in loc:
origin[1] = 0
return origin + sizes
def _refresh_pads(ax, cax, pads, loc):
ref = _size_to_bounds(ax, 0, 0, loc)[:2]
bbox = ax.get_window_extent().transformed(ax.figure.dpi_scale_trans.inverted())
x0, y0 = (
bbox.x0 + ref[0] * (bbox.x1 - bbox.x0),
bbox.y1 + ref[1] * (bbox.y1 - bbox.y0),
)
bbox = cax.get_window_extent().transformed(ax.figure.dpi_scale_trans.inverted())
x1, y1 = (
bbox.x0 + ref[0] * (bbox.x1 - bbox.x0),
bbox.y1 + ref[1] * (bbox.y1 - bbox.y0),
)
pads[0] += x1 - x0
pads[1] += y1 - y0
return pads
def _get_pad(pad, loc):
pad_num = False
if isinstance(pad, Number):
pad_num = True
pad = [pad, pad]
pads = [-pad[0], -pad[1]]
if "center" in loc:
pads[0] *= -1
pads[1] *= -1
if "upper" in loc or "lower" in loc:
if pad_num:
pads[0] = 0
pads[1] *= -1
elif "left" in loc or "right" in loc:
if pad_num:
pads[1] = 0
pads[0] *= -1
if "left" in loc:
pads[0] *= -1
if "lower" in loc:
pads[1] *= -1
return pads
def _ez_inset(
parent_axes: matplotlib.axes.Axes,
width: float | str,
height: float | str,
pad: float | tuple[float, float] = 0.1,
loc: Literal[
"upper left",
"upper center",
"upper right",
"center left",
"center",
"center right",
"lower left",
"lower center",
"lower right",
] = "upper right",
**kwargs,
) -> matplotlib.axes.Axes:
fig = parent_axes.get_figure()
if fig is None:
raise RuntimeError("Parent axes is not attached to a figure")
locator = InsetAxesLocator(parent_axes, width, height, pad, loc)
ax_ = fig.add_axes(locator(parent_axes, None).bounds, **kwargs)
ax_.set_axes_locator(locator)
return ax_
class InsetAxesLocator:
def __init__(self, ax, width, height, pad, loc):
self._ax = ax
self._transAxes = ax.transAxes
self._width = width
self._height = height
self._loc = loc
self.set_pad(pad)
def __call__(self, ax, renderer):
return matplotlib.transforms.TransformedBbox(
matplotlib.transforms.Bbox.from_bounds(*self._size_to_bounds(ax)),
self._transAxes
+ matplotlib.transforms.ScaledTranslation(
self.pads[0], self.pads[1], ax.figure.dpi_scale_trans
)
- ax.figure.transSubfigure,
)
def set_pad(self, pad):
pad_num = False
if isinstance(pad, Number):
pad_num = True
pad = [pad, pad]
self.pads = [-pad[0], -pad[1]]
if "center" in self._loc:
self.pads[0] *= -1
self.pads[1] *= -1
if "upper" in self._loc or "lower" in self._loc:
if pad_num:
self.pads[0] = 0
self.pads[1] *= -1
elif "left" in self._loc or "right" in self._loc:
if pad_num:
self.pads[1] = 0
self.pads[0] *= -1
if "left" in self._loc:
self.pads[0] *= -1
if "lower" in self._loc:
self.pads[1] *= -1
def add_pad(self, delta):
self.pads[0] += delta[0]
self.pads[1] += delta[1]
def sizes(self, ax):
ax_sizes = (
ax.get_window_extent()
.transformed(ax.figure.dpi_scale_trans.inverted())
.bounds[2:]
)
return [
float(sz[:-1]) / 100 if isinstance(sz, str) else sz / ax_sizes[i]
for i, sz in enumerate([self._width, self._height])
]
def _size_to_bounds(self, ax):
sizes = self.sizes(ax)
origin = [1 - sizes[0], 1 - sizes[1]]
if "center" in self._loc:
origin[0] /= 2
origin[1] /= 2
if "upper" in self._loc or "lower" in self._loc:
origin[1] *= 2
elif "left" in self._loc or "right" in self._loc:
origin[0] *= 2
if "left" in self._loc:
origin[0] = 0
if "lower" in self._loc:
origin[1] = 0
return origin + sizes
def _gen_cax(ax, width=4.0, aspect=7.0, pad=3.0, horiz=False, **kwargs):
w, h = width / 72, aspect * width / 72
if horiz:
cax = _ez_inset(ax, h, w, pad=(0, -w - pad / 72), **kwargs)
else:
cax = _ez_inset(ax, w, h, pad=(-w - pad / 72, 0), **kwargs)
return cax
def nice_colorbar(
ax: matplotlib.axes.Axes | Iterable[matplotlib.axes.Axes] | None = None,
mappable: matplotlib.cm.ScalarMappable | None = None,
width: float = 8.0,
aspect: float = 5.0,
pad: float = 3.0,
minmax: bool = False,
orientation: Literal["vertical", "horizontal"] = "vertical",
floating=False,
ticklabels: Sequence[str] | None = None,
**kwargs,
):
r"""Create a colorbar with fixed width and aspect to ensure uniformity of plots.
Parameters
----------
ax
The `matplotlib.axes.Axes` instance in which the colorbar is drawn.
mappable
The mappable whose colormap and norm will be used.
width
The width of the colorbar in points.
aspect
aspect ratio of the colorbar.
pad
The pad between the colorbar and axes in points.
minmax
If `False`, the ticks and the ticklabels will be determined from the keyword
arguments (the default). If `True`, the minimum and maximum of the colorbar will
be labeled.
orientation
Colorbar orientation.
**kwargs
Keyword arguments are passed to `proportional_colorbar`.
Returns
-------
cbar : matplotlib.colorbar.Colorbar
The created colorbar.
"""
is_horizontal = orientation == "horizontal"
if ax is None:
ax = plt.gca()
if floating:
if isinstance(ax, np.ndarray):
if ax.ndim == 1:
parent = ax[-1]
elif ax.ndim == 2:
parent = ax[0, -1]
else:
raise ValueError
else:
parent = ax
cbar = proportional_colorbar(
mappable=mappable,
ax=ax,
cax=_gen_cax(parent, width, aspect, pad, is_horizontal),
orientation=orientation,
**kwargs,
)
else:
if isinstance(ax, Iterable):
if not isinstance(ax, np.ndarray):
ax = np.array(ax, dtype=object)
bbox = matplotlib.transforms.Bbox.union(
[
x.get_position(original=True)
.frozen()
.transformed(x.figure.transFigure)
.transformed(x.figure.dpi_scale_trans.inverted())
for x in ax.flat
]
)
else:
fig = ax.get_figure()
if fig is None:
raise RuntimeError("Axes is not attached to a figure")
bbox = (
ax.get_position(original=True)
.frozen()
.transformed(fig.transFigure)
.transformed(fig.dpi_scale_trans.inverted())
)
if orientation == "horizontal":
kwargs["anchor"] = (1, 1)
kwargs["location"] = "top"
kwargs["fraction"] = width / (72 * bbox.height)
kwargs["pad"] = pad / (72 * bbox.height)
kwargs["shrink"] = width * aspect / (72 * bbox.width)
else:
kwargs["anchor"] = (0, 1)
kwargs["fraction"] = width / (72 * bbox.width)
kwargs["pad"] = pad / (72 * bbox.width)
kwargs["shrink"] = width * aspect / (72 * bbox.height)
cbar = proportional_colorbar(
mappable=mappable,
ax=ax,
aspect=aspect,
panchor=(0, 1),
orientation=orientation,
**kwargs,
)
if minmax:
if is_horizontal:
cbar.set_ticks(cbar.ax.get_xlim())
else:
cbar.set_ticks(cbar.ax.get_ylim())
cbar.set_ticklabels(("Min", "Max"))
cbar.ax.tick_params(labelsize="small")
if ticklabels is not None:
cbar.set_ticklabels(ticklabels)
if is_horizontal:
cbar.ax.set_box_aspect(1 / aspect)
else:
cbar.ax.set_box_aspect(aspect)
return cbar
def flatten_transparency(rgba: npt.NDArray, background: RGBColorType | None = None):
"""
Flatten the transparency of an RGBA image by blending it with a background color.
Parameters
----------
rgba
The input RGBA image as a numpy array.
background : RGBColorType, optional
The background color to blend with. Defaults to white.
"""
if background is None:
background = (1, 1, 1)
else:
background = matplotlib.colors.to_rgb(background)
original_shape = rgba.shape
rgba = rgba.reshape(-1, 4)
rgb = rgba[:, :-1]
a = rgba[:, -1][:, np.newaxis]
rgb *= a
rgb += (1 - a) * background
return rgb.reshape(original_shape[:-1] + (3,))
def _get_segment_for_color(
cmap: matplotlib.colors.LinearSegmentedColormap,
color: Literal["red", "green", "blue", "alpha"],
) -> Any:
if hasattr(cmap, "_segmentdata"):
if color in cmap._segmentdata:
return cmap._segmentdata[color]
return None
def _is_segment_iterable(cmap: matplotlib.colors.Colormap) -> bool:
if not isinstance(cmap, matplotlib.colors.LinearSegmentedColormap):
return False
if any(callable(_get_segment_for_color(cmap, c)) for c in ["red", "green", "blue"]): # type: ignore[arg-type]
return False
return True