Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
1691 lines (1448 loc) · 61.6 KB

File metadata and controls

1691 lines (1448 loc) · 61.6 KB
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
'''
Colorbar toolkit with two classes and a function:
:class:`ColorbarBase`
the base class with full colorbar drawing functionality.
It can be used as-is to make a colorbar for a given colormap;
a mappable object (e.g., image) is not needed.
:class:`Colorbar`
the derived class for use with images or contour plots.
:func:`make_axes`
a function for resizing an axes and adding a second axes
suitable for a colorbar
The :meth:`~matplotlib.figure.Figure.colorbar` method uses :func:`make_axes`
and :class:`Colorbar`; the :func:`~matplotlib.pyplot.colorbar` function
is a thin wrapper over :meth:`~matplotlib.figure.Figure.colorbar`.
'''
import copy
import logging
import numpy as np
import matplotlib as mpl
import matplotlib.artist as martist
import matplotlib.cbook as cbook
import matplotlib.collections as collections
import matplotlib.colors as colors
import matplotlib.contour as contour
import matplotlib.cm as cm
import matplotlib.gridspec as gridspec
import matplotlib.patches as mpatches
import matplotlib.path as mpath
import matplotlib.ticker as ticker
import matplotlib.transforms as mtransforms
import matplotlib._layoutbox as layoutbox
import matplotlib._constrained_layout as constrained_layout
from matplotlib import docstring
_log = logging.getLogger(__name__)
make_axes_kw_doc = '''
============= ====================================================
Property Description
============= ====================================================
*orientation* vertical or horizontal
*fraction* 0.15; fraction of original axes to use for colorbar
*pad* 0.05 if vertical, 0.15 if horizontal; fraction
of original axes between colorbar and new image axes
*shrink* 1.0; fraction by which to multiply the size of the colorbar
*aspect* 20; ratio of long to short dimensions
*anchor* (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal;
the anchor point of the colorbar axes
*panchor* (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal;
the anchor point of the colorbar parent axes. If
False, the parent axes' anchor will be unchanged
============= ====================================================
'''
colormap_kw_doc = '''
============ ====================================================
Property Description
============ ====================================================
*extend* {'neither', 'both', 'min', 'max'}
If not 'neither', make pointed end(s) for out-of-
range values. These are set for a given colormap
using the colormap set_under and set_over methods.
*extendfrac* {*None*, 'auto', length, lengths}
If set to *None*, both the minimum and maximum
triangular colorbar extensions with have a length of
5% of the interior colorbar length (this is the
default setting). If set to 'auto', makes the
triangular colorbar extensions the same lengths as
the interior boxes (when *spacing* is set to
'uniform') or the same lengths as the respective
adjacent interior boxes (when *spacing* is set to
'proportional'). If a scalar, indicates the length
of both the minimum and maximum triangular colorbar
extensions as a fraction of the interior colorbar
length. A two-element sequence of fractions may also
be given, indicating the lengths of the minimum and
maximum colorbar extensions respectively as a
fraction of the interior colorbar length.
*extendrect* bool
If *False* the minimum and maximum colorbar extensions
will be triangular (the default). If *True* the
extensions will be rectangular.
*spacing* {'uniform', 'proportional'}
Uniform spacing gives each discrete color the same
space; proportional makes the space proportional to
the data interval.
*ticks* *None* or list of ticks or Locator
If None, ticks are determined automatically from the
input.
*format* None or str or Formatter
If None, the
:class:`~matplotlib.ticker.ScalarFormatter` is used.
If a format string is given, e.g., '%.3f', that is
used. An alternative
:class:`~matplotlib.ticker.Formatter` object may be
given instead.
*drawedges* bool
Whether to draw lines at color boundaries.
*label* str
The label on the colorbar's long axis.
============ ====================================================
The following will probably be useful only in the context of
indexed colors (that is, when the mappable has norm=NoNorm()),
or other unusual circumstances.
============ ===================================================
Property Description
============ ===================================================
*boundaries* None or a sequence
*values* None or a sequence which must be of length 1 less
than the sequence of *boundaries*. For each region
delimited by adjacent entries in *boundaries*, the
color mapped to the corresponding value in values
will be used.
============ ===================================================
'''
colorbar_doc = '''
Add a colorbar to a plot.
Function signatures for the :mod:`~matplotlib.pyplot` interface; all
but the first are also method signatures for the
:meth:`~matplotlib.figure.Figure.colorbar` method::
colorbar(**kwargs)
colorbar(mappable, **kwargs)
colorbar(mappable, cax=cax, **kwargs)
colorbar(mappable, ax=ax, **kwargs)
Parameters
----------
mappable
The `matplotlib.cm.ScalarMappable` (i.e., `~matplotlib.image.Image`,
`~matplotlib.contour.ContourSet`, etc.) described by this colorbar.
This argument is mandatory for the `.Figure.colorbar` method but optional
for the `.pyplot.colorbar` function, which sets the default to the current
image.
Note that one can create a `ScalarMappable` "on-the-fly" to generate
colorbars not attached to a previously drawn artist, e.g. ::
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
cax : :class:`~matplotlib.axes.Axes` object, optional
Axes into which the colorbar will be drawn.
ax : :class:`~matplotlib.axes.Axes`, list of Axes, optional
Parent axes from which space for a new colorbar axes will be stolen.
If a list of axes is given they will all be resized to make room for the
colorbar axes.
use_gridspec : bool, optional
If *cax* is ``None``, a new *cax* is created as an instance of Axes. If
*ax* is an instance of Subplot and *use_gridspec* is ``True``, *cax* is
created as an instance of Subplot using the :mod:`~.gridspec` module.
Returns
-------
colorbar : `~matplotlib.colorbar.Colorbar`
See also its base class, `~matplotlib.colorbar.ColorbarBase`.
Notes
-----
Additional keyword arguments are of two kinds:
axes properties:
%s
colorbar properties:
%s
If *mappable* is a :class:`~matplotlib.contours.ContourSet`, its *extend*
kwarg is included automatically.
The *shrink* kwarg provides a simple way to scale the colorbar with respect
to the axes. Note that if *cax* is specified, it determines the size of the
colorbar and *shrink* and *aspect* kwargs are ignored.
For more precise control, you can manually specify the positions of
the axes objects in which the mappable and the colorbar are drawn. In
this case, do not use any of the axes properties kwargs.
It is known that some vector graphics viewers (svg and pdf) renders white gaps
between segments of the colorbar. This is due to bugs in the viewers, not
Matplotlib. As a workaround, the colorbar can be rendered with overlapping
segments::
cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
However this has negative consequences in other circumstances, e.g. with
semi-transparent images (alpha < 1) and colorbar extensions; therefore, this
workaround is not used by default (see issue #1188).
''' % (make_axes_kw_doc, colormap_kw_doc)
docstring.interpd.update(colorbar_doc=colorbar_doc)
def _set_ticks_on_axis_warn(*args, **kw):
# a top level function which gets put in at the axes'
# set_xticks set_yticks by _patch_ax
cbook._warn_external("Use the colorbar set_ticks() method instead.")
class _ColorbarAutoLocator(ticker.MaxNLocator):
"""
AutoLocator for Colorbar
This locator is just a `.MaxNLocator` except the min and max are
clipped by the norm's min and max (i.e. vmin/vmax from the
image/pcolor/contour object). This is necessary so ticks don't
extrude into the "extend regions".
"""
def __init__(self, colorbar):
"""
This ticker needs to know the *colorbar* so that it can access
its *vmin* and *vmax*. Otherwise it is the same as
`~.ticker.AutoLocator`.
"""
self._colorbar = colorbar
nbins = 'auto'
steps = [1, 2, 2.5, 5, 10]
super().__init__(nbins=nbins, steps=steps)
def tick_values(self, vmin, vmax):
# flip if needed:
if vmin > vmax:
vmin, vmax = vmax, vmin
vmin = max(vmin, self._colorbar.norm.vmin)
vmax = min(vmax, self._colorbar.norm.vmax)
ticks = super().tick_values(vmin, vmax)
rtol = (vmax - vmin) * 1e-10
return ticks[(ticks >= vmin - rtol) & (ticks <= vmax + rtol)]
class _ColorbarAutoMinorLocator(ticker.AutoMinorLocator):
"""
AutoMinorLocator for Colorbar
This locator is just a `.AutoMinorLocator` except the min and max are
clipped by the norm's min and max (i.e. vmin/vmax from the
image/pcolor/contour object). This is necessary so that the minorticks
don't extrude into the "extend regions".
"""
def __init__(self, colorbar, n=None):
"""
This ticker needs to know the *colorbar* so that it can access
its *vmin* and *vmax*.
"""
self._colorbar = colorbar
self.ndivs = n
super().__init__(n=None)
def __call__(self):
vmin = self._colorbar.norm.vmin
vmax = self._colorbar.norm.vmax
ticks = super().__call__()
rtol = (vmax - vmin) * 1e-10
return ticks[(ticks >= vmin - rtol) & (ticks <= vmax + rtol)]
class _ColorbarLogLocator(ticker.LogLocator):
"""
LogLocator for Colorbarbar
This locator is just a `.LogLocator` except the min and max are
clipped by the norm's min and max (i.e. vmin/vmax from the
image/pcolor/contour object). This is necessary so ticks don't
extrude into the "extend regions".
"""
def __init__(self, colorbar, *args, **kwargs):
"""
_ColorbarLogLocator(colorbar, *args, **kwargs)
This ticker needs to know the *colorbar* so that it can access
its *vmin* and *vmax*. Otherwise it is the same as
`~.ticker.LogLocator`. The ``*args`` and ``**kwargs`` are the
same as `~.ticker.LogLocator`.
"""
self._colorbar = colorbar
super().__init__(*args, **kwargs)
def tick_values(self, vmin, vmax):
if vmin > vmax:
vmin, vmax = vmax, vmin
vmin = max(vmin, self._colorbar.norm.vmin)
vmax = min(vmax, self._colorbar.norm.vmax)
ticks = super().tick_values(vmin, vmax)
rtol = (np.log10(vmax) - np.log10(vmin)) * 1e-10
ticks = ticks[(np.log10(ticks) >= np.log10(vmin) - rtol) &
(np.log10(ticks) <= np.log10(vmax) + rtol)]
return ticks
class _ColorbarMappableDummy:
"""
Private class to hold deprecated ColorbarBase methods that used to be
inhereted from ScalarMappable.
"""
@cbook.deprecated("3.1", alternative="ScalarMappable.set_norm")
def set_norm(self, norm):
"""
`.colorbar.Colorbar.set_norm` does nothing; set the norm on
the mappable associated with this colorbar.
"""
pass
@cbook.deprecated("3.1", alternative="ScalarMappable.set_cmap")
def set_cmap(self, cmap):
"""
`.colorbar.Colorbar.set_cmap` does nothing; set the norm on
the mappable associated with this colorbar.
"""
pass
@cbook.deprecated("3.1", alternative="ScalarMappable.set_clim")
def set_clim(self, vmin=None, vmax=None):
"""
`.colorbar.Colorbar.set_clim` does nothing; set the limits on
the mappable associated with this colorbar.
"""
pass
@cbook.deprecated("3.1", alternative="ScalarMappable.get_cmap")
def get_cmap(self):
"""Return the colormap."""
return self.cmap
@cbook.deprecated("3.1", alternative="ScalarMappable.get_clim")
def get_clim(self):
"""Return the min, max of the color limits for image scaling."""
return self.norm.vmin, self.norm.vmax
class ColorbarBase(_ColorbarMappableDummy):
r"""
Draw a colorbar in an existing axes.
There are only some rare cases in which you would work directly with a
`.ColorbarBase` as an end-user. Typically, colorbars are used
with `.ScalarMappable`\s such as an `.AxesImage` generated via
`~.axes.Axes.imshow`. For these cases you will use `.Colorbar` and
likely create it via `.pyplot.colorbar` or `.Figure.colorbar`.
The main application of using a `.ColorbarBase` explicitly is drawing
colorbars that are not associated with other elements in the figure, e.g.
when showing a colormap by itself.
If the *cmap* kwarg is given but *boundaries* and *values* are left as
None, then the colormap will be displayed on a 0-1 scale. To show the
under- and over-value colors, specify the *norm* as::
norm=colors.Normalize(clip=False)
To show the colors versus index instead of on the 0-1 scale,
use::
norm=colors.NoNorm()
Useful public methods are :meth:`set_label` and :meth:`add_lines`.
Attributes
----------
ax : `~matplotlib.axes.Axes`
The `~.axes.Axes` instance in which the colorbar is drawn.
lines : list
A list of `.LineCollection` if lines were drawn, otherwise
an empty list.
dividers : `.LineCollection`
A LineCollection if *drawedges* is ``True``, otherwise ``None``.
Parameters
----------
ax : `~matplotlib.axes.Axes`
The `~.axes.Axes` instance in which the colorbar is drawn.
cmap : `~matplotlib.colors.Colormap` or None
The colormap to use. If *None*, use :rc:`image.cmap`.
norm : `~matplotlib.colors.Normalize`
alpha : float
values
boundaries
orientation : {'vertical', 'horizontal'}
ticklocation : {'auto', 'left', 'right', 'top', 'bottom'}
extend : {'neither', 'both', 'min', 'max'}
spacing : {'uniform', 'proportional'}
ticks : `~matplotlib.ticker.Locator` or array-like of float
format : str or `~matplotlib.ticker.Formatter`
drawedges : bool
filled : bool
extendfrac
extendrec
label : str
"""
_slice_dict = {'neither': slice(0, None),
'both': slice(1, -1),
'min': slice(1, None),
'max': slice(0, -1)}
n_rasterize = 50 # rasterize solids if number of colors >= n_rasterize
def __init__(self, ax, cmap=None,
norm=None,
alpha=None,
values=None,
boundaries=None,
orientation='vertical',
ticklocation='auto',
extend='neither',
spacing='uniform', # uniform or proportional
ticks=None,
format=None,
drawedges=False,
filled=True,
extendfrac=None,
extendrect=False,
label='',
):
cbook._check_isinstance([colors.Colormap, None], cmap=cmap)
cbook._check_in_list(
['vertical', 'horizontal'], orientation=orientation)
cbook._check_in_list(
['auto', 'left', 'right', 'top', 'bottom'],
ticklocation=ticklocation)
cbook._check_in_list(
self._slice_dict, extend=extend)
cbook._check_in_list(
['uniform', 'proportional'], spacing=spacing)
self.ax = ax
self._patch_ax()
if cmap is None:
cmap = cm.get_cmap()
if norm is None:
norm = colors.Normalize()
self.alpha = alpha
self.cmap = cmap
self.norm = norm
self.values = values
self.boundaries = boundaries
self.extend = extend
self._inside = self._slice_dict[extend]
self.spacing = spacing
self.orientation = orientation
self.drawedges = drawedges
self.filled = filled
self.extendfrac = extendfrac
self.extendrect = extendrect
self.solids = None
self.lines = list()
self.outline = None
self.patch = None
self.dividers = None
self.locator = None
self.formatter = None
self._manual_tick_data_values = None
self.__scale = None # linear, log10 for now. Hopefully more?
if ticklocation == 'auto':
ticklocation = 'bottom' if orientation == 'horizontal' else 'right'
self.ticklocation = ticklocation
self.set_label(label)
self._reset_locator_formatter_scale()
if np.iterable(ticks):
self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
else:
self.locator = ticks # Handle default in _ticker()
if isinstance(format, str):
self.formatter = ticker.FormatStrFormatter(format)
else:
self.formatter = format # Assume it is a Formatter or None
self.draw_all()
def _extend_lower(self):
"""Return whether the lower limit is open ended."""
return self.extend in ('both', 'min')
def _extend_upper(self):
"""Return whether the uper limit is open ended."""
return self.extend in ('both', 'max')
def _patch_ax(self):
# bind some methods to the axes to warn users
# against using those methods.
self.ax.set_xticks = _set_ticks_on_axis_warn
self.ax.set_yticks = _set_ticks_on_axis_warn
def draw_all(self):
'''
Calculate any free parameters based on the current cmap and norm,
and do all the drawing.
'''
# sets self._boundaries and self._values in real data units.
# takes into account extend values:
self._process_values()
# sets self.vmin and vmax in data units, but just for
# the part of the colorbar that is not part of the extend
# patch:
self._find_range()
# returns the X and Y mesh, *but* this was/is in normalized
# units:
X, Y = self._mesh()
C = self._values[:, np.newaxis]
# decide minor/major axis
self.config_axis()
self._config_axes(X, Y)
if self.filled:
self._add_solids(X, Y, C)
def config_axis(self):
ax = self.ax
if self.orientation == 'vertical':
long_axis, short_axis = ax.yaxis, ax.xaxis
else:
long_axis, short_axis = ax.xaxis, ax.yaxis
long_axis.set_label_position(self.ticklocation)
long_axis.set_ticks_position(self.ticklocation)
short_axis.set_ticks([])
short_axis.set_ticks([], minor=True)
self._set_label()
def _get_ticker_locator_formatter(self):
"""
This code looks at the norm being used by the colorbar
and decides what locator and formatter to use. If ``locator`` has
already been set by hand, it just returns
``self.locator, self.formatter``.
"""
locator = self.locator
formatter = self.formatter
if locator is None:
if self.boundaries is None:
if isinstance(self.norm, colors.NoNorm):
nv = len(self._values)
base = 1 + int(nv / 10)
locator = ticker.IndexLocator(base=base, offset=0)
elif isinstance(self.norm, colors.BoundaryNorm):
b = self.norm.boundaries
locator = ticker.FixedLocator(b, nbins=10)
elif isinstance(self.norm, colors.LogNorm):
locator = _ColorbarLogLocator(self)
elif isinstance(self.norm, colors.SymLogNorm):
# The subs setting here should be replaced
# by logic in the locator.
locator = ticker.SymmetricalLogLocator(
subs=np.arange(1, 10),
linthresh=self.norm.linthresh,
base=10)
else:
if mpl.rcParams['_internal.classic_mode']:
locator = ticker.MaxNLocator()
else:
locator = _ColorbarAutoLocator(self)
else:
b = self._boundaries[self._inside]
locator = ticker.FixedLocator(b, nbins=10)
if formatter is None:
if isinstance(self.norm, colors.LogNorm):
formatter = ticker.LogFormatterSciNotation()
elif isinstance(self.norm, colors.SymLogNorm):
formatter = ticker.LogFormatterSciNotation(
linthresh=self.norm.linthresh)
else:
formatter = ticker.ScalarFormatter()
else:
formatter = self.formatter
self.locator = locator
self.formatter = formatter
_log.debug('locator: %r', locator)
return locator, formatter
def _use_auto_colorbar_locator(self):
"""
Return if we should use an adjustable tick locator or a fixed
one. (check is used twice so factored out here...)
"""
contouring = self.boundaries is not None and self.spacing == 'uniform'
return (type(self.norm) in [colors.Normalize, colors.LogNorm] and
not contouring)
def _reset_locator_formatter_scale(self):
"""
Reset the locator et al to defaults. Any user-hardcoded changes
need to be re-entered if this gets called (either at init, or when
the mappable normal gets changed: Colorbar.update_normal)
"""
self.locator = None
self.formatter = None
if (isinstance(self.norm, colors.LogNorm)):
# *both* axes are made log so that determining the
# mid point is easier.
self.ax.set_xscale('log')
self.ax.set_yscale('log')
self.minorticks_on()
self.__scale = 'log'
else:
self.ax.set_xscale('linear')
self.ax.set_yscale('linear')
if type(self.norm) is colors.Normalize:
self.__scale = 'linear'
else:
self.__scale = 'manual'
def update_ticks(self):
"""
Force the update of the ticks and ticklabels. This must be
called whenever the tick locator and/or tick formatter changes.
"""
ax = self.ax
# Get the locator and formatter; defaults to self.locator if not None.
locator, formatter = self._get_ticker_locator_formatter()
long_axis = ax.yaxis if self.orientation == 'vertical' else ax.xaxis
if self._use_auto_colorbar_locator():
_log.debug('Using auto colorbar locator on colorbar')
_log.debug('locator: %r', locator)
long_axis.set_major_locator(locator)
long_axis.set_major_formatter(formatter)
else:
_log.debug('Using fixed locator on colorbar')
ticks, ticklabels, offset_string = self._ticker(locator, formatter)
long_axis.set_ticks(ticks)
long_axis.set_ticklabels(ticklabels)
long_axis.get_major_formatter().set_offset_string(offset_string)
def set_ticks(self, ticks, update_ticks=True):
"""
Set tick locations.
Parameters
----------
ticks : {None, sequence, :class:`~matplotlib.ticker.Locator` instance}
If None, a default Locator will be used.
update_ticks : {True, False}, optional
If True, tick locations are updated immediately. If False,
use :meth:`update_ticks` to manually update the ticks.
"""
if np.iterable(ticks):
self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
else:
self.locator = ticks
if update_ticks:
self.update_ticks()
self.stale = True
def get_ticks(self, minor=False):
"""Return the x ticks as a list of locations."""
if self._manual_tick_data_values is None:
ax = self.ax
long_axis = (
ax.yaxis if self.orientation == 'vertical' else ax.xaxis)
return long_axis.get_majorticklocs()
else:
# We made the axes manually, the old way, and the ylim is 0-1,
# so the majorticklocs are in those units, not data units.
return self._manual_tick_data_values
def set_ticklabels(self, ticklabels, update_ticks=True):
"""
Set tick labels.
Tick labels are updated immediately unless *update_ticks* is *False*,
in which case one should call `.update_ticks` explicitly.
"""
if isinstance(self.locator, ticker.FixedLocator):
self.formatter = ticker.FixedFormatter(ticklabels)
if update_ticks:
self.update_ticks()
else:
cbook._warn_external("set_ticks() must have been called.")
self.stale = True
def minorticks_on(self):
"""
Turns on the minor ticks on the colorbar without extruding
into the "extend regions".
"""
ax = self.ax
long_axis = ax.yaxis if self.orientation == 'vertical' else ax.xaxis
if long_axis.get_scale() == 'log':
long_axis.set_minor_locator(_ColorbarLogLocator(self, base=10.,
subs='auto'))
long_axis.set_minor_formatter(ticker.LogFormatterSciNotation())
else:
long_axis.set_minor_locator(_ColorbarAutoMinorLocator(self))
def minorticks_off(self):
"""
Turns off the minor ticks on the colorbar.
"""
ax = self.ax
long_axis = ax.yaxis if self.orientation == 'vertical' else ax.xaxis
long_axis.set_minor_locator(ticker.NullLocator())
def _config_axes(self, X, Y):
'''
Make an axes patch and outline.
'''
ax = self.ax
ax.set_frame_on(False)
ax.set_navigate(False)
xy = self._outline(X, Y)
ax.ignore_existing_data_limits = True
ax.update_datalim(xy)
ax.set_xlim(*ax.dataLim.intervalx)
ax.set_ylim(*ax.dataLim.intervaly)
if self.outline is not None:
self.outline.remove()
self.outline = mpatches.Polygon(
xy, edgecolor=mpl.rcParams['axes.edgecolor'],
facecolor='none',
linewidth=mpl.rcParams['axes.linewidth'],
closed=True,
zorder=2)
ax.add_artist(self.outline)
self.outline.set_clip_box(None)
self.outline.set_clip_path(None)
c = mpl.rcParams['axes.facecolor']
if self.patch is not None:
self.patch.remove()
self.patch = mpatches.Polygon(xy, edgecolor=c,
facecolor=c,
linewidth=0.01,
zorder=-1)
ax.add_artist(self.patch)
self.update_ticks()
def _set_label(self):
if self.orientation == 'vertical':
self.ax.set_ylabel(self._label, **self._labelkw)
else:
self.ax.set_xlabel(self._label, **self._labelkw)
self.stale = True
def set_label(self, label, **kw):
"""Label the long axis of the colorbar."""
self._label = label
self._labelkw = kw
self._set_label()
def _outline(self, X, Y):
'''
Return *x*, *y* arrays of colorbar bounding polygon,
taking orientation into account.
'''
N = X.shape[0]
ii = [0, 1, N - 2, N - 1, 2 * N - 1, 2 * N - 2, N + 1, N, 0]
x = X.T.reshape(-1)[ii]
y = Y.T.reshape(-1)[ii]
return (np.column_stack([y, x])
if self.orientation == 'horizontal' else
np.column_stack([x, y]))
def _edges(self, X, Y):
'''
Return the separator line segments; helper for _add_solids.
'''
N = X.shape[0]
# Using the non-array form of these line segments is much
# simpler than making them into arrays.
if self.orientation == 'vertical':
return [list(zip(X[i], Y[i])) for i in range(1, N - 1)]
else:
return [list(zip(Y[i], X[i])) for i in range(1, N - 1)]
def _add_solids(self, X, Y, C):
'''
Draw the colors using :meth:`~matplotlib.axes.Axes.pcolormesh`;
optionally add separators.
'''
if self.orientation == 'vertical':
args = (X, Y, C)
else:
args = (np.transpose(Y), np.transpose(X), np.transpose(C))
kw = dict(cmap=self.cmap,
norm=self.norm,
alpha=self.alpha,
edgecolors='None')
_log.debug('Setting pcolormesh')
col = self.ax.pcolormesh(*args, **kw)
# self.add_observer(col) # We should observe, not be observed...
if self.solids is not None:
self.solids.remove()
self.solids = col
if self.dividers is not None:
self.dividers.remove()
self.dividers = None
if self.drawedges:
linewidths = (0.5 * mpl.rcParams['axes.linewidth'],)
self.dividers = collections.LineCollection(
self._edges(X, Y),
colors=(mpl.rcParams['axes.edgecolor'],),
linewidths=linewidths)
self.ax.add_collection(self.dividers)
elif len(self._y) >= self.n_rasterize:
self.solids.set_rasterized(True)
def add_lines(self, levels, colors, linewidths, erase=True):
'''
Draw lines on the colorbar.
*colors* and *linewidths* must be scalars or
sequences the same length as *levels*.
Set *erase* to False to add lines without first
removing any previously added lines.
'''
y = self._locate(levels)
rtol = (self._y[-1] - self._y[0]) * 1e-10
igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol)
y = y[igood]
if np.iterable(colors):
colors = np.asarray(colors)[igood]
if np.iterable(linewidths):
linewidths = np.asarray(linewidths)[igood]
X, Y = np.meshgrid([self._y[0], self._y[-1]], y)
if self.orientation == 'vertical':
xy = np.stack([X, Y], axis=-1)
else:
xy = np.stack([Y, X], axis=-1)
col = collections.LineCollection(xy, linewidths=linewidths)
if erase and self.lines:
for lc in self.lines:
lc.remove()
self.lines = []
self.lines.append(col)
col.set_color(colors)
self.ax.add_collection(col)
self.stale = True
def _ticker(self, locator, formatter):
'''
Return the sequence of ticks (colorbar data locations),
ticklabels (strings), and the corresponding offset string.
'''
if isinstance(self.norm, colors.NoNorm) and self.boundaries is None:
intv = self._values[0], self._values[-1]
else:
intv = self.vmin, self.vmax
locator.create_dummy_axis(minpos=intv[0])
formatter.create_dummy_axis(minpos=intv[0])
locator.set_view_interval(*intv)
locator.set_data_interval(*intv)
formatter.set_view_interval(*intv)
formatter.set_data_interval(*intv)
b = np.array(locator())
if isinstance(locator, ticker.LogLocator):
eps = 1e-10
b = b[(b <= intv[1] * (1 + eps)) & (b >= intv[0] * (1 - eps))]
else:
eps = (intv[1] - intv[0]) * 1e-10
b = b[(b <= intv[1] + eps) & (b >= intv[0] - eps)]
self._manual_tick_data_values = b
ticks = self._locate(b)
ticklabels = formatter.format_ticks(b)
offset_string = formatter.get_offset()
return ticks, ticklabels, offset_string
def _process_values(self, b=None):
'''
Set the :attr:`_boundaries` and :attr:`_values` attributes
based on the input boundaries and values. Input boundaries
can be *self.boundaries* or the argument *b*.
'''
if b is None:
b = self.boundaries
if b is not None:
self._boundaries = np.asarray(b, dtype=float)
if self.values is None:
self._values = 0.5 * (self._boundaries[:-1]
+ self._boundaries[1:])
if isinstance(self.norm, colors.NoNorm):
self._values = (self._values + 0.00001).astype(np.int16)
else:
self._values = np.array(self.values)
return
if self.values is not None:
self._values = np.array(self.values)
if self.boundaries is None:
b = np.zeros(len(self.values) + 1)
b[1:-1] = 0.5 * (self._values[:-1] + self._values[1:])
b[0] = 2.0 * b[1] - b[2]
b[-1] = 2.0 * b[-2] - b[-3]
self._boundaries = b
return
self._boundaries = np.array(self.boundaries)
return
# Neither boundaries nor values are specified;
# make reasonable ones based on cmap and norm.
if isinstance(self.norm, colors.NoNorm):
b = self._uniform_y(self.cmap.N + 1) * self.cmap.N - 0.5
v = np.zeros(len(b) - 1, dtype=np.int16)
v[self._inside] = np.arange(self.cmap.N, dtype=np.int16)
if self._extend_lower():
v[0] = -1
if self._extend_upper():
v[-1] = self.cmap.N
self._boundaries = b
self._values = v
return
elif isinstance(self.norm, colors.BoundaryNorm):
b = list(self.norm.boundaries)
if self._extend_lower():
b = [b[0] - 1] + b
if self._extend_upper():
b = b + [b[-1] + 1]
b = np.array(b)
v = np.zeros(len(b) - 1)
bi = self.norm.boundaries
v[self._inside] = 0.5 * (bi[:-1] + bi[1:])
if self._extend_lower():
v[0] = b[0] - 1
if self._extend_upper():
v[-1] = b[-1] + 1
self._boundaries = b
self._values = v
return
else:
if not self.norm.scaled():
self.norm.vmin = 0
self.norm.vmax = 1
self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(
self.norm.vmin,
self.norm.vmax,
expander=0.1)
b = self.norm.inverse(self._uniform_y(self.cmap.N + 1))
if isinstance(self.norm, (colors.PowerNorm, colors.LogNorm)):
# If using a lognorm or powernorm, ensure extensions don't
# go negative
if self._extend_lower():
b[0] = 0.9 * b[0]
if self._extend_upper():
b[-1] = 1.1 * b[-1]
else:
if self._extend_lower():
b[0] = b[0] - 1
if self._extend_upper():
b[-1] = b[-1] + 1
self._process_values(b)
def _find_range(self):
'''
Set :attr:`vmin` and :attr:`vmax` attributes to the first and
last boundary excluding extended end boundaries.
'''
b = self._boundaries[self._inside]
self.vmin = b[0]
self.vmax = b[-1]
def _central_N(self):
"""Return the number of boundaries excluding end extensions."""
Morty Proxy This is a proxified and sanitized view of the page, visit original site.