/
axes.py
3449 lines (3256 loc) 路 155 KB
/
axes.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
#!/usr/bin/env python3
"""
This page documents the axes subclasses returned by
`~proplot.subplots.subplots` and their various method wrappers. You should
start with the documentation on the following methods.
* `Axes.format`
* `Axes.context`
* `CartesianAxes.format`
* `ProjectionAxes.format`
`Axes.format` and `Axes.context` are both called by
`CartesianAxes.format` and `ProjectionAxes.format`. ``format`` is your
**one-stop-shop for changing axes settings** like *x* and *y* axis limits,
axis labels, tick locations, tick labels grid lines, axis scales, titles,
a-b-c labelling, adding geographic features, and much more.
"""
import numpy as np
import warnings
import functools
from numbers import Integral
import matplotlib.projections as mproj
import matplotlib.axes as maxes
import matplotlib.dates as mdates
import matplotlib.scale as mscale
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.patches as mpatches
import matplotlib.gridspec as mgridspec
import matplotlib.transforms as mtransforms
import matplotlib.collections as mcollections
from . import utils, projs, axistools
from .utils import _notNone, units
from .rctools import rc, RC_NODOTSNAMES
from .wrappers import (
_get_transform, _norecurse, _redirect,
_add_errorbars, _bar_wrapper, _barh_wrapper, _boxplot_wrapper,
_default_crs, _default_latlon, _default_transform, _cmap_changer,
_cycle_changer, _fill_between_wrapper, _fill_betweenx_wrapper,
_hist_wrapper, _plot_wrapper, _scatter_wrapper,
_standardize_1d, _standardize_2d,
_text_wrapper, _violinplot_wrapper,
colorbar_wrapper, legend_wrapper,
)
try:
from cartopy.mpl.geoaxes import GeoAxes
except ModuleNotFoundError:
GeoAxes = object
__all__ = [
'Axes',
'BasemapAxes',
'CartesianAxes',
'CartopyAxes',
'PolarAxes', 'ProjectionAxes',
]
# Translator for inset colorbars and legends
SIDE_TRANSLATE = {
'l': 'left',
'r': 'right',
'b': 'bottom',
't': 'top',
}
LOC_TRANSLATE = {
None: None,
'inset': 'best',
'i': 'best',
0: 'best',
1: 'upper right',
2: 'upper left',
3: 'lower left',
4: 'lower right',
5: 'center left',
6: 'center right',
7: 'lower center',
8: 'upper center',
9: 'center',
'l': 'left',
'r': 'right',
'b': 'bottom',
't': 'top',
'c': 'center',
'ur': 'upper right',
'ul': 'upper left',
'll': 'lower left',
'lr': 'lower right',
'cr': 'center right',
'cl': 'center left',
'uc': 'upper center',
'lc': 'lower center',
}
# Helper function
ABC_STRING = 'abcdefghijklmnopqrstuvwxyz'
def _abc(i):
"""Function for a-b-c labeling, returns a...z...aa...zz...aaa...zzz."""
if i < 26:
return ABC_STRING[i]
else:
return _abc(i - 26) + ABC_STRING[i % 26] # sexy sexy recursion
# Wrapper generator
def _disable_decorator(msg):
"""Generates decorators that disable methods. Also sets __doc__ to None so
that ProPlot fork of automodapi doesn't add these methods to the website
documentation. Users can still call help(ax.method) because python looks
for superclass method docstrings if a docstring is empty."""
def decorator(func):
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
raise RuntimeError(msg.format(func.__name__))
_wrapper.__doc__ = None
return _wrapper
return decorator
#-----------------------------------------------------------------------------#
# Generalized custom axes class
#-----------------------------------------------------------------------------#
class Axes(maxes.Axes):
"""Lowest-level axes subclass. Handles titles and axis
sharing. Adds several new methods and overrides existing ones."""
def __init__(self, *args, number=None,
sharex=0, sharey=0,
spanx=None, spany=None, alignx=None, aligny=None,
main=False,
**kwargs):
"""
Parameters
----------
number : int
The subplot number, used for a-b-c labelling (see
`~Axes.format`).
sharex, sharey : {3, 2, 1, 0}, optional
The "axis sharing level" for the *x* axis, *y* axis, or both
axes. See `~proplot.subplots.subplots` for details.
spanx, spany : bool, optional
Boolean toggle for whether spanning labels are enabled for the
*x* and *y* axes. See `~proplot.subplots.subplots` for details.
alignx, aligny : bool, optional
Boolean toggle for whether aligned axis labels are enabled for the
*x* and *y* axes. See `~proplot.subplots.subplots` for details.
main : bool, optional
Used internally, indicates whether this is a "main axes" rather
than a twin, panel, or inset axes.
See also
--------
`~matplotlib.axes.Axes`, `CartesianAxes`, `PolarAxes`, `ProjectionAxes`
"""
# Call parent
super().__init__(*args, **kwargs)
# Properties
self._number = number # for abc numbering
self._abc_loc = None
self._abc_text = None
self._titles_dict = {} # dictionary of title text objects and their locations
self._title_loc = None # location of main title
self._title_pad = rc.get('axes.titlepad') # so we can copy to top panel
self._title_above_panel = True # TODO: add rc prop?
# Children and related properties
self._bpanels = []
self._tpanels = []
self._lpanels = []
self._rpanels = []
self._tight_bbox = None # bounding boxes are saved
self._panel_side = None
self._panel_share = False # True when panels "filled" with colorbar/legend
self._panel_parent = None
self._panel_filled = False # True when panels "filled" with colorbar/legend
self._inset_parent = None
self._inset_zoom = False
self._inset_zoom_data = None
self._alty_child = None
self._altx_child = None
self._alty_parent = None
self._altx_parent = None
self._auto_colorbar = {} # stores handles and kwargs for auto colorbar
self._auto_legend = {}
# Text labels
# TODO: Add text labels as panels instead of as axes children?
coltransform = mtransforms.blended_transform_factory(self.transAxes, self.figure.transFigure)
rowtransform = mtransforms.blended_transform_factory(self.figure.transFigure, self.transAxes)
self._llabel = self.text(0.05, 0.5, '', va='center', ha='right', transform=rowtransform)
self._rlabel = self.text(0.95, 0.5, '', va='center', ha='left', transform=rowtransform)
self._blabel = self.text(0.5, 0.05, '', va='top', ha='center', transform=coltransform)
self._tlabel = self.text(0.5, 0.95, '', va='bottom', ha='center', transform=coltransform) # reasonable starting point
# Shared and spanning axes
if main:
self.figure._axes_main.append(self)
self._spanx_on = spanx
self._spany_on = spany
self._alignx_on = alignx
self._aligny_on = aligny
self._sharex_level = sharex
self._sharey_level = sharey
self._share_setup()
self.format(mode=1) # mode == 1 applies the rcExtraParams
def _draw_auto_legends_colorbars(self):
"""Generate automatic legends and colorbars. Wrapper funcs
let user add handles to location lists with successive calls to
make successive calls to plotting commands."""
for loc,(handles,kwargs) in self._auto_colorbar.items():
self.colorbar(handles, **kwargs)
for loc,(handles,kwargs) in self._auto_legend.items():
self.legend(handles, **kwargs)
self._auto_legend = {}
self._auto_colorbar = {}
def _get_side_axes(self, side):
"""Returns axes whose left, right, top, or bottom side abutts
against the same row or column as this axes."""
s = side[0]
if s not in 'lrbt':
raise ValueError(f'Invalid side {side!r}.')
if not hasattr(self, 'get_subplotspec'):
return [self]
x = ('x' if s in 'lr' else 'y')
idx = (0 if s in 'lt' else 1) # which side of range to test
coord = self._range_gridspec(x)[idx] # side for a particular axes
axs = [ax for ax in self.figure._axes_main
if ax._range_gridspec(x)[idx] == coord]
if not axs:
return [self]
else:
return axs
def _get_extent_axes(self, x):
"""Returns axes whose horizontal or vertical extent in the main
gridspec matches the horizontal or vertical extend of this axes.
Also sorts the list so the leftmost or bottommost axes is at the
start of the list."""
if not hasattr(self, 'get_subplotspec'):
return [self]
y = ('y' if x == 'x' else 'x')
idx = (0 if x == 'x' else 1)
argfunc = (np.argmax if x == 'x' else np.argmin)
irange = self._range_gridspec(x)
axs = [ax for ax in self.figure._axes_main
if ax._range_gridspec(x) == irange]
if not axs:
return [self]
else:
pax = axs.pop(argfunc([ax._range_gridspec(y)[idx] for ax in axs]))
return [pax, *axs]
def _get_title_props(self, abc=False, loc=None):
"""Returns standardized location name, position keyword arguments, and
setting keyword arguments for the relevant title or a-b-c label at location
`loc`."""
# Props
# NOTE: Sometimes we load all properties from rc object, sometimes
# just changed ones. This is important if e.g. user calls in two
# lines ax.format(titleweight='bold') then ax.format(title='text'),
# don't want to override custom setting with rc default setting.
props = lambda cache: rc.fill({
'fontsize': f'{prefix}.size',
'weight': f'{prefix}.weight',
'color': f'{prefix}.color',
'border': f'{prefix}.border',
'linewidth': f'{prefix}.linewidth',
'fontfamily': 'font.family',
}, cache=cache)
# Location string and position coordinates
cache = True
prefix = 'abc' if abc else 'title'
loc = _notNone(loc, rc[f'{prefix}.loc'])
iloc = getattr(self, '_' + ('abc' if abc else 'title') + '_loc') # old
if loc is None:
loc = iloc
elif iloc is not None and loc != iloc:
cache = False
# Above axes
loc = LOC_TRANSLATE.get(loc, loc)
if loc in ('top','bottom'):
raise ValueError(f'Invalid title location {loc!r}.')
elif loc in ('left','right','center'):
kw = props(cache)
kw.pop('border', None) # no border for titles outside axes
kw.pop('linewidth', None)
if loc == 'center':
obj = self.title
else:
obj = getattr(self, '_' + loc + '_title')
# Inside axes
elif loc in self._titles_dict:
kw = props(cache)
obj = self._titles_dict[loc]
else:
kw = props(False)
width, height = self.get_size_inches()
if loc in ('upper center','lower center'):
x, ha = 0.5, 'center'
elif loc in ('upper left','lower left'):
xpad = rc.get('axes.titlepad')/(72*width)
x, ha = 1.5*xpad, 'left'
elif loc in ('upper right','lower right'):
xpad = rc.get('axes.titlepad')/(72*width)
x, ha = 1 - 1.5*xpad, 'right'
else:
raise ValueError(f'Invalid title or abc "loc" {loc}.')
if loc in ('upper left','upper right','upper center'):
ypad = rc.get('axes.titlepad')/(72*height)
y, va = 1 - 1.5*ypad, 'top'
elif loc in ('lower left','lower right','lower center'):
ypad = rc.get('axes.titlepad')/(72*height)
y, va = 1.5*ypad, 'bottom'
obj = self.text(x, y, '', ha=ha, va=va, transform=self.transAxes)
obj.set_transform(self.transAxes)
return loc, obj, kw
@staticmethod
def _loc_translate(loc, **kwargs):
"""Translates location string `loc` into a standardized form."""
if loc is True:
loc = None
elif isinstance(loc, (str, Integral)):
loc = LOC_TRANSLATE.get(loc, loc)
return loc
def _make_inset_locator(self, bounds, trans):
"""Helper function, copied from private matplotlib version."""
def inset_locator(ax, renderer):
bbox = mtransforms.Bbox.from_bounds(*bounds)
bb = mtransforms.TransformedBbox(bbox, trans)
tr = self.figure.transFigure.inverted()
bb = mtransforms.TransformedBbox(bb, tr)
return bb
return inset_locator
def _range_gridspec(self, x):
"""Gets the column or row range for the axes."""
subplotspec = self.get_subplotspec()
if x == 'x':
_, _, _, _, col1, col2 = subplotspec.get_active_rows_columns()
return col1, col2
else:
_, _, row1, row2, _, _ = subplotspec.get_active_rows_columns()
return row1, row2
def _range_tightbbox(self, x):
"""Gets span of tight bounding box, including twin axes and panels
which are not considered real children and so aren't ordinarily included in
the tight bounding box calc. `~proplot.axes.Axes.get_tightbbox` caches
tight bounding boxes when `~Figure.get_tightbbox` is called."""
# TODO: Better resting for axes visibility
if x == 'x':
return self._tight_bbox.xmin, self._tight_bbox.xmax
else:
return self._tight_bbox.ymin, self._tight_bbox.ymax
def _reassign_suplabel(self, side):
"""Re-assigns the column and row labels to panel axes, if they exist.
This is called by `~proplot.subplots.Figure._align_suplabel`."""
# Place column and row labels on panels instead of axes -- works when
# this is called on the main axes *or* on the relevant panel itself
# TODO: Mixed figure panels with super labels? How does that work?
s = side[0]
side = SIDE_TRANSLATE[s]
if s == self._panel_side:
ax = self._panel_parent
else:
ax = self
paxs = getattr(ax, '_' + s + 'panels')
if not paxs:
return ax
idx = (0 if s in 'lt' else -1)
pax = paxs[idx]
kw = {}
obj = getattr(ax, '_' + s + 'label')
for key in ('color', 'fontproperties'): # TODO: add to this?
kw[key] = getattr(obj, 'get_' + key)()
pobj = getattr(pax, '_' + s + 'label')
pobj.update(kw)
text = obj.get_text()
if text:
obj.set_text('')
pobj.set_text(text)
return pax
def _reassign_title(self):
"""Re-assigns title to the first upper panel if present. We cannot
simply add upper panel as child axes, because then title will be offset
but still belong to main axes, which messes up tight bounding box."""
# Reassign title from main axes to top panel -- works when this is
# called on the main axes *or* on the top panel itself. This is
# critical for bounding box calcs; not always clear whether draw() and
# get_tightbbox() are called on the main axes or panel first
if self._panel_side == 'top' and self._panel_parent:
ax, taxs = self._panel_parent, [self]
else:
ax, taxs = self, self._tpanels
if not taxs or not ax._title_above_panel:
tax = ax
else:
tax = taxs[0]
tax._title_pad = ax._title_pad
for loc,obj in ax._titles_dict.items():
if not obj.get_text() or loc not in ('left','center','right'):
continue
kw = {}
loc, tobj, _ = tax._get_title_props(loc=loc)
for key in ('text', 'color', 'fontproperties'): # TODO: add to this?
kw[key] = getattr(obj, 'get_' + key)()
tobj.update(kw)
tax._titles_dict[loc] = tobj
obj.set_text('')
# Push title above tick marks -- this is known matplotlib problem,
# but especially annoying with top panels!
# TODO: Make sure this is robust. Seems 'default' is returned usually
# when tick label sides is actually *both*. Also makes sure axis is
# visible; if not, this is a filled colorbar or legend, no padding needed
pad = 0
pos = tax.xaxis.get_ticks_position()
labs = tax.xaxis.get_ticklabels()
if pos == 'default' or (pos == 'top' and not len(labs)) or (
pos == 'unknown' and tax._panel_side == 'top'
and not len(labs) and tax.xaxis.get_visible()):
pad = tax.xaxis.get_tick_padding()
tax._set_title_offset_trans(self._title_pad + pad)
def _sharex_setup(self, sharex, level):
"""Sets up panel axis sharing."""
if level not in range(4):
raise ValueError('Level can be 1 (do not share limits, just hide axis labels), 2 (share limits, but do not hide tick labels), or 3 (share limits and hide tick labels).')
self._sharex_level = max(self._sharex_level, level) # enforce, e.g. if doing panel sharing
self._share_short_axis(sharex, 'l', level)
self._share_short_axis(sharex, 'r', level)
self._share_long_axis(sharex, 'b', level)
self._share_long_axis(sharex, 't', level)
def _sharey_setup(self, sharey, level):
"""Sets up panel axis sharing."""
if level not in range(4):
raise ValueError('Level can be 1 (do not share limits, just hide axis labels), 2 (share limits, but do not hide tick labels), or 3 (share limits and hide tick labels).')
self._sharey_level = max(self._sharey_level, level)
self._share_short_axis(sharey, 'b', level)
self._share_short_axis(sharey, 't', level)
self._share_long_axis(sharey, 'l', level)
self._share_long_axis(sharey, 'r', level)
def _share_setup(self):
"""Applies axis sharing for axes that share the same horizontal or
vertical extent, and for their panels."""
# Panel axes sharing, between main subplot and its panels
# Top and bottom
shared = lambda paxs: [pax for pax in paxs if not pax._panel_filled and pax._panel_share]
if not self._panel_side: # this is a main axes
bottom = self
paxs = shared(self._bpanels)
if paxs:
bottom = paxs[-1]
for iax in (self, *paxs[:-1]):
iax._sharex_setup(bottom, 3) # parent is *bottom-most* panel
paxs = shared(self._tpanels)
for iax in paxs:
iax._sharex_setup(bottom, 3)
# Left and right
left = self
paxs = shared(self._lpanels)
if paxs:
left = paxs[0]
for iax in (*paxs[1:], self):
iax._sharey_setup(left, 3) # parent is *bottom-most* panel
paxs = shared(self._rpanels)
for iax in paxs:
iax._sharey_setup(left, 3)
# Main axes, sometimes overrides panel axes sharing
# TODO: This can get very repetitive, but probably minimal impact
# on performance?
# Share x axes
parent, *children = self._get_extent_axes('x')
for child in children:
child._sharex_setup(parent, parent._sharex_level)
# Share y axes
parent, *children = self._get_extent_axes('y')
for child in children:
child._sharey_setup(parent, parent._sharey_level)
def _share_short_axis(self, share, side, level):
"""Share the "short" axes of panels along a main subplot with panels
along an external subplot."""
if share is None or self._panel_side: # not None
return
s = side[0]
axis = 'x' if s in 'lr' else 'y'
caxs = getattr(self, '_' + s + 'panels') # calling this means, share properties on this axes with input 'share' axes
paxs = getattr(share, '_' + s + 'panels')
caxs = [pax for pax in caxs if not pax._panel_filled]
paxs = [pax for pax in paxs if not pax._panel_filled]
for cax,pax in zip(caxs,paxs): # may be uneven
getattr(cax, '_share' + axis + '_setup')(pax, level)
def _share_long_axis(self, share, side, level):
"""Share the "long" axes of panels along a main subplot with the
axis from an external subplot."""
# NOTE: We do not check _panel_share because that only controls
# sharing with main subplot, not other subplots
if share is None or self._panel_side:
return
s = side[0]
axis = 'x' if s in 'tb' else 'y'
paxs = getattr(self, '_' + s + 'panels') # calling this means, share properties on this axes with input 'share' axes
paxs = [pax for pax in paxs if not pax._panel_filled]
for pax in paxs:
getattr(pax, '_share' + axis + '_setup')(share, level)
def _update_title(self, obj, **kwargs):
"""Redraws title if updating with input keyword args failed."""
# Try to just return updated object, redraw may be necessary
# WARNING: Making text instances invisible seems to mess up tight
# bounding box calculations and cause other issues. Just reset text.
keys = ('border','lw','linewidth','bordercolor','invert')
kwextra = {key:value for key,value in kwargs.items() if key in keys}
kwargs = {key:value for key,value in kwargs.items() if key not in keys}
obj.update(kwargs)
if kwextra:
obj.set_text('')
else:
return obj
# Get properties from old object
for key in ('ha', 'va', 'color', 'transform', 'fontproperties'):
kwextra[key] = getattr(obj, 'get_' + key)() # copy over attrs
text = kwargs.pop('text', obj.get_text())
x, y = kwargs.pop('position', (None,None))
pos = obj.get_position()
x = _notNone(kwargs.pop('x', x), pos[0])
y = _notNone(kwargs.pop('y', y), pos[1])
return self.text(x, y, text, **kwextra)
def context(self, *, mode=2, rc_kw=None, **kwargs):
"""
For internal use. Sets up temporary `~proplot.rctools.rc` settings by
returning the result of `~proplot.rctools.rc_configurator.context`.
Parameters
----------
rc_kw : dict, optional
A dictionary containing "rc" configuration settings that will
be applied to this axes. Temporarily updates the
`~proplot.rctools.rc` object.
**kwargs
Any of three options:
* A keyword arg for `Axes.format`, `CartesianAxes.format`,
or `ProjectionAxes.format`.
* A global "rc" keyword arg, like ``linewidth`` or ``color``.
* A standard "rc" keyword arg **with the dots omitted**,
like ``landcolor`` instead of ``land.color``.
The latter two options update the `~proplot.rctools.rc`
object, just like `rc_kw`.
Other parameters
----------------
mode : int, optional
The "getitem mode". This is used under-the-hood -- you shouldn't
have to use it directly. Determines whether queries to the
`~proplot.rctools.rc` object will ignore `rcParams <https://matplotlib.org/users/customizing.html>`__.
This can help prevent a massive number of unnecessary lookups
when the settings haven't been changed by the user.
See `~proplot.rctools.rc_configurator` for details.
Returns
-------
`~proplot.rctools.rc_configurator`
The `proplot.rctools.rc` object primed for use in a "with"
statement.
dict
Dictionary of keyword arguments that are not `~proplot.rctools.rc`
properties, to be passed to the ``format`` methods.
"""
# Figure out which kwargs are valid rc settings
# TODO: Support for 'small', 'large', etc. font
kw = {} # for format
rc_kw = rc_kw or {}
for key,value in kwargs.items():
key_fixed = RC_NODOTSNAMES.get(key, None)
if key_fixed is None:
kw[key] = value
else:
rc_kw[key_fixed] = value
rc._getitem_mode = 0 # might still be non-zero if had error
# Return "context object", which is just the configurator itself
# primed for use in a "with" statement
return rc.context(rc_kw, mode=mode), kw
def format(self, *, title=None, top=None,
figtitle=None, suptitle=None, rowlabels=None, collabels=None,
leftlabels=None, rightlabels=None, toplabels=None, bottomlabels=None,
llabels=None, rlabels=None, tlabels=None, blabels=None,
**kwargs,
):
"""
Called by `CartesianAxes.format`, `ProjectionAxes.format`, and
`PolarAxes.format`. Formats the axes title(s), the a-b-c label, row
and column labels, and the figure title.
Parameters
----------
title : str, optional
The axes title.
abc : bool, optional
Whether to apply "a-b-c" subplot labelling based on the
``number`` attribute. If ``number`` is >26, the labels will loop
around to a, ..., z, aa, ..., zz, aaa, ..., zzz, ... Default is
:rc:`abc`.
abcstyle : str, optional
String denoting the format of a-b-c labels containing the character
``a`` or ``A``. ``'a'`` is the default, but e.g. ``'a.'``,
``'a)'``, or ``'A'`` might also be desirable. Default is
:rc:`abc.style`.
abcloc, titleloc : str, optional
Strings indicating the location for the a-b-c label and
main title. The following locations keys are valid. Defaults are
:rc:`abc.loc` and :rc:`title.loc`.
======================== ============================
Location Valid keys
======================== ============================
center above axes ``'center'``, ``'c'``
left above axes ``'left'``, ``'l'``
right above axes ``'right'``, ``'r'``
lower center inside axes ``'lower center``', ``'lc'``
upper center inside axes ``'upper center'``, ``'uc'``
upper right inside axes ``'upper right'``, ``'ur'``
upper left inside axes ``'upper left'``, ``'ul'``
lower left inside axes ``'lower left'``, ``'ll'``
lower right inside axes ``'lower right'``, ``'lr'``
======================== ============================
abcborder, titleborder : bool, optional
Whether to draw a white border around titles and a-b-c labels
positioned inside the axes. This can help them stand out on top
of artists plotted inside the axes. Defaults are
:rc:`abc.border` and :rc:`title.border`
ltitle, rtitle, ultitle, uctitle, urtitle, lltitle, lctitle, lrtitle : str, optional
Axes titles in particular positions. This lets you specify multiple
"titles" for each subplots. See the `abcloc` keyword.
top : bool, optional
Whether to try to put title and a-b-c label above the top subplot
panel (if it exists), or to always put them on the main subplot.
Default is ``True``.
rowlabels, colllabels : list of str, optional
Aliases for `leftlabels`, `toplabels`.
llabels, tlabels, rlabels, blabels : list of str, optional
Aliases for `leftlabels`, `toplabels`, `rightlabels`, `bottomlabels`.
leftlabels, toplabels, rightlabels, bottomlabels : list of str, optional
The subplot row and column labels. If list, length must match
the number of subplots on the left, top, right, or bottom edges
of the figure.
figtitle, suptitle : str, optional
The figure "super" title, centered between the left edge of
the lefmost column of subplots and the right edge of the rightmost
column of subplots, and automatically offset above figure titles.
This is an improvement on matplotlib's "super" title, which just
centers the text between figure edges.
Note
----
The `abc`, `abcstyle`, `abcloc`, and `titleloc` keyword arguments
are actually rc configuration settings that are temporarily
changed by the call to `~Axes.context`. They are documented here
because it is extremely common to change them with `~Axes.format`.
They also appear in the tables in the `~proplot.rctools` documention.
"""
# Figure patch (for some reason needs to be re-asserted even if
# declared before figure is drawn)
kw = rc.fill({'facecolor':'figure.facecolor'})
self.figure.patch.update(kw)
if top is not None:
self._title_above_panel = top
pad = rc['axes.titlepad']
if pad is not None:
self._set_title_offset_trans(pad)
self._title_pad = pad
# Super title
# NOTE: These are actually *figure-wide* settings, but that line seems
# to get blurred -- where we have shared axes, spanning labels, and
# whatnot. May result in redundant assignments if formatting more than
# one axes, but operations are fast so some redundancy is nbd.
fig = self.figure
suptitle = _notNone(figtitle, suptitle, None, names=('figtitle','suptitle'))
kw = rc.fill({
'fontsize': 'suptitle.size',
'weight': 'suptitle.weight',
'color': 'suptitle.color',
'fontfamily': 'font.family'
})
if suptitle or kw:
fig._update_suptitle(suptitle, **kw)
# Labels
llabels = _notNone(rowlabels, leftlabels, llabels, None, names=('rowlabels','leftlabels','llabels'))
tlabels = _notNone(collabels, toplabels, tlabels, None, names=('collabels','toplabels','tlabels'))
rlabels = _notNone(rightlabels, rlabels, None, names=('rightlabels','rlabels'))
blabels = _notNone(bottomlabels, blabels, None, names=('bottomlabels','blabels'))
for side,labels in zip(
('left', 'right', 'top', 'bottom'),
(llabels, rlabels, tlabels, blabels),
):
kw = rc.fill({
'fontsize': side + 'label.size',
'weight': side + 'label.weight',
'color': side + 'label.color',
'fontfamily': 'font.family'
})
if labels or kw:
fig._update_suplabels(self, side, labels, **kw)
# A-b-c labels
titles_dict = self._titles_dict
if not self._panel_side:
# Location and text
abcstyle = rc['abc.style'] # changed or running format first time?
if 'abcformat' in kwargs: # super sophisticated deprecation system
abcstyle = kwargs.pop('abcformat')
warnings.warn(f'rc setting "abcformat" is deprecated. Please use "abcstyle".')
if abcstyle and self.number is not None:
if not isinstance(abcstyle, str) or (abcstyle.count('a') != 1
and abcstyle.count('A') != 1):
raise ValueError(f'Invalid abcstyle {abcstyle!r}. Must include letter "a" or "A".')
abcedges = abcstyle.split('a' if 'a' in abcstyle else 'A')
text = abcedges[0] + _abc(self.number-1) + abcedges[-1]
if 'A' in abcstyle:
text = text.upper()
self._abc_text = text
# Apply new settings
# Also if a-b-c label was moved, remove previous one and update
# text on new one, in case self._abc_text has not changed.
loc, obj, kw = self._get_title_props(abc=True)
iloc = self._abc_loc
obj = self._update_title(obj, **kw)
titles_dict[loc] = obj
if iloc is not None and loc!=iloc:
self.abc.set_text('')
obj.set_text(self._abc_text)
self.abc = obj
self._abc_loc = loc
# Toggle visibility
# NOTE: If abc is a matplotlib 'title' attribute, making it
# invisible messes stuff up. Just set text to empty.
abc = rc['abc']
if abc is not None:
obj.set_text(self._abc_text if bool(abc) else '')
# Titles
# Tricky because we have to reconcile two workflows:
# 1. title='name' and titleloc='position'
# 2. ltitle='name', rtitle='name', etc., arbitrarily many titles
# First update existing titles
# NOTE: _update_title should never return new objects unless called
# with *inner* titles... *outer* titles will just refresh, so we
# don't need to re-assign the attributes or anything.
loc, obj, kw = self._get_title_props()
if kw:
for iloc,iobj in titles_dict.items():
if iloc is self._abc_loc:
continue
titles_dict[iloc] = self._update_title(iobj, **kw)
# Workflow 2, want this to come first so workflow 1 gets priority
for ikey,ititle in kwargs.items():
if not ikey[-5:] == 'title':
raise TypeError(f'format() got an unexpected keyword argument {ikey!r}.')
iloc, iobj, ikw = self._get_title_props(loc=ikey[:-5])
if ititle is not None:
ikw['text'] = ititle
if ikw:
titles_dict[iloc] = self._update_title(iobj, **ikw)
# Workflow 1, make sure that if user calls ax.format(title='Title')
# *then* ax.format(titleloc='left') it copies over the text.
iloc = self._title_loc
if iloc is not None and loc != iloc:
iobj = titles_dict[iloc]
if title is None:
title = iobj.get_text()
iobj.set_text('')
self._title_loc = loc # assigns default loc on first run, or changed loc
if title is not None:
kw['text'] = title
if kw:
titles_dict[loc] = self._update_title(obj, **kw)
def area(self, *args, **kwargs):
"""Alias for `~matplotlib.axes.Axes.fill_between`."""
# NOTE: *Cannot* assign area = axes.Axes.fill_between because the
# wrapper won't be applied and for some reason it messes up
# automodsumm, which tries to put the matplotlib docstring on website
return self.fill_between(*args, **kwargs)
def areax(self, *args, **kwargs):
"""Alias for `~matplotlib.axes.Axes.fill_betweenx`."""
return self.fill_betweenx(*args, **kwargs)
def boxes(self, *args, **kwargs):
"""Alias for `~matplotlib.axes.Axes.boxplot`."""
return self.boxplot(*args, **kwargs)
@_standardize_1d
@_cmap_changer
def cmapline(self, *args, values=None,
cmap=None, norm=None,
interp=0, **kwargs):
"""
Invoked when you pass the `cmap` keyword argument to
`~matplotlib.axes.Axes.plot`. Draws a "colormap line",
i.e. a line whose color changes as a function of the parametric
coordinate ``values``. using the input colormap ``cmap``.
This is actually a collection of lines, added as a
`~matplotlib.collections.LineCollection` instance. See `this matplotlib example
<https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html>`__.
Parameters
----------
*args : (y,) or (x,y)
The coordinates. If `x` is not provided, it is inferred from `y`.
cmap : colormap spec, optional
The colormap specifier, passed to `~proplot.styletools.Colormap`.
values : list of float
The parametric values used to map points on the line to colors
in the colormap.
norm : normalizer spec, optional
The normalizer, passed to `~proplot.styletools.Norm`.
interp : int, optional
Number of values between each line joint and each *halfway* point
between line joints to which you want to interpolate.
"""
# First error check
# WARNING: So far this only works for 1D *x* and *y* coordinates. Cannot
# draw multiple colormap lines at once, unlike `~matplotlib.axes.Axes.plot`.
if values is None:
raise ValueError('Requires a "values" keyword arg.')
if len(args) not in (1,2):
raise ValueError(f'Requires 1-2 arguments, got {len(args)}.')
y = np.array(args[-1]).squeeze()
x = np.arange(y.shape[-1]) if len(args) == 1 else np.array(args[0]).squeeze()
values = np.array(values).squeeze()
if x.ndim != 1 or y.ndim != 1 or values.ndim != 1:
raise ValueError(f'x ({x.ndim}-d), y ({y.ndim}-d), and values ({values.ndim}-d) must be 1-dimensional.')
if len(x) != len(y) or len(x) != len(values) or len(y) != len(values):
raise ValueError(f'{len(x)} xs, {len(y)} ys, but {len(values)} colormap values.')
# Interpolate values to allow for smooth gradations between values
# (bins=False) or color switchover halfway between points (bins=True)
# Then optionally interpolate the corresponding colormap values
if interp > 0:
xorig, yorig, vorig = x, y, values
x, y, values = [], [], []
for j in range(xorig.shape[0]-1):
idx = (slice(None, -1) if j+1 < xorig.shape[0]-1 else slice(None))
x.extend(np.linspace(xorig[j], xorig[j+1], interp + 2)[idx].flat)
y.extend(np.linspace(yorig[j], yorig[j+1], interp + 2)[idx].flat)
values.extend(np.linspace(vorig[j], vorig[j+1], interp + 2)[idx].flat)
x, y, values = np.array(x), np.array(y), np.array(values)
coords = []
levels = utils.edges(values)
for j in range(y.shape[0]):
# Get x/y coordinates and values for points to the 'left' and
# 'right' of each joint
if j == 0:
xleft, yleft = [], []
else:
xleft = [(x[j-1] + x[j])/2, x[j]]
yleft = [(y[j-1] + y[j])/2, y[j]]
if j+1 == y.shape[0]:
xright, yright = [], []
else:
xleft = xleft[:-1] # prevent repetition when joined with right
yleft = yleft[:-1]
xright = [x[j], (x[j+1] + x[j])/2]
yright = [y[j], (y[j+1] + y[j])/2]
pleft = np.stack((xleft, yleft), axis=1)
pright = np.stack((xright, yright), axis=1)
coords.append(np.concatenate((pleft, pright), axis=0))
# Create LineCollection and update with values
hs = mcollections.LineCollection(np.array(coords), cmap=cmap, norm=norm,
linestyles='-', capstyle='butt', joinstyle='miter')
hs.set_array(np.array(values))
hs.update({key:value for key,value in kwargs.items() if key not in ('color',)})
# Add collection, with some custom attributes
self.add_collection(hs)
if self.get_autoscale_on() and self.ignore_existing_data_limits:
self.autoscale_view() # data limits not updated otherwise
hs.values = values
hs.levels = levels # needed for other functions some
return hs
def colorbar(self, *args, loc=None, pad=None,
length=None, width=None, space=None, frame=None, frameon=None,
alpha=None, linewidth=None, edgecolor=None, facecolor=None,
**kwargs):
"""
Adds colorbar as an *inset* or along the outside edge of the axes.
See `~proplot.wrappers.colorbar_wrapper` for details.
Parameters
----------
loc : str, optional
The colorbar location. Default is :rc:`colorbar.loc`. The
following location keys are valid.
================== ==================================
Location Valid keys
================== ==================================
outer left ``'left'``, ``'l'``
outer right ``'right'``, ``'r'``
outer bottom ``'bottom'``, ``'b'``
outer top ``'top'``, ``'t'``
default inset ``'inset'``, ``'i'``, ``0``
upper right inset ``'upper right'``, ``'ur'``, ``1``
upper left inset ``'upper left'``, ``'ul'``, ``2``
lower left inset ``'lower left'``, ``'ll'``, ``3``
lower right inset ``'lower right'``, ``'lr'``, ``4``
================== ==================================
pad : float or str, optional
The space between the axes edge and the colorbar. For inset
colorbars only. Units are interpreted by `~proplot.utils.units`.
Default is :rc:`colorbar.axespad`.
length : float or str, optional
The colorbar length. For outer colorbars, units are relative to the
axes width or height. Default is :rc:`colorbar.length`. For inset
colorbars, units are interpreted by `~proplot.utils.units`. Default
is :rc:`colorbar.insetlength`.
width : float or str, optional
The colorbar width. Units are interpreted by `~proplot.utils.units`.
Default is :rc:`colorbar.width` or :rc:`colorbar.insetwidth`.
space : float or str, optional
The space between the colorbar and the main axes. For outer
colorbars only. Units are interpreted by `~proplot.utils.units`.
When :rcraw:`tight` is ``True``, this is adjusted automatically.
Otherwise, defaut is :rc:`subplots.panelspace`.
frame, frameon : bool, optional
Whether to draw a frame around inset colorbars, just like
`~matplotlib.axes.Axes.legend`.
Default is :rc:`colorbar.frameon`.
alpha, linewidth, edgecolor, facecolor : optional
Transparency, edge width, edge color, and face color for the frame
around the inset colorbar. Default is
:rc:`colorbar.framealpha`, :rc:`axes.linewidth`,
:rc:`axes.edgecolor`, and :rc:`axes.facecolor`,
respectively.
**kwargs
Passed to `~proplot.wrappers.colorbar_wrapper`.
"""
# TODO: add option to pad inset away from axes edge!
kwargs.update({'edgecolor':edgecolor, 'linewidth':linewidth})
loc = _notNone(loc, rc['colorbar.loc'])
loc = self._loc_translate(loc)
if loc == 'best': # a white lie
loc = 'lower right'
if not isinstance(loc, str): # e.g. 2-tuple or ndarray
raise ValueError(f'Invalid colorbar location {loc!r}.')
# Generate panel
if loc in ('left','right','top','bottom'):
ax = self.panel_axes(loc, width=width, space=space, filled=True)
return ax.colorbar(loc='_fill', *args, length=length, **kwargs)
# Filled colorbar
if loc == '_fill':
# Hide content and resize panel
# NOTE: Do not run self.clear in case we want title above this
for s in self.spines.values():
s.set_visible(False)
self.xaxis.set_visible(False)
self.yaxis.set_visible(False)
self.patch.set_alpha(0)
self._panel_filled = True
# Draw colorbar with arbitrary length relative to full length of panel
side = self._panel_side
length = _notNone(length, rc['colorbar.length'])
subplotspec = self.get_subplotspec()
if length <= 0 or length > 1:
raise ValueError(f'Panel colorbar length must satisfy 0 < length <= 1, got length={length!r}.')
if side in ('bottom','top'):
gridspec = mgridspec.GridSpecFromSubplotSpec(
nrows=1, ncols=3, wspace=0,
subplot_spec=subplotspec,
width_ratios=((1-length)/2, length, (1-length)/2),
)
subplotspec = gridspec[1]
else:
gridspec = mgridspec.GridSpecFromSubplotSpec(
nrows=3, ncols=1, hspace=0,
subplot_spec=subplotspec,
height_ratios=((1-length)/2, length, (1-length)/2),
)
subplotspec = gridspec[1]
with self.figure._unlock():
ax = self.figure.add_subplot(subplotspec, projection=None)