/
wrappers.py
3148 lines (2948 loc) 路 126 KB
/
wrappers.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
"""
These "wrapper" functions are applied to various `~proplot.axes.Axes` plotting
methods. When a function is "wrapped", it accepts the parameters that the
"wrapper" function accepts. In a future version, these features will be
documented on the individual plotting methods, but for now they are documented
separately on the "wrappers".
"""
import sys
import numpy as np
import numpy.ma as ma
import functools
from . import styletools, axistools
from .utils import _warn_proplot, _notNone, edges, edges2d, units
import matplotlib.axes as maxes
import matplotlib.container as mcontainer
import matplotlib.contour as mcontour
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.patheffects as mpatheffects
import matplotlib.patches as mpatches
import matplotlib.colors as mcolors
import matplotlib.artist as martist
import matplotlib.legend as mlegend
from numbers import Number
from .rctools import rc
try: # use this for debugging instead of print()!
from icecream import ic
except ImportError: # graceful fallback if IceCream isn't installed
ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa
try:
from cartopy.crs import PlateCarree
except ModuleNotFoundError:
PlateCarree = object
__all__ = [
'add_errorbars', 'bar_wrapper', 'barh_wrapper', 'boxplot_wrapper',
'default_crs', 'default_latlon', 'default_transform',
'cmap_changer',
'cycle_changer',
'colorbar_wrapper',
'fill_between_wrapper', 'fill_betweenx_wrapper', 'hist_wrapper',
'legend_wrapper', 'plot_wrapper', 'scatter_wrapper',
'standardize_1d', 'standardize_2d', 'text_wrapper',
'violinplot_wrapper',
]
def _load_objects():
"""Delay loading expensive modules. We just want to detect if *input
arrays* belong to these types -- and if this is the case, it means the
module has already been imported! So, we only try loading these classes
within autoformat calls. This saves >~500ms of import time."""
global DataArray, DataFrame, Series, Index, ndarray
ndarray = np.ndarray
DataArray = getattr(sys.modules.get('xarray', None), 'DataArray', ndarray)
DataFrame = getattr(sys.modules.get('pandas', None), 'DataFrame', ndarray)
Series = getattr(sys.modules.get('pandas', None), 'Series', ndarray)
Index = getattr(sys.modules.get('pandas', None), 'Index', ndarray)
_load_objects()
# Keywords for styling cmap overridden plots
# TODO: Deprecate this when #45 merged! Pcolor *already* accepts lw,
# linewidth, *and* linewidths!
STYLE_ARGS_TRANSLATE = {
'contour': {
'colors': 'colors',
'linewidths': 'linewidths',
'linestyles': 'linestyles'},
'hexbin': {
'colors': 'edgecolors',
'linewidths': 'linewidths'},
'tricontour': {
'colors': 'colors',
'linewidths': 'linewidths',
'linestyles': 'linestyles'},
'parametric': {
'colors': 'color',
'linewidths': 'linewidth',
'linestyles': 'linestyle'},
'pcolor': {
'colors': 'edgecolors',
'linewidths': 'linewidth',
'linestyles': 'linestyle'},
'tripcolor': {
'colors': 'edgecolors',
'linewidths': 'linewidth',
'linestyles': 'linestyle'},
'pcolormesh': {
'colors': 'edgecolors',
'linewidths': 'linewidth',
'linestyles': 'linestyle'},
}
def _is_number(data):
"""Test whether input is numeric array rather than datetime or strings."""
return len(data) and np.issubdtype(_to_array(data).dtype, np.number)
def _is_string(data):
"""Test whether input is array of strings."""
return len(data) and isinstance(_to_array(data).flat[0], str)
def _to_array(data):
"""Convert to ndarray cleanly."""
return np.asarray(getattr(data, 'values', data))
def _to_arraylike(data):
"""Converts list of lists to array."""
_load_objects()
if not isinstance(data, (ndarray, DataArray, DataFrame, Series, Index)):
data = np.array(data)
if not np.iterable(data):
data = np.atleast_1d(data)
return data
def _to_iloc(data):
"""Indexible attribute of array."""
return getattr(data, 'iloc', data)
def default_latlon(self, func, *args, latlon=True, **kwargs):
"""
Makes ``latlon=True`` the default for basemap plots.
Wraps %(methods)s for `~proplot.axes.BasemapAxes`.
This means you no longer have to pass ``latlon=True`` if your data
coordinates are longitude and latitude.
"""
return func(self, *args, latlon=latlon, **kwargs)
def default_transform(self, func, *args, transform=None, **kwargs):
"""
Makes ``transform=cartopy.crs.PlateCarree()`` the default
for cartopy plots.
Wraps %(methods)s for `~proplot.axes.GeoAxes`.
This means you no longer have to
pass ``transform=cartopy.crs.PlateCarree()`` if your data
coordinates are longitude and latitude.
"""
# Apply default transform
# TODO: Do some cartopy methods reset backgroundpatch or outlinepatch?
# Deleted comment reported this issue
if transform is None:
transform = PlateCarree()
result = func(self, *args, transform=transform, **kwargs)
return result
def default_crs(self, func, *args, crs=None, **kwargs):
"""
Fixes the `~cartopy.mpl.geoaxes.GeoAxes.set_extent` bug associated with
tight bounding boxes and makes ``crs=cartopy.crs.PlateCarree()`` the
default for cartopy plots. Wraps %(methods)s
for `~proplot.axes.GeoAxes`.
"""
# Apply default crs
name = func.__name__
if crs is None:
crs = PlateCarree()
try:
result = func(self, *args, crs=crs, **kwargs)
except TypeError as err: # duplicate keyword args, i.e. crs is positional
if not args:
raise err
result = func(self, *args[:-1], crs=args[-1], **kwargs)
# Fix extent, so axes tight bounding box gets correct box!
# From this issue:
# https://github.com/SciTools/cartopy/issues/1207#issuecomment-439975083
if name == 'set_extent':
clipped_path = self.outline_patch.orig_path.clip_to_bbox(self.viewLim)
self.outline_patch._path = clipped_path
self.background_patch._path = clipped_path
return result
def _standard_label(data, axis=None, units=True):
"""Gets data and label for pandas or xarray objects or
their coordinates."""
label = ''
_load_objects()
if isinstance(data, ndarray):
if axis is not None and data.ndim > axis:
data = np.arange(data.shape[axis])
# Xarray with common NetCDF attribute names
elif isinstance(data, DataArray):
if axis is not None and data.ndim > axis:
data = data.coords[data.dims[axis]]
label = getattr(data, 'name', '') or ''
for key in ('standard_name', 'long_name'):
label = data.attrs.get(key, label)
if units:
units = data.attrs.get('units', '')
if label and units:
label = f'{label} ({units})'
elif units:
label = units
# Pandas object with name attribute
# if not label and isinstance(data, DataFrame) and data.columns.size == 1:
elif isinstance(data, (DataFrame, Series, Index)):
if axis == 0 and isinstance(data, (DataFrame, Series)):
data = data.index
elif axis == 1 and isinstance(data, DataFrame):
data = data.columns
elif axis is not None:
data = np.arange(len(data)) # e.g. for Index
# DataFrame has no native name attribute but user can add one:
# https://github.com/pandas-dev/pandas/issues/447
label = getattr(data, 'name', '') or ''
return data, str(label).strip()
def standardize_1d(self, func, *args, **kwargs):
"""
Interprets positional arguments for the "1d" plotting methods
%(methods)s. This also optionally modifies the x axis label, y axis label,
title, and axis ticks if a `~xarray.DataArray`, `~pandas.DataFrame`, or
`~pandas.Series` is passed.
Positional arguments are standardized as follows:
* If a 2D array is passed, the corresponding plot command is called for
each column of data (except for ``boxplot`` and ``violinplot``, in which
case each column is interpreted as a distribution).
* If *x* and *y* or *latitude* and *longitude* coordinates were not
provided, and a `~pandas.DataFrame` or `~xarray.DataArray`, we
try to infer them from the metadata. Otherwise,
``np.arange(0, data.shape[0])`` is used.
"""
# Sanitize input
# TODO: Add exceptions for methods other than 'hist'?
name = func.__name__
_load_objects()
if not args:
return func(self, *args, **kwargs)
elif len(args) == 1:
x = None
y, *args = args
elif len(args) in (2, 3, 4):
x, y, *args = args # same
else:
raise ValueError(f'Too many arguments passed to {name}. Max is 4.')
vert = kwargs.get('vert', None)
if vert is not None:
orientation = ('vertical' if vert else 'horizontal')
else:
orientation = kwargs.get('orientation', 'vertical')
# Iterate through list of ys that we assume are identical
# Standardize based on the first y input
if len(args) >= 1 and 'fill_between' in name:
ys, args = (y, args[0]), args[1:]
else:
ys = (y,)
ys = [_to_arraylike(y) for y in ys]
# Auto x coords
y = ys[0] # test the first y input
if x is None:
axis = 1 if (name in ('hist', 'boxplot', 'violinplot') or any(
kwargs.get(s, None) for s in ('means', 'medians'))) else 0
x, _ = _standard_label(y, axis=axis)
x = _to_arraylike(x)
if x.ndim != 1:
raise ValueError(
f'x coordinates must be 1-dimensional, but got {x.ndim}.'
)
# Auto formatting
xi = None # index version of 'x'
if not hasattr(self, 'projection'):
# First handle string-type x-coordinates
kw = {}
xax = 'y' if orientation == 'horizontal' else 'x'
yax = 'x' if xax == 'y' else 'y'
if _is_string(x):
xi = np.arange(len(x))
kw[xax + 'locator'] = mticker.FixedLocator(xi)
kw[xax + 'formatter'] = mticker.IndexFormatter(x)
kw[xax + 'minorlocator'] = mticker.NullLocator()
if name == 'boxplot':
kwargs['labels'] = x
elif name == 'violinplot':
kwargs['positions'] = xi
if name in ('boxplot', 'violinplot'):
kwargs['positions'] = xi
# Next handle labels if 'autoformat' is on
if self.figure._auto_format:
# Ylabel
y, label = _standard_label(y)
if label:
# for histogram, this indicates x coordinate
iaxis = xax if name in ('hist',) else yax
kw[iaxis + 'label'] = label
# Xlabel
x, label = _standard_label(x)
if label and name not in ('hist',):
kw[xax + 'label'] = label
if name != 'scatter' and len(x) > 1 and xi is None and x[1] < x[0]:
kw[xax + 'reverse'] = True
# Appply
if kw:
self.format(**kw)
# Standardize args
if xi is not None:
x = xi
if name in ('boxplot', 'violinplot'):
ys = [_to_array(yi) for yi in ys] # store naked array
# Basemap shift x coordiantes without shifting y, we fix this!
if getattr(self, 'name', '') == 'basemap' and kwargs.get('latlon', None):
ix, iys = x, []
xmin, xmax = self.projection.lonmin, self.projection.lonmax
for y in ys:
# Ensure data is monotonic and falls within map bounds
ix, iy = _enforce_bounds(*_standardize_latlon(x, y), xmin, xmax)
iys.append(iy)
x, ys = ix, iys
# WARNING: For some functions, e.g. boxplot and violinplot, we *require*
# cycle_changer is also applied so it can strip 'x' input.
return func(self, x, *ys, *args, **kwargs)
def _interp_poles(y, Z):
"""Adds data points on the poles as the average of highest
latitude data."""
# Get means
with np.errstate(all='ignore'):
p1 = Z[0, :].mean() # pole 1, make sure is not 0D DataArray!
p2 = Z[-1, :].mean() # pole 2
if hasattr(p1, 'item'):
p1 = np.asscalar(p1) # happens with DataArrays
if hasattr(p2, 'item'):
p2 = np.asscalar(p2)
# Concatenate
ps = (-90, 90) if (y[0] < y[-1]) else (90, -90)
Z1 = np.repeat(p1, Z.shape[1])[None, :]
Z2 = np.repeat(p2, Z.shape[1])[None, :]
y = ma.concatenate((ps[:1], y, ps[1:]))
Z = ma.concatenate((Z1, Z, Z2), axis=0)
return y, Z
def _standardize_latlon(x, y):
"""Ensures monotonic longitudes and makes `~numpy.ndarray` copies so the
contents can be modified. Ignores 2D coordinate arrays."""
# Sanitization and bail if 2D
if x.ndim == 1:
x = ma.array(x)
if y.ndim == 1:
y = ma.array(y)
if x.ndim != 1 or all(x < x[0]): # skip monotonic backwards data
return x, y
# Enforce monotonic longitudes
lon1 = x[0]
while True:
filter_ = (x < lon1)
if filter_.sum() == 0:
break
x[filter_] += 360
return x, y
def _enforce_bounds(x, y, xmin, xmax):
"""Ensures data for basemap plots is restricted between the minimum and
maximum longitude of the projection. Input is the ``x`` and ``y``
coordinates. The ``y`` coordinates are rolled along the rightmost axis."""
if x.ndim != 1:
return x, y
# Roll in same direction if some points on right-edge extend
# more than 360 above min longitude; *they* should be on left side
lonroll = np.where(x > xmin + 360)[0] # tuple of ids
if lonroll.size: # non-empty
roll = x.size - lonroll.min()
x = np.roll(x, roll)
y = np.roll(y, roll, axis=-1)
x[:roll] -= 360 # make monotonic
# Set NaN where data not in range xmin, xmax. Must be done
# for regional smaller projections or get weird side-effects due
# to having valid data way outside of the map boundaries
y = y.copy()
if x.size - 1 == y.shape[-1]: # test western/eastern grid cell edges
y[..., (x[1:] < xmin) | (x[:-1] > xmax)] = np.nan
elif x.size == y.shape[-1]: # test the centers and pad by one for safety
where = np.where((x < xmin) | (x > xmax))[0]
y[..., where[1:-1]] = np.nan
return x, y
def standardize_2d(self, func, *args, order='C', globe=False, **kwargs):
"""
Interprets positional arguments for the "2d" plotting methods
%(methods)s. This also optionally modifies the x axis label, y axis label,
title, and axis ticks if a `~xarray.DataArray`, `~pandas.DataFrame`, or
`~pandas.Series` is passed.
Positional arguments are standardized as follows:
* If *x* and *y* or *latitude* and *longitude* coordinates were not
provided, and a `~pandas.DataFrame` or `~xarray.DataArray` is passed, we
try to infer them from the metadata. Otherwise,
``np.arange(0, data.shape[0])`` and ``np.arange(0, data.shape[1])``
are used.
* For ``pcolor`` and ``pcolormesh``, coordinate *edges* are calculated
if *centers* were provided. For all other methods, coordinate *centers*
are calculated if *edges* were provided.
For `~proplot.axes.GeoAxes` and `~proplot.axes.BasemapAxes`, the
`globe` keyword arg is added, suitable for plotting datasets with global
coverage. Passing ``globe=True`` does the following:
1. "Interpolates" input data to the North and South poles.
2. Makes meridional coverage "circular", i.e. the last longitude coordinate
equals the first longitude coordinate plus 360\N{DEGREE SIGN}.
For `~proplot.axes.BasemapAxes`, 1D longitude vectors are also cycled to
fit within the map edges. For example, if the projection central longitude
is 90\N{DEGREE SIGN}, the data is shifted so that it spans
-90\N{DEGREE SIGN} to 270\N{DEGREE SIGN}.
"""
# Sanitize input
name = func.__name__
_load_objects()
if not args:
return func(self, *args, **kwargs)
elif len(args) > 4:
raise ValueError(f'Too many arguments passed to {name}. Max is 4.')
x, y = None, None
if len(args) > 2:
x, y, *args = args
# Ensure DataArray, DataFrame or ndarray
Zs = []
for Z in args:
Z = _to_arraylike(Z)
if Z.ndim != 2:
raise ValueError(f'Z must be 2-dimensional, got shape {Z.shape}.')
Zs.append(Z)
if not all(Zs[0].shape == Z.shape for Z in Zs):
raise ValueError(
f'Zs must be same shape, got shapes {[Z.shape for Z in Zs]}.'
)
# Retrieve coordinates
if x is None and y is None:
Z = Zs[0]
if order == 'C': # TODO: check order stuff works
idx, idy = 1, 0
else:
idx, idy = 0, 1
if isinstance(Z, ndarray):
x = np.arange(Z.shape[idx])
y = np.arange(Z.shape[idy])
elif isinstance(Z, DataArray): # DataArray
x = Z.coords[Z.dims[idx]]
y = Z.coords[Z.dims[idy]]
else: # DataFrame; never Series or Index because these are 1D
x = Z.index
y = Z.columns
# Check coordinates
x, y = _to_arraylike(x), _to_arraylike(y)
if x.ndim != y.ndim:
raise ValueError(
f'x coordinates are {x.ndim}-dimensional, '
f'but y coordinates are {y.ndim}-dimensional.'
)
for s, array in zip(('x', 'y'), (x, y)):
if array.ndim not in (1, 2):
raise ValueError(
f'{s} coordinates are {array.ndim}-dimensional, '
f'but must be 1 or 2-dimensional.'
)
# Auto formatting
kw = {}
xi, yi = None, None
if not hasattr(self, 'projection'):
# First handle string-type x and y-coordinates
if _is_string(x):
xi = np.arange(len(x))
kw['xlocator'] = mticker.FixedLocator(xi)
kw['xformatter'] = mticker.IndexFormatter(x)
kw['xminorlocator'] = mticker.NullLocator()
if _is_string(x):
yi = np.arange(len(y))
kw['ylocator'] = mticker.FixedLocator(yi)
kw['yformatter'] = mticker.IndexFormatter(y)
kw['yminorlocator'] = mticker.NullLocator()
# Handle labels if 'autoformat' is on
if self.figure._auto_format:
for key, xy in zip(('xlabel', 'ylabel'), (x, y)):
_, label = _standard_label(xy)
if label:
kw[key] = label
if len(xy) > 1 and all(isinstance(xy, Number)
for xy in xy[:2]) and xy[1] < xy[0]:
kw[key[0] + 'reverse'] = True
if xi is not None:
x = xi
if yi is not None:
y = yi
# Handle figure titles
if self.figure._auto_format:
_, colorbar_label = _standard_label(Zs[0], units=True)
_, title = _standard_label(Zs[0], units=False)
if title:
kw['title'] = title
if kw:
self.format(**kw)
# Enforce edges
if name in ('pcolor', 'pcolormesh'):
# Get centers or raise error. If 2D, don't raise error, but don't fix
# either, because matplotlib pcolor just trims last column and row.
xlen, ylen = x.shape[-1], y.shape[0]
for Z in Zs:
if Z.ndim != 2:
raise ValueError(
f'Input arrays must be 2D, instead got shape {Z.shape}.'
)
elif Z.shape[1] == xlen and Z.shape[0] == ylen:
if all(
z.ndim == 1 and z.size > 1
and _is_number(z) for z in (x, y)
):
x = edges(x)
y = edges(y)
else:
if (
x.ndim == 2 and x.shape[0] > 1 and x.shape[1] > 1
and _is_number(x)
):
x = edges2d(x)
if (
y.ndim == 2 and y.shape[0] > 1 and y.shape[1] > 1
and _is_number(y)
):
y = edges2d(y)
elif Z.shape[1] != xlen - 1 or Z.shape[0] != ylen - 1:
raise ValueError(
f'Input shapes x {x.shape} and y {y.shape} must match '
f'Z centers {Z.shape} or '
f'Z borders {tuple(i+1 for i in Z.shape)}.'
)
# Optionally re-order
# TODO: Double check this
if order == 'F':
x, y = x.T, y.T # in case they are 2-dimensional
Zs = (Z.T for Z in Zs)
elif order != 'C':
raise ValueError(
f'Invalid order {order!r}. Choose from '
'"C" (row-major, default) and "F" (column-major).'
)
# Enforce centers
else:
# Get centers given edges. If 2D, don't raise error, let matplotlib
# raise error down the line.
xlen, ylen = x.shape[-1], y.shape[0]
for Z in Zs:
if Z.ndim != 2:
raise ValueError(
f'Input arrays must be 2D, instead got shape {Z.shape}.'
)
elif Z.shape[1] == xlen - 1 and Z.shape[0] == ylen - 1:
if all(
z.ndim == 1 and z.size > 1
and _is_number(z) for z in (x, y)
):
x = (x[1:] + x[:-1]) / 2
y = (y[1:] + y[:-1]) / 2
else:
if (
x.ndim == 2 and x.shape[0] > 1 and x.shape[1] > 1
and _is_number(x)
):
x = 0.25 * (
x[:-1, :-1] + x[:-1, 1:] + x[1:, :-1] + x[1:, 1:]
)
if (
y.ndim == 2 and y.shape[0] > 1 and y.shape[1] > 1
and _is_number(y)
):
y = 0.25 * (
y[:-1, :-1] + y[:-1, 1:] + y[1:, :-1] + y[1:, 1:]
)
elif Z.shape[1] != xlen or Z.shape[0] != ylen:
raise ValueError(
f'Input shapes x {x.shape} and y {y.shape} '
f'must match Z centers {Z.shape} '
f'or Z borders {tuple(i+1 for i in Z.shape)}.'
)
# Optionally re-order
# TODO: Double check this
if order == 'F':
x, y = x.T, y.T # in case they are 2-dimensional
Zs = (Z.T for Z in Zs)
elif order != 'C':
raise ValueError(
f'Invalid order {order!r}. Choose from '
'"C" (row-major, default) and "F" (column-major).'
)
# Cartopy projection axes
if (getattr(self, 'name', '') == 'geo'
and isinstance(kwargs.get('transform', None), PlateCarree)):
x, y = _standardize_latlon(x, y)
ix, iZs = x, []
for Z in Zs:
if globe and x.ndim == 1 and y.ndim == 1:
# Fix holes over poles by *interpolating* there
y, Z = _interp_poles(y, Z)
# Fix seams by ensuring circular coverage. Unlike basemap,
# cartopy can plot across map edges.
if (x[0] % 360) != ((x[-1] + 360) % 360):
ix = ma.concatenate((x, [x[0] + 360]))
Z = ma.concatenate((Z, Z[:, :1]), axis=1)
iZs.append(Z)
x, Zs = ix, iZs
# Basemap projection axes
elif getattr(self, 'name', '') == 'basemap' and kwargs.get('latlon', None):
# Fix grid
xmin, xmax = self.projection.lonmin, self.projection.lonmax
x, y = _standardize_latlon(x, y)
ix, iZs = x, []
for Z in Zs:
# Ensure data is within map bounds
ix, Z = _enforce_bounds(x, Z, xmin, xmax)
# Globe coverage fixes
if globe and ix.ndim == 1 and y.ndim == 1:
# Fix holes over poles by interpolating there (equivalent to
# simple mean of highest/lowest latitude points)
y, Z = _interp_poles(y, Z)
# Fix seams at map boundary; 3 scenarios here:
# Have edges (e.g. for pcolor), and they fit perfectly against
# basemap seams. Does not augment size.
if ix[0] == xmin and ix.size - 1 == Z.shape[1]:
pass # do nothing
# Have edges (e.g. for pcolor), and the projection edge is
# in-between grid cell boundaries. Augments size by 1.
elif ix.size - 1 == Z.shape[1]: # just add grid cell
ix = ma.append(xmin, ix)
ix[-1] = xmin + 360
Z = ma.concatenate((Z[:, -1:], Z), axis=1)
# Have centers (e.g. for contourf), and we need to interpolate
# to left/right edges of the map boundary. Augments size by 2.
elif ix.size == Z.shape[1]:
xi = np.array([ix[-1], ix[0] + 360]) # x
if xi[0] != xi[1]:
Zq = ma.concatenate((Z[:, -1:], Z[:, :1]), axis=1)
xq = xmin + 360
Zq = (
Zq[:, :1] * (xi[1] - xq) + Zq[:, 1:] * (xq - xi[0])
) / (xi[1] - xi[0])
ix = ma.concatenate(([xmin], ix, [xmin + 360]))
Z = ma.concatenate((Zq, Z, Zq), axis=1)
else:
raise ValueError(
'Unexpected shape of longitude/latitude/data arrays.'
)
iZs.append(Z)
x, Zs = ix, iZs
# Convert to projection coordinates
if x.ndim == 1 and y.ndim == 1:
x, y = np.meshgrid(x, y)
x, y = self.projection(x, y)
kwargs['latlon'] = False
# Finally return result
# WARNING: Must apply default colorbar label *here* in case metadata
# was stripped by globe=True.
colorbar_kw = kwargs.pop('colorbar_kw', None) or {}
colorbar_kw.setdefault('label', colorbar_label)
return func(self, x, y, *Zs, colorbar_kw=colorbar_kw, **kwargs)
def _errorbar_values(data, idata, bardata=None, barrange=None, barstd=False):
"""Returns values that can be passed to the `~matplotlib.axes.Axes.errorbar`
`xerr` and `yerr` keyword args."""
if bardata is not None:
err = np.array(bardata)
if err.ndim == 1:
err = err[:, None]
if err.ndim != 2 or err.shape[0] != 2 \
or err.shape[1] != idata.shape[-1]:
raise ValueError(
f'bardata must have shape (2, {idata.shape[-1]}), '
f'but got {err.shape}.'
)
elif barstd:
err = np.array(idata) + \
np.std(data, axis=0)[None, :] * np.array(barrange)[:, None]
else:
err = np.percentile(data, barrange, axis=0)
err = err - np.array(idata)
err[0, :] *= -1 # array now represents error bar sizes
return err
def add_errorbars(
self, func, *args,
medians=False, means=False,
boxes=None, bars=None,
boxdata=None, bardata=None,
boxstd=False, barstd=False,
boxmarker=True, boxmarkercolor='white',
boxrange=(25, 75), barrange=(5, 95), boxcolor=None, barcolor=None,
boxlw=None, barlw=None, capsize=None,
boxzorder=3, barzorder=3,
**kwargs
):
"""
Adds support for drawing error bars to the "1d" plotting methods
%(methods)s. Includes options for interpreting columns of data as ranges,
representing the mean or median of each column with lines, points, or bars,
and drawing error bars representing percentile ranges or standard deviation
multiples for the data in each column.
Parameters
----------
*args
The input data.
bars : bool, optional
Toggles *thin* error bars with optional "whiskers" (i.e. caps). Default
is ``True`` when `means` is ``True``, `medians` is ``True``, or
`bardata` is not ``None``.
boxes : bool, optional
Toggles *thick* boxplot-like error bars with a marker inside
representing the mean or median. Default is ``True`` when `means` is
``True``, `medians` is ``True``, or `boxdata` is not ``None``.
means : bool, optional
Whether to plot the means of each column in the input data.
medians : bool, optional
Whether to plot the medians of each column in the input data.
bardata, boxdata : 2xN ndarray, optional
Arrays that manually specify the thin and thick error bar coordinates.
The first row contains lower bounds, and the second row contains
upper bounds. Columns correspond to points in the dataset.
barstd, boxstd : bool, optional
Whether `barrange` and `boxrange` refer to multiples of the standard
deviation, or percentile ranges. Default is ``False``.
barrange : (float, float), optional
Percentile ranges or standard deviation multiples for drawing thin
error bars. The defaults are ``(-3,3)`` (i.e. +/-3 standard deviations)
when `barstd` is ``True``, and ``(0,100)`` (i.e. the full data range)
when `barstd` is ``False``.
boxrange : (float, float), optional
Percentile ranges or standard deviation multiples for drawing thick
error bars. The defaults are ``(-1,1)`` (i.e. +/-1 standard deviation)
when `boxstd` is ``True``, and ``(25,75)`` (i.e. the middle 50th
percentile) when `boxstd` is ``False``.
barcolor, boxcolor : color-spec, optional
Colors for the thick and thin error bars. Default is ``'k'``.
barlw, boxlw : float, optional
Line widths for the thin and thick error bars, in points. Default
`barlw` is ``0.7`` and default `boxlw` is ``4*barlw``.
boxmarker : bool, optional
Whether to draw a small marker in the middle of the box denoting
the mean or median position. Ignored if `boxes` is ``False``.
Default is ``True``.
boxmarkercolor : color-spec, optional
Color for the `boxmarker` marker. Default is ``'w'``.
capsize : float, optional
The cap size for thin error bars, in points.
barzorder, boxzorder : float, optional
The "zorder" for the thin and thick error bars.
lw, linewidth : float, optional
If passed, this is used for the default `barlw`.
edgecolor : float, optional
If passed, this is used for the default `barcolor` and `boxcolor`.
"""
name = func.__name__
x, y, *args = args
# Sensible defaults
if boxdata is not None:
bars = _notNone(bars, True)
if bardata is not None:
boxes = _notNone(boxes, True)
if boxdata is not None or bardata is not None:
# e.g. if boxdata passed but bardata not passed, use bars=False
bars = _notNone(bars, False)
boxes = _notNone(boxes, False)
# Get means or medians for plotting
iy = y
if (means or medians):
bars = _notNone(bars, True)
boxes = _notNone(boxes, True)
if y.ndim != 2:
raise ValueError(
f'Need 2D data array for means=True or medians=True, '
f'got {y.ndim}D array.'
)
if means:
iy = np.mean(y, axis=0)
elif medians:
iy = np.percentile(y, 50, axis=0)
# Call function, accounting for different signatures of plot and violinplot
get = kwargs.pop if name == 'violinplot' else kwargs.get
lw = _notNone(get('lw', None), get('linewidth', None), 0.7)
get = kwargs.pop if name != 'bar' else kwargs.get
edgecolor = _notNone(get('edgecolor', None), 'k')
if name == 'violinplot':
xy = (x, y) # full data
else:
xy = (x, iy) # just the stats
obj = func(self, *xy, *args, **kwargs)
if not boxes and not bars:
return obj
# Account for horizontal bar plots
if 'vert' in kwargs:
orientation = 'vertical' if kwargs['vert'] else 'horizontal'
else:
orientation = kwargs.get('orientation', 'vertical')
if orientation == 'horizontal':
axis = 'x' # xerr
xy = (iy, x)
else:
axis = 'y' # yerr
xy = (x, iy)
# Defaults settings
barlw = _notNone(barlw, lw)
boxlw = _notNone(boxlw, 4 * barlw)
capsize = _notNone(capsize, 3)
barcolor = _notNone(barcolor, edgecolor)
boxcolor = _notNone(boxcolor, edgecolor)
# Draw boxes and bars
if boxes:
default = (-1, 1) if barstd else (25, 75)
boxrange = _notNone(boxrange, default)
err = _errorbar_values(y, iy, boxdata, boxrange, boxstd)
if boxmarker:
self.scatter(
*xy, marker='o', color=boxmarkercolor,
s=boxlw, zorder=5
)
self.errorbar(*xy, **{
axis + 'err': err, 'capsize': 0, 'zorder': boxzorder,
'color': boxcolor, 'linestyle': 'none', 'linewidth': boxlw
})
if bars: # now impossible to make thin bar width different from cap width!
default = (-3, 3) if barstd else (0, 100)
barrange = _notNone(barrange, default)
err = _errorbar_values(y, iy, bardata, barrange, barstd)
self.errorbar(*xy, **{
axis + 'err': err, 'capsize': capsize, 'zorder': barzorder,
'color': barcolor, 'linewidth': barlw, 'linestyle': 'none',
'markeredgecolor': barcolor, 'markeredgewidth': barlw
})
return obj
def plot_wrapper(self, func, *args, cmap=None, values=None, **kwargs):
"""
Calls `~proplot.axes.Axes.parametric` if the `cmap` argument was supplied,
otherwise calls `~matplotlib.axes.Axes.plot`. Wraps %(methods)s.
Parameters
----------
*args : (y,), (x, y), or (x, y, fmt)
Passed to `~matplotlib.axes.Axes.plot`.
cmap, values : optional
Passed to `~proplot.axes.Axes.parametric`.
**kwargs
`~matplotlib.lines.Line2D` properties.
"""
if len(args) > 3: # e.g. with fmt string
raise ValueError(f'Expected 1-3 positional args, got {len(args)}.')
if cmap is None:
lines = func(self, *args, values=values, **kwargs)
else:
lines = self.parametric(*args, cmap=cmap, values=values, **kwargs)
return lines
def scatter_wrapper(
self, func, *args,
s=None, size=None, markersize=None,
c=None, color=None, markercolor=None,
smin=None, smax=None,
cmap=None, cmap_kw=None, vmin=None, vmax=None, norm=None, norm_kw=None,
lw=None, linewidth=None, linewidths=None,
markeredgewidth=None, markeredgewidths=None,
edgecolor=None, edgecolors=None,
markeredgecolor=None, markeredgecolors=None,
**kwargs
):
"""
Adds keyword arguments to `~matplotlib.axes.Axes.scatter` that are more
consistent with the `~matplotlib.axes.Axes.plot` keyword arguments, and
interpret the `cmap` and `norm` keyword arguments with
`~proplot.styletools.Colormap` and `~proplot.styletools.Normalize` like
in `cmap_changer`. Wraps %(methods)s.
Parameters
----------
s, size, markersize : float or list of float, optional
Aliases for the marker size.
smin, smax : float, optional
Used to scale the `s` array. These are the minimum and maximum marker
sizes. Defaults are the minimum and maximum of the `s` array.
c, color, markercolor : color-spec or list thereof, or array, optional
Aliases for the marker fill color. If just an array of values, the
colors will be generated by passing the values through the `norm`
normalizer and drawing from the `cmap` colormap.
cmap : colormap-spec, optional
The colormap specifer, passed to the `~proplot.styletools.Colormap`
constructor.
cmap_kw : dict-like, optional
Passed to `~proplot.styletools.Colormap`.
vmin, vmax : float, optional
Used to generate a `norm` for scaling the `c` array. These are the
values corresponding to the leftmost and rightmost colors in the
colormap. Defaults are the minimum and maximum values of the `c` array.
norm : normalizer spec, optional
The colormap normalizer, passed to the `~proplot.styletools.Norm`
constructor.
norm_kw : dict, optional
Passed to `~proplot.styletools.Norm`.
lw, linewidth, linewidths, markeredgewidth, markeredgewidths : \
float or list thereof, optional
Aliases for the marker edge width.
edgecolors, markeredgecolor, markeredgecolors : \
color-spec or list thereof, optional
Aliases for the marker edge color.
**kwargs
Passed to `~matplotlib.axes.Axes.scatter`.
"""
# Manage input arguments
# NOTE: Parse 1D must come before this
nargs = len(args)
if len(args) > 4:
raise ValueError(f'Expected 1-4 positional args, got {nargs}.')
args = list(args)
if len(args) == 4:
c = args.pop(1)
if len(args) == 3:
s = args.pop(0)
# Format cmap and norm
cmap_kw = cmap_kw or {}
norm_kw = norm_kw or {}
if cmap is not None:
cmap = styletools.Colormap(cmap, **cmap_kw)
if norm is not None:
norm = styletools.Norm(norm, **norm_kw)
# Apply some aliases for keyword arguments
c = _notNone(
c, color, markercolor, None,
names=('c', 'color', 'markercolor')
)
s = _notNone(
s, size, markersize, None,
names=('s', 'size', 'markersize')
)
lw = _notNone(
lw, linewidth, linewidths, markeredgewidth, markeredgewidths, None,
names=(
'lw', 'linewidth', 'linewidths',
'markeredgewidth', 'markeredgewidths'
),
)
ec = _notNone(
edgecolor, edgecolors, markeredgecolor, markeredgecolors, None,
names=(
'edgecolor', 'edgecolors', 'markeredgecolor', 'markeredgecolors'
),
)
# Scale s array
if np.iterable(s):
smin_true, smax_true = min(s), max(s)
if smin is None:
smin = smin_true
if smax is None:
smax = smax_true
s = smin + (smax - smin) * (np.array(s) - smin_true) / \