/
figure.py
1940 lines (1785 loc) · 80.9 KB
/
figure.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
"""
The figure class used for all proplot figures.
"""
import functools
import inspect
import os
from numbers import Integral
import matplotlib.axes as maxes
import matplotlib.figure as mfigure
import matplotlib.gridspec as mgridspec
import matplotlib.projections as mproj
import matplotlib.text as mtext
import matplotlib.transforms as mtransforms
import numpy as np
from . import axes as paxes
from . import constructor
from . import gridspec as pgridspec
from .config import rc, rc_matplotlib
from .internals import ic # noqa: F401
from .internals import (
_not_none,
_pop_params,
_pop_rc,
_translate_loc,
context,
docstring,
texts,
warnings,
)
from .utils import units
__all__ = [
'Figure',
]
# Preset figure widths or sizes based on academic journal recommendations
# NOTE: Please feel free to add to this!
JOURNAL_SIZES = {
'aaas1': '5.5cm',
'aaas2': '12cm',
'agu1': ('95mm', '115mm'),
'agu2': ('190mm', '115mm'),
'agu3': ('95mm', '230mm'),
'agu4': ('190mm', '230mm'),
'ams1': 3.2,
'ams2': 4.5,
'ams3': 5.5,
'ams4': 6.5,
'nat1': '89mm',
'nat2': '183mm',
'pnas1': '8.7cm',
'pnas2': '11.4cm',
'pnas3': '17.8cm',
}
# Figure docstring
_figure_docstring = """
refnum : int, optional
The reference subplot number. The `refwidth`, `refheight`, and `refaspect`
keyword args are applied to this subplot, and the aspect ratio is conserved
for this subplot in the `~Figure.auto_layout`. The default is the first
subplot created in the figure.
refaspect : float or 2-tuple of float, optional
The reference subplot aspect ratio. If scalar, this indicates the width
divided by height. If 2-tuple, this indicates the (width, height). Ignored
if both `figwidth` *and* `figheight` or both `refwidth` *and* `refheight` were
passed. The default value is ``1`` or the "data aspect ratio" if the latter
is explicitly fixed (as with `~proplot.axes.PlotAxes.imshow` plots and
`~proplot.axes.Axes.GeoAxes` projections; see `~matplotlib.axes.Axes.set_aspect`).
refwidth, refheight : unit-spec, default: :rc:`subplots.refwidth`
The width, height of the reference subplot.
%(units.in)s
Ignored if `figwidth`, `figheight`, or `figsize` was passed. If you
specify just one, `refaspect` will be respected.
ref, aspect, axwidth, axheight
Aliases for `refnum`, `refaspect`, `refwidth`, `refheight`.
*These may be deprecated in a future release.*
figwidth, figheight : unit-spec, optional
The figure width and height. Default behavior is to use `refwidth`.
%(units.in)s
If you specify just one, `refaspect` will be respected.
width, height
Aliases for `figwidth`, `figheight`.
figsize : 2-tuple, optional
Tuple specifying the figure ``(width, height)``.
sharex, sharey, share \
: {0, False, 1, 'labels', 'labs', 2, 'limits', 'lims', 3, True, 4, 'all'}, \
default: :rc:`subplots.share`
The axis sharing "level" for the *x* axis, *y* axis, or both
axes. Options are as follows:
* ``0`` or ``False``: No axis sharing. This also sets the default `spanx`
and `spany` values to ``False``.
* ``1`` or ``'labels'`` or ``'labs'``: Only draw axis labels on the bottommost
row or leftmost column of subplots. Tick labels still appear on every subplot.
* ``2`` or ``'limits'`` or ``'lims'``: As above but force the axis limits, scales,
and tick locations to be identical. Tick labels still appear on every subplot.
* ``3`` or ``True``: As above but only show the tick labels on the bottommost
row and leftmost column of subplots.
* ``4`` or ``'all'``: As above but also share the axis limits, scales, and
tick locations between subplots not in the same row or column.
spanx, spany, span : bool or {0, 1}, default: :rc:`subplots.span`
Whether to use "spanning" axis labels for the *x* axis, *y* axis, or both
axes. Default is ``False`` if `sharex`, `sharey`, or `share` are ``0`` or
``False``. When ``True``, a single, centered axis label is used for all axes
with bottom and left edges in the same row or column. This can considerably
redundancy in your figure. "Spanning" labels integrate with "shared" axes. For
example, for a 3-row, 3-column figure, with ``sharey > 1`` and ``spany == True``,
your figure will have 1 y axis label instead of 9 y axis labels.
alignx, aligny, align : bool or {0, 1}, default: :rc:`subplots.align`
Whether to `"align" axis labels \
<https://matplotlib.org/stable/gallery/subplots_axes_and_figures/align_labels_demo.html>`__
for the *x* axis, *y* axis, or both axes. Aligned labels always appear in the same
row or column. This is ignored if `spanx`, `spany`, or `span` are ``True``.
%(gridspec.shared)s
%(gridspec.scalar)s
tight : bool, default: :rc`subplots.tight`
Whether automatic calls to `~Figure.auto_layout` should include
:ref:`tight layout adjustments <ug_tight>`. If you manually specified a spacing
in the call to `~proplot.ui.subplots`, it will be used to override the tight
layout spacing. For example, with ``left=1``, the left margin is set to 1
em-width, while the remaining margin widths are calculated automatically.
%(gridspec.tight)s
journal : str, optional
String corresponding to an academic journal standard used to control the figure
width `figwidth` and, if specified, the figure height `figheight`. See the below
table. Feel free to add to this table by submitting a pull request.
.. _journal_table:
=========== ==================== \
===============================================================================
Key Size description Organization
=========== ==================== \
===============================================================================
``'aaas1'`` 1-column \
`American Association for the Advancement of Science <aaas_>`_ (e.g. *Science*)
``'aaas2'`` 2-column ”
``'agu1'`` 1-column `American Geophysical Union <agu_>`_
``'agu2'`` 2-column ”
``'agu3'`` full height 1-column ”
``'agu4'`` full height 2-column ”
``'ams1'`` 1-column `American Meteorological Society <ams_>`_
``'ams2'`` small 2-column ”
``'ams3'`` medium 2-column ”
``'ams4'`` full 2-column ”
``'nat1'`` 1-column `Nature Research <nat_>`_
``'nat2'`` 2-column ”
``'pnas1'`` 1-column \
`Proceedings of the National Academy of Sciences <pnas_>`_
``'pnas2'`` 2-column ”
``'pnas3'`` landscape page ”
=========== ==================== \
===============================================================================
.. _aaas: \
https://www.sciencemag.org/authors/instructions-preparing-initial-manuscript
.. _agu: \
https://www.agu.org/Publish-with-AGU/Publish/Author-Resources/Graphic-Requirements
.. _ams: \
https://www.ametsoc.org/ams/index.cfm/publications/authors/journal-and-bams-authors/figure-information-for-authors/
.. _nat: \
https://www.nature.com/nature/for-authors/formatting-guide
.. _pnas: \
https://www.pnas.org/page/authors/format
"""
docstring._snippet_manager['figure.figure'] = _figure_docstring
# Multiple subplots
_subplots_params_docstring = """
array : `proplot.gridspec.GridSpec` or array-like of int, optional
The subplot grid specifier. If a `~proplot.gridspec.GridSpec`, one subplot is
drawn for each unique `~proplot.gridspec.GridSpec` slot. If a 2D array of integers,
one subplot is drawn for each unique integer in the array. Think of this array as
a "picture" of the subplot grid -- for example, the array ``[[1, 1], [2, 3]]``
creates one long subplot in the top row, two smaller subplots in the bottom row.
Integers must range from 1 to the number of plots, and ``0`` indicates an
empty space -- for example, ``[[1, 1, 1], [2, 0, 3]]`` creates one long subplot
in the top row with two subplots in the bottom row separated by a space.
nrows, ncols : int, default: 1
The number of rows and columns in the subplot grid. Ignored
if `array` was passed. Use these arguments for simple subplot grids.
order : {'C', 'F'}, default: 'C'
Whether subplots are numbered in column-major (``'C'``) or row-major (``'F'``)
order. Analogous to `numpy.array` ordering. This controls the order that
subplots appear in the `SubplotGrid` returned by this function, and the order
of subplot a-b-c labels (see `~proplot.axes.Axes.format`).
%(axes.proj)s
To use different projections for different subplots, you have
two options:
* Pass a *list* of projection specifications, one for each subplot.
For example, ``pplt.subplots(ncols=2, proj=('cart', 'robin'))``.
* Pass a *dictionary* of projection specifications, where the
keys are integers or tuples of integers that indicate the projection
to use for the corresponding subplot number(s). If a key is not
provided, the default projection ``'cartesian'`` is used. For example,
``pplt.subplots(ncols=4, proj={2: 'cyl', (3, 4): 'stere'})`` creates
a figure with a default Cartesian axes for the first subplot, a Mercator
projection for the second subplot, and a Stereographic projection
for the third and fourth subplots.
%(axes.proj_kw)s
If dictionary of properties, applies globally. If list or dictionary of
dictionaries, applies to specific subplots, as with `proj`. For example,
``pplt.subplots(ncols=2, proj='cyl', proj_kw=({'lon_0': 0}, {'lon_0': 180})``
centers the projection in the left subplot on the prime meridian and in the
right subplot on the international dateline.
%(axes.basemap)s
If boolean, applies to all subplots. If list or dict, applies to specific
subplots, as with `proj`.
%(gridspec.shared)s
%(gridspec.vector)s
%(gridspec.tight)s
"""
docstring._snippet_manager['figure.subplots_params'] = _subplots_params_docstring
# Extra args docstring
_axes_params_docstring = """
**kwargs
Passed to the proplot class `proplot.axes.CartesianAxes`, `proplot.axes.PolarAxes`,
`proplot.axes.GeoAxes`, or `proplot.axes.ThreeAxes`. This can include keyword
arguments for projection-specific ``format`` commands.
"""
docstring._snippet_manager['figure.axes_params'] = _axes_params_docstring
# Multiple subplots docstring
_subplots_docstring = """
Add an arbitrary grid of subplots to the figure.
Parameters
----------
%(figure.subplots_params)s
Other parameters
----------------
%(figure.figure)s
%(figure.axes_params)s
Returns
-------
axs : SubplotGrid
The axes instances stored in a `SubplotGrid`.
See also
--------
proplot.ui.figure
proplot.ui.subplots
proplot.figure.Figure.subplot
proplot.figure.Figure.add_subplot
proplot.gridspec.SubplotGrid
proplot.axes.Axes
"""
docstring._snippet_manager['figure.subplots'] = _subplots_docstring
# Single subplot docstring
_subplot_docstring = """
Add a subplot axes to the figure.
Parameters
----------
*args : int, tuple, or `~matplotlib.gridspec.SubplotSpec`, optional
The subplot location specifier. Your options are:
* A single 3-digit integer argument specifying the number of rows,
number of columns, and gridspec number (using row-major indexing).
* Three positional arguments specifying the number of rows, number of
columns, and gridspec number (int) or number range (2-tuple of int).
* A `~matplotlib.gridspec.SubplotSpec` instance generated by indexing
a proplot `~proplot.gridspec.GridSpec`.
For integer input, the implied geometry must be compatible with the implied
geometry from previous calls -- for example, ``fig.add_subplot(331)`` followed
by ``fig.add_subplot(132)`` is valid because the 1 row of the second input can
be tiled into the 3 rows of the the first input, but ``fig.add_subplot(232)``
will raise an error because 2 rows cannot be tiled into 3 rows. For
`~matplotlib.gridspec.SubplotSpec` input, the `~matplotlig.gridspec.SubplotSpec`
must be derived from the `~proplot.gridspec.GridSpec` used in previous calls.
These restrictions arise because we allocate a single,
unique `~Figure.gridspec` for each figure.
number : int, optional
The axes number used for a-b-c labeling. See `~proplot.axes.Axes.format` for
details. By default this is incremented automatically based on the other subplots
in the figure. Use e.g. ``number=None`` or ``number=False`` to ensure the subplot
has no a-b-c label. Note the number corresponding to ``a`` is ``1``, not ``0``.
autoshare : bool, default: True
Whether to automatically share the *x* and *y* axes with subplots spanning the
same rows and columns based on the figure-wide `sharex` and `sharey` settings.
This has no effect if :rcraw:`subplots.share` is ``False`` or if ``sharex=False``
or ``sharey=False`` were passed to the figure.
%(axes.proj)s
%(axes.proj_kw)s
%(axes.basemap)s
Other parameters
----------------
%(figure.axes_params)s
See also
--------
proplot.figure.Figure.add_axes
proplot.figure.Figure.subplots
proplot.figure.Figure.add_subplots
"""
docstring._snippet_manager['figure.subplot'] = _subplot_docstring
# Single axes
_axes_docstring = """
Add a non-subplot axes to the figure.
Parameters
----------
rect : 4-tuple of float
The (left, bottom, width, height) dimensions of the axes in
figure-relative coordinates.
%(axes.proj)s
%(axes.proj_kw)s
%(axes.basemap)s
Other parameters
----------------
%(figure.axes_params)s
See also
--------
proplot.figure.Figure.subplot
proplot.figure.Figure.add_subplot
proplot.figure.Figure.subplots
proplot.figure.Figure.add_subplots
"""
docstring._snippet_manager['figure.axes'] = _axes_docstring
# Colorbar or legend panel docstring
_space_docstring = """
loc : str, optional
The {name} location. Valid location keys are as follows.
%(axes.panel_loc)s
space : float or str, default: None
The fixed space between the {name} and the subplot grid edge.
%(units.em)s
When the :ref:`tight layout algorithm <ug_tight>` is active for the figure,
`space` is computed automatically (see `pad`). Otherwise, `space` is set to
a suitable default.
pad : float or str, default: :rc:`subplots.innerpad` or :rc:`subplots.panelpad`
The :ref:`tight layout padding <ug_tight>` between the {name} and the
subplot grid. Default is :rcraw:`subplots.innerpad` for the first {name}
and :rcraw:`subplots.panelpad` for subsequently "stacked" {name}s.
%(units.em)s
row, rows
Aliases for `span` for {name}s on the left or right side.
col, cols
Aliases for `span` for {name}s on the top or bottom side.
span : int or 2-tuple of int, default: None
Integer(s) indicating the span of the {name} across rows and columns of
subplots. For example, ``fig.{name}(loc='b', col=1)`` draws a {name} beneath
the leftmost column of subplots, and ``fig.{name}(loc='b', cols=(1, 2))``
draws a {name} beneath the left two columns of subplots. By default
the {name} will span every subplot row and column.
align : {{'center', 'top', 't', 'bottom', 'b', 'left', 'l', 'right', 'r'}}, optional
For outer {name}s only. How to align the {name} against the
subplot edge. The values ``'top'`` and ``'bottom'`` are valid for left and
right {name}s and ``'left'`` and ``'right'`` are valid for top and bottom
{name}s. The default is always ``'center'``.
"""
docstring._snippet_manager['figure.legend_space'] = _space_docstring.format(name='legend') # noqa: E501
docstring._snippet_manager['figure.colorbar_space'] = _space_docstring.format(name='colorbar') # noqa: E501
# Save docstring
_save_docstring = """
Save the figure.
Parameters
----------
path : path-like, optional
The file path. User paths are expanded with `os.path.expanduser`.
**kwargs
Passed to `~matplotlib.figure.Figure.savefig`
See also
--------
Figure.save
Figure.savefig
matplotlib.figure.Figure.savefig
"""
docstring._snippet_manager['figure.save'] = _save_docstring
def _get_journal_size(preset):
"""
Return the width and height corresponding to the given preset.
"""
value = JOURNAL_SIZES.get(preset, None)
if value is None:
raise ValueError(
f'Unknown preset figure size specifier {preset!r}. '
'Current options are: '
+ ', '.join(map(repr, JOURNAL_SIZES.keys()))
)
figwidth = figheight = None
try:
figwidth, figheight = value
except (TypeError, ValueError):
figwidth = value
return figwidth, figheight
def _add_canvas_preprocessor(canvas, method):
"""
Return a pre-processer that can be used to override instance-level
canvas draw() and print_figure() methods. This applies tight layout
and aspect ratio-conserving adjustments and aligns labels. Required
so canvas methods instantiate renderers with the correct dimensions.
"""
# NOTE: Renderer must be (1) initialized with the correct figure size or
# (2) changed inplace during draw, but vector graphic renderers *cannot*
# be changed inplace. So options include (1) monkey patch
# canvas.get_width_height, overriding figure.get_size_inches, and exploit
# the FigureCanvasAgg.get_renderer() implementation (because FigureCanvasAgg
# queries the bbox directly rather than using get_width_height() so requires
# workaround), (2) override bbox and bbox_inches as *properties* (but these
# are really complicated, dangerous, and result in unnecessary extra draws),
# or (3) simply override canvas draw methods. Our choice is #3.
def _canvas_preprocess(self, *args, **kwargs):
fig = self.figure # update even if not stale! needed after saves
func = getattr(type(self), method) # the original method
# Bail out if we are already adjusting layout
# NOTE: The _is_adjusting check necessary when inserting new
# gridspec rows or columns with the qt backend.
# NOTE: Return value for macosx _draw is the renderer, for qt draw is
# nothing, and for print_figure is some figure object, but this block
# has never been invoked when calling print_figure.
if fig._is_adjusting:
if method == '_draw': # macosx backend
return fig._get_renderer()
else:
return
# Adjust layout
# NOTE: The authorized_context is needed because some backends disable
# constrained layout or tight layout before printing the figure.
# NOTE: *Critical* to not add print_figure renderer to the cache when the print
# method (print_pdf, print_png, etc.) calls Figure.draw(). Otherwise have issues
# where (1) figure size and/or figure bounds are incorrect after saving figure
# *then* displaying it in qt or inline notebook backends, and (2) figure fails
# to update correctly after successively modifying and displaying within inline
# notebook backend (previously worked around this by forcing additional draw()
# call in this function before proceeding with print_figure).
ctx1 = fig._context_adjusting(cache=(method != 'print_figure'))
ctx2 = fig._context_authorized() # backends might call set_constrained_layout()
ctx3 = rc.context(fig._render_context) # draw with figure-specific setting
with ctx1, ctx2, ctx3:
fig.auto_layout()
return func(self, *args, **kwargs)
# Add preprocessor
setattr(canvas, method, _canvas_preprocess.__get__(canvas))
return canvas
class Figure(mfigure.Figure):
"""
The `~matplotlib.figure.Figure` subclass used by proplot.
"""
# Shared error and warning messages
_share_message = (
'Axis sharing level can be 0 or False (share nothing), '
"1 or 'labels' or 'labs' (share axis labels), "
"2 or 'limits' or 'lims' (share axis limits and axis labels), "
'3 or True (share axis limits, axis labels, and tick labels), '
"or 4 or 'all' (share axis labels and tick labels in the same gridspec "
'rows and columns and share axis limits across all subplots).'
)
_space_message = (
'To set the left, right, bottom, top, wspace, or hspace gridspec values, '
'pass them as keyword arguments to pplt.figure() or pplt.subplots(). Please '
'note they are now specified in physical units, with strings interpreted by '
'pplt.units() and floats interpreted as font size-widths.'
)
_tight_message = (
'Proplot uses its own tight layout algorithm that is activated by default. '
"To disable it, set pplt.rc['subplots.tight'] to False or pass tight=False "
'to pplt.subplots(). For details, see fig.auto_layout().'
)
_warn_interactive = True # disabled after first warning
def __repr__(self):
opts = {}
for attr in ('refaspect', 'refwidth', 'refheight', 'figwidth', 'figheight'):
value = getattr(self, '_' + attr)
if value is not None:
opts[attr] = np.round(value, 2)
geom = ''
if self.gridspec:
nrows, ncols = self.gridspec.get_geometry()
geom = f'nrows={nrows}, ncols={ncols}, '
opts = ', '.join(f'{key}={value!r}' for key, value in opts.items())
return f'Figure({geom}{opts})'
# NOTE: If _rename_kwargs argument is an invalid identifier, it is
# simply used in the warning message.
@docstring._obfuscate_kwargs
@docstring._snippet_manager
@warnings._rename_kwargs('0.7', axpad='innerpad', autoformat='pplt.rc.autoformat = {}') # noqa: E501
def __init__(
self, *, refnum=None, ref=None, refaspect=None, aspect=None,
refwidth=None, refheight=None, axwidth=None, axheight=None,
figwidth=None, figheight=None, width=None, height=None, journal=None,
sharex=None, sharey=None, share=None, # used for default spaces
spanx=None, spany=None, span=None,
alignx=None, aligny=None, align=None,
left=None, right=None, top=None, bottom=None,
wspace=None, hspace=None, space=None,
tight=None, outerpad=None, innerpad=None, panelpad=None,
wpad=None, hpad=None, pad=None,
**kwargs
):
"""
Parameters
----------
%(figure.figure)s
Other parameters
----------------
%(figure.format)s
**kwargs
Passed to `matplotlib.figure.Figure`.
See also
--------
Figure.format
proplot.ui.figure
proplot.ui.subplots
matplotlib.figure.Figure
"""
# Add figure sizing settings
# NOTE: We cannot catpure user-input 'figsize' here because it gets
# automatically filled by the figure manager. See ui.figure().
# NOTE: The figure size is adjusted according to these arguments by the
# canvas preprocessor. Although in special case where both 'figwidth' and
# 'figheight' were passes we update 'figsize' to limit side effects.
refnum = _not_none(refnum=refnum, ref=ref, default=1) # never None
refaspect = _not_none(refaspect=refaspect, aspect=aspect)
refwidth = _not_none(refwidth=refwidth, axwidth=axwidth)
refheight = _not_none(refheight=refheight, axheight=axheight)
figwidth = _not_none(figwidth=figwidth, width=width)
figheight = _not_none(figheight=figheight, height=height)
messages = []
if journal is not None:
jwidth, jheight = _get_journal_size(journal)
if jwidth is not None and figwidth is not None:
messages.append(('journal', journal, 'figwidth', figwidth))
if jheight is not None and figheight is not None:
messages.append(('journal', journal, 'figheight', figheight))
figwidth = _not_none(jwidth, figwidth)
figheight = _not_none(jheight, figheight)
if figwidth is not None and refwidth is not None:
messages.append(('figwidth', figwidth, 'refwidth', refwidth))
refwidth = None
if figheight is not None and refheight is not None:
messages.append(('figheight', figheight, 'refheight', refheight))
refheight = None
if figwidth is None and figheight is None and refwidth is None and refheight is None: # noqa: E501
refwidth = rc['subplots.refwidth'] # always inches
if np.iterable(refaspect):
refaspect = refaspect[0] / refaspect[1]
for key1, val1, key2, val2 in messages:
warnings._warn_proplot(
f'Got conflicting figure size arguments {key1}={val1!r} and '
f'{key2}={val2!r}. Ignoring {key2!r}.'
)
self._refnum = refnum
self._refaspect = refaspect
self._refaspect_default = 1 # updated for imshow and geographic plots
self._refwidth = units(refwidth, 'in')
self._refheight = units(refheight, 'in')
self._figwidth = units(figwidth, 'in')
self._figheight = units(figheight, 'in')
# Add special consideration for interactive backends
backend = _not_none(rc.backend, '')
backend = backend.lower()
interactive = 'nbagg' in backend or 'ipympl' in backend
if not interactive:
pass
elif figwidth is None or figheight is None:
figsize = rc['figure.figsize'] # modified by proplot
self._figwidth = figwidth = _not_none(figwidth, figsize[0])
self._figheight = figheight = _not_none(figheight, figsize[1])
self._refwidth = self._refheight = None # critical!
if self._warn_interactive:
Figure._warn_interactive = False # set class attribute
warnings._warn_proplot(
'Auto-sized proplot figures are not compatible with interactive '
"backends like '%matplotlib widget' and '%matplotlib notebook'. "
f'Reverting to the figure size ({figwidth}, {figheight}). To make '
'auto-sized figures, please consider using the non-interactive '
'(default) backend. This warning message is shown the first time '
'you create a figure without explicitly specifying the size.'
)
# Add space settings
# NOTE: This is analogous to 'subplotpars' but we don't worry about
# user mutability. Think it's perfectly fine to ask users to simply
# pass these to pplt.figure() or pplt.subplots(). Also overriding
# 'subplots_adjust' would be confusing since we switch to absolute
# units and that function is heavily used outside of proplot.
params = {
'left': left,
'right': right,
'top': top,
'bottom': bottom,
'wspace': wspace,
'hspace': hspace,
'space': space,
'wpad': wpad,
'hpad': hpad,
'pad': pad,
'outerpad': outerpad,
'innerpad': innerpad,
'panelpad': panelpad,
}
self._gridspec_params = params # used to initialize the gridspec
for key, value in tuple(params.items()):
if not isinstance(value, str) and np.iterable(value) and len(value) > 1:
raise ValueError(
f'Invalid gridspec parameter {key}={value!r}. Space parameters '
'passed to Figure() must be scalar. For vector spaces use '
'GridSpec() or pass space parameters to subplots().'
)
# Add tight layout setting and ignore native settings
pars = kwargs.pop('subplotpars', None)
if pars is not None:
warnings._warn_proplot(
f'Ignoring subplotpars={pars!r}. ' + self._space_message
)
if kwargs.pop('tight_layout', None):
warnings._warn_proplot(
'Ignoring tight_layout=True. ' + self._tight_message
)
if kwargs.pop('constrained_layout', None):
warnings._warn_proplot(
'Ignoring constrained_layout=True. ' + self._tight_message
)
if rc_matplotlib.get('figure.autolayout', False):
warnings._warn_proplot(
"Setting rc['figure.autolayout'] to False. " + self._tight_message
)
if rc_matplotlib.get('figure.constrained_layout.use', False):
warnings._warn_proplot(
"Setting rc['figure.constrained_layout.use'] to False. " + self._tight_message # noqa: E501
)
try:
rc_matplotlib['figure.autolayout'] = False # this is rcParams
except KeyError:
pass
try:
rc_matplotlib['figure.constrained_layout.use'] = False # this is rcParams
except KeyError:
pass
self._tight_active = _not_none(tight, rc['subplots.tight'])
# Translate share settings
translate = {'labels': 1, 'labs': 1, 'limits': 2, 'lims': 2, 'all': 4}
sharex = _not_none(sharex, share, rc['subplots.share'])
sharey = _not_none(sharey, share, rc['subplots.share'])
sharex = 3 if sharex is True else translate.get(sharex, sharex)
sharey = 3 if sharey is True else translate.get(sharey, sharey)
if sharex not in range(5):
raise ValueError(f'Invalid sharex={sharex!r}. ' + self._share_message)
if sharey not in range(5):
raise ValueError(f'Invalid sharey={sharey!r}. ' + self._share_message)
self._sharex = int(sharex)
self._sharey = int(sharey)
# Translate span and align settings
spanx = _not_none(spanx, span, False if not sharex else None, rc['subplots.span']) # noqa: E501
spany = _not_none(spany, span, False if not sharey else None, rc['subplots.span']) # noqa: E501
if spanx and (alignx or align): # only warn when explicitly requested
warnings._warn_proplot('"alignx" has no effect when spanx=True.')
if spany and (aligny or align):
warnings._warn_proplot('"aligny" has no effect when spany=True.')
self._spanx = bool(spanx)
self._spany = bool(spany)
alignx = _not_none(alignx, align, rc['subplots.align'])
aligny = _not_none(aligny, align, rc['subplots.align'])
self._alignx = bool(alignx)
self._aligny = bool(aligny)
# Initialize the figure
# NOTE: Super labels are stored inside {axes: text} dictionaries
self._gridspec = None
self._panel_dict = {'left': [], 'right': [], 'bottom': [], 'top': []}
self._subplot_dict = {} # subplots indexed by number
self._subplot_counter = 0 # avoid add_subplot() returning an existing subplot
self._is_adjusting = False
self._is_authorized = False
self._includepanels = None
self._render_context = {}
rc_kw, rc_mode = _pop_rc(kwargs)
kw_format = _pop_params(kwargs, self._format_signature)
with self._context_authorized():
super().__init__(**kwargs)
# Super labels. We don't rely on private matplotlib _suptitle attribute and
# _align_axis_labels supports arbitrary spanning labels for subplot groups.
# NOTE: Don't use 'anchor' rotation mode otherwise switching to horizontal
# left and right super labels causes overlap. Current method is fine.
self._suptitle = self.text(0.5, 0.95, '', ha='center', va='bottom')
self._supxlabel_dict = {} # an axes: label mapping
self._supylabel_dict = {} # an axes: label mapping
self._suplabel_dict = {'left': {}, 'right': {}, 'bottom': {}, 'top': {}}
self._suptitle_pad = rc['suptitle.pad']
d = self._suplabel_props = {} # store the super label props
d['left'] = {'va': 'center', 'ha': 'right'}
d['right'] = {'va': 'center', 'ha': 'left'}
d['bottom'] = {'va': 'top', 'ha': 'center'}
d['top'] = {'va': 'bottom', 'ha': 'center'}
d = self._suplabel_pad = {} # store the super label padding
d['left'] = rc['leftlabel.pad']
d['right'] = rc['rightlabel.pad']
d['bottom'] = rc['bottomlabel.pad']
d['top'] = rc['toplabel.pad']
# Format figure
# NOTE: This ignores user-input rc_mode.
self.format(rc_kw=rc_kw, rc_mode=1, skip_axes=True, **kw_format)
def _context_adjusting(self, cache=True):
"""
Prevent re-running auto layout steps due to draws triggered by figure
resizes. Otherwise can get infinite loops.
"""
kw = {'_is_adjusting': True}
if not cache:
kw['_cachedRenderer'] = None # temporarily ignore it
return context._state_context(self, **kw)
def _context_authorized(self):
"""
Prevent warning message when internally calling no-op methods. Otherwise
emit warnings to help new users.
"""
return context._state_context(self, _is_authorized=True)
def _parse_proj(
self, proj=None, projection=None,
proj_kw=None, projection_kw=None, basemap=None,
**kwargs
):
"""
Translate the user-input projection into a registered matplotlib
axes class. Input projection can be a string, `matplotlib.axes.Axes`,
`cartopy.crs.Projection`, or `mpl_toolkits.basemap.Basemap`.
"""
# Parse arguments
proj = _not_none(proj=proj, projection=projection, default='cartesian')
proj_kw = _not_none(proj_kw=proj_kw, projection_kw=projection_kw, default={})
if isinstance(proj, str):
proj = proj.lower()
if isinstance(self, paxes.Axes):
proj = self._name
elif isinstance(self, maxes.Axes):
raise ValueError('Matplotlib axes cannot be added to proplot figures.')
# Search axes projections
name = None
if isinstance(proj, str):
try:
mproj.get_projection_class('proplot_' + proj)
except (KeyError, ValueError):
pass
else:
name = proj
# Helpful error message
if (
name is None
and basemap is None
and isinstance(proj, str)
and constructor.Projection is object
and constructor.Basemap is object
):
raise ValueError(
f'Invalid projection name {proj!r}. If you are trying to generate a '
'GeoAxes with a cartopy.crs.Projection or mpl_toolkits.basemap.Basemap '
'then cartopy or basemap must be installed. Otherwise the known axes '
f'subclasses are:\n{paxes._cls_table}'
)
# Search geographic projections
# NOTE: Also raises errors due to unexpected projection type
if name is None:
proj = constructor.Proj(proj, basemap=basemap, include_axes=True, **proj_kw)
name = proj._proj_package
kwargs['map_projection'] = proj
kwargs['projection'] = 'proplot_' + name
return kwargs
def _get_align_axes(self, side):
"""
Return the main axes along the edge of the figure.
"""
x, y = 'xy' if side in ('left', 'right') else 'yx'
axs = self._subplot_dict.values()
if not axs:
return []
ranges = np.array([ax._range_subplotspec(x) for ax in axs])
edge = ranges[:, 0].min() if side in ('left', 'top') else ranges[:, 1].max()
idx = 0 if side in ('left', 'top') else 1
axs = [ax for ax in axs if ax._range_subplotspec(x)[idx] == edge]
axs = [ax for ax in sorted(axs, key=lambda ax: ax._range_subplotspec(y)[0])]
axs = [ax for ax in axs if ax.get_visible()]
return axs
def _get_align_coord(self, side, axs, includepanels=False):
"""
Return the figure coordinate for centering spanning axis labels or super titles.
"""
# Get position in figure relative coordinates
if not all(isinstance(ax, paxes.Axes) for ax in axs):
raise RuntimeError('Axes must be proplot axes.')
if not all(isinstance(ax, maxes.SubplotBase) for ax in axs):
raise RuntimeError('Axes must be subplots.')
s = 'y' if side in ('left', 'right') else 'x'
axs = [ax._panel_parent or ax for ax in axs] # deflect to main axes
if includepanels: # include panel short axes?
axs = [_ for ax in axs for _ in ax._iter_axes(panels=True, children=False)]
ranges = np.array([ax._range_subplotspec(s) for ax in axs])
min_, max_ = ranges[:, 0].min(), ranges[:, 1].max()
ax_lo = axs[np.where(ranges[:, 0] == min_)[0][0]]
ax_hi = axs[np.where(ranges[:, 1] == max_)[0][0]]
box_lo = ax_lo.get_subplotspec().get_position(self)
box_hi = ax_hi.get_subplotspec().get_position(self)
if s == 'x':
pos = 0.5 * (box_lo.x0 + box_hi.x1)
else:
pos = 0.5 * (box_lo.y1 + box_hi.y0) # 'lo' is actually on top of figure
ax = axs[(np.argmin(ranges[:, 0]) + np.argmax(ranges[:, 1])) // 2]
ax = ax._panel_parent or ax # always use main subplot for spanning labels
return pos, ax
def _get_offset_coord(self, side, axs, renderer, *, pad=None, extra=None):
"""
Return the figure coordinate for offsetting super labels and super titles.
"""
s = 'x' if side in ('left', 'right') else 'y'
cs = []
objs = tuple(_ for ax in axs for _ in ax._iter_axes(panels=True, children=True, hidden=True)) # noqa: E501
objs = objs + (extra or ()) # e.g. top super labels
for obj in objs:
bbox = obj.get_tightbbox(renderer) # cannot use cached bbox
attr = s + 'max' if side in ('top', 'right') else s + 'min'
c = getattr(bbox, attr)
c = (c, 0) if side in ('left', 'right') else (0, c)
c = self.transFigure.inverted().transform(c)
c = c[0] if side in ('left', 'right') else c[1]
cs.append(c)
width, height = self.get_size_inches()
if pad is None:
pad = self._suplabel_pad[side] / 72
pad = pad / width if side in ('left', 'right') else pad / height
return min(cs) - pad if side in ('left', 'bottom') else max(cs) + pad
def _get_renderer(self):
"""
Get a renderer at all costs. See matplotlib's tight_layout.py.
"""
if self._cachedRenderer:
renderer = self._cachedRenderer
else:
canvas = self.canvas
if canvas and hasattr(canvas, 'get_renderer'):
renderer = canvas.get_renderer()
else:
from matplotlib.backends.backend_agg import FigureCanvasAgg
canvas = FigureCanvasAgg(self)
renderer = canvas.get_renderer()
return renderer
def _add_axes_panel(self, ax, side=None, **kwargs):
"""
Add an axes panel.
"""
# Interpret args
# NOTE: Axis sharing not implemented for figure panels, 99% of the
# time this is just used as construct for adding global colorbars and
# legends, really not worth implementing axis sharing
ax = ax._altx_parent or ax
ax = ax._alty_parent or ax
if not isinstance(ax, paxes.Axes):
raise RuntimeError('Cannot add panels to non-proplot axes.')
if not isinstance(ax, maxes.SubplotBase):
raise RuntimeError('Cannot add panels to non-subplot axes.')
orig = ax._panel_side
if orig is None:
pass
elif side is None or side == orig:
ax, side = ax._panel_parent, orig
else:
raise RuntimeError(f'Cannot add {side!r} panel to existing {orig!r} panel.')
side = _translate_loc(side, 'panel', default=_not_none(orig, 'right'))
# Add and setup the panel accounting for index changes
# NOTE: Always put tick labels on the 'outside'
gs = self.gridspec
if not gs:
raise RuntimeError('The gridspec must be active.')
ss, share = gs._insert_panel_slot(side, ax, **kwargs)
pax = self.add_subplot(ss, autoshare=False, number=False)
pax._panel_side = side
pax._panel_share = share
pax._panel_parent = ax
ax._panel_dict[side].append(pax)
ax._apply_auto_share()
axis = pax.yaxis if side in ('left', 'right') else pax.xaxis
getattr(axis, 'tick_' + side)() # set tick and tick label position
axis.set_label_position(side) # set label position
return pax
def _add_figure_panel(
self, side=None, span=None, row=None, col=None, rows=None, cols=None, **kwargs
):
"""
Add a figure panel.
"""
# Interpret args and enforce sensible keyword args
side = _translate_loc(side, 'panel', default='right')
if side in ('left', 'right'):
for key, value in (('col', col), ('cols', cols)):
if value is not None:
raise ValueError(f'Invalid keyword {key!r} for {side!r} panel.')
span = _not_none(span=span, row=row, rows=rows)
else:
for key, value in (('row', row), ('rows', rows)):
if value is not None:
raise ValueError(f'Invalid keyword {key!r} for {side!r} panel.')
span = _not_none(span=span, col=col, cols=cols)
# Add and setup panel
# NOTE: This relies on panel slot obfuscation built into gridspec
gs = self.gridspec
if not gs:
raise RuntimeError('The gridspec must be active.')
ss, _ = gs._insert_panel_slot(side, span, filled=True, **kwargs)
pax = self.add_subplot(ss, autoshare=False, number=False)
plist = self._panel_dict[side]
plist.append(pax)
pax._panel_side = side
pax._panel_share = False
pax._panel_parent = None
return pax
def _add_subplot(self, *args, **kwargs):
"""
The driver function for adding single subplots.
"""
# Parse arguments
kwargs = self._parse_proj(**kwargs)
args = args or (1, 1, 1)
gs = self.gridspec
# Integer arg
if len(args) == 1 and isinstance(args[0], Integral):
if not 111 <= args[0] <= 999:
raise ValueError(f'Input {args[0]} must fall between 111 and 999.')
args = tuple(map(int, str(args[0])))
# Subplot spec
if (
len(args) == 1
and isinstance(args[0], (maxes.SubplotBase, mgridspec.SubplotSpec))
):
ss = args[0]
if isinstance(ss, maxes.SubplotBase):
ss = ss.get_subplotspec()
if gs is None:
gs = ss.get_topmost_subplotspec().get_gridspec()
if not isinstance(gs, pgridspec.GridSpec):
raise ValueError(
'Input subplotspec must be derived from a proplot.GridSpec.'
)
if ss.get_topmost_subplotspec().get_gridspec() is not gs: