/
wrappers.py
2796 lines (2649 loc) 路 125 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
"""
Imported by `~proplot.axes`, declares wrappers for various plotting functions.
"""
import sys
import numpy as np
import numpy.ma as ma
import functools
import warnings
from . import utils, styletools, axistools
from .utils import _notNone
import matplotlib.axes as maxes
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:
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_wrapper', 'colorbar_wrapper', 'cycle_wrapper',
'fill_between_wrapper', 'fill_betweenx_wrapper', 'hist_wrapper',
'legend_wrapper', 'plot_wrapper', 'scatter_wrapper',
'standardize_1d', 'standardize_2d', 'text_wrapper',
'violinplot_wrapper',
]
# Xarray and pandas integration
ndarray = np.ndarray
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
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
STYLE_ARGS_TRANSLATE = {
'contour': {'colors':'colors', 'linewidths':'linewidths', 'linestyles':'linestyles'},
'hexbin': {'colors':'edgecolors', 'linewidths':'linewidths'},
'tricontour': {'colors':'colors', 'linewidths':'linewidths', 'linestyles':'linestyles'},
'cmapline': {'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'},
}
#------------------------------------------------------------------------------#
# Alter default behavior
#------------------------------------------------------------------------------#
def default_latlon(self, func, *args, latlon=True, **kwargs):
"""
Wraps %(methods)s for `~proplot.axes.BasemapAxes`.
With the default `~mpl_toolkits.basemap` API, you need to pass
``latlon=True`` if your data coordinates are longitude and latitude
instead of map projection coordinates. Now, this is the default.
"""
return func(self, *args, latlon=latlon, **kwargs)
def default_transform(self, func, *args, transform=None, **kwargs):
"""
Wraps %(methods)s for `~proplot.axes.CartopyAxes`.
With the default `~cartopy.mpl.geoaxes.GeoAxes` API, you need to pass
``transform=cartopy.crs.PlateCarree()`` if your data coordinates are
longitude and latitude instead of map projection coordinates. Now,
this is the default.
"""
# 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):
"""
Wraps %(methods)s for `~proplot.axes.CartopyAxes` and fixes a
`~cartopy.mpl.geoaxes.GeoAxes.set_extent` bug associated with tight
bounding boxes.
With the default `~cartopy.mpl.geoaxes.GeoAxes` API, you need to pass
``crs=cartopy.crs.PlateCarree()`` if your data coordinates are
longitude and latitude instead of map projection coordinates. Now,
this is the default.
"""
# 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
#------------------------------------------------------------------------------#
# 1D dataset standardization and automatic formatting
#------------------------------------------------------------------------------#
def _to_iloc(data):
"""Get indexible attribute of array, so we can perform axis wise operations."""
return getattr(data, 'iloc', data)
def _to_array(data):
"""Convert to ndarray cleanly."""
data = getattr(data, 'values', data)
return np.array(data)
def _atleast_array(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 _auto_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 ('long_name', 'standard_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
label = getattr(data, 'name', '') or '' # DataFrame has no native name attribute but user can add one: https://github.com/pandas-dev/pandas/issues/447
return data, str(label).strip()
def standardize_1d(self, func, *args, **kwargs):
"""
Wraps %(methods)s, standardizes acceptable positional args and 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 args 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 = [_atleast_array(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, _ = _auto_label(y, axis=axis)
x = _atleast_array(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 = {}
xaxis = 'y' if (orientation == 'horizontal') else 'x'
yaxis = 'x' if xaxis == 'y' else 'y'
if _to_array(x).dtype == 'object':
xi = np.arange(len(x))
kw[xaxis + 'locator'] = mticker.FixedLocator(xi)
kw[xaxis + 'formatter'] = mticker.IndexFormatter(x)
kw[xaxis + '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 = _auto_label(y)
if label:
iaxis = xaxis if name in ('hist',) else yaxis # for histogram, this indicates x coordinate
kw[iaxis + 'label'] = label
# Xlabel
x, label = _auto_label(x)
if label and name not in ('hist',):
kw[xaxis + 'label'] = label
if name != 'scatter' and len(x) > 1 and xi is None and x[1] < x[0]:
kw[xaxis + 'reverse'] = True
# Appply
if kw:
self.format(**kw)
# Return result, maybe modify arguments
# WARNING: For some functions, e.g. boxplot and violinplot, we *require*
# cycle_wrapper is also applied so it can strip 'x' input.
if xi is not None:
x = xi
if name in ('boxplot','violinplot'):
ys = [_to_array(yi) for yi in ys] # store naked array
return func(self, x, *ys, *args, **kwargs)
#-----------------------------------------------------------------------------#
# 2D dataset standardization and automatic formatting
#-----------------------------------------------------------------------------#
# NOTE: Why are projection grid fixes in standardize_2d, and not in their
# own wrappers? Because grid fixes must come *after* automatic formatting,
# which means we'd have to apply these wrappers separately on CartesianAxes,
# BasemapAxes, CartopyAxes, and PolarAxes. Would be super redundant.
def _fix_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 _fix_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 standardize_2d(self, func, *args, order='C', globe=False, **kwargs):
"""
Wraps %(methods)s, standardizes acceptable positional args and optionally
modifies the x axis label, y axis label, title, and axis ticks if the
a `~xarray.DataArray`, `~pandas.DataFrame`, or `~pandas.Series` is passed.
Positional args 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.CartopyAxes` 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 = _atleast_array(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 = _atleast_array(x), _atleast_array(y)
if x.ndim != y.ndim:
raise ValueError(f'x coordinates are {x.ndim}-dimensional, 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, 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 _to_array(x).dtype == 'object':
xi = np.arange(len(x))
kw['xlocator'] = mticker.FixedLocator(xi)
kw['xformatter'] = mticker.IndexFormatter(x)
kw['xminorlocator'] = mticker.NullLocator()
if _to_array(y).dtype == 'object':
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 = _auto_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:
_, title = _auto_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 z.dtype != 'object' for z in (x,y)):
x = utils.edges(x)
y = utils.edges(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 Z centers {Z.shape} 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).')
# 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 and x.ndim == 1 and y.ndim == 1:
if all(z.ndim == 1 and z.size > 1 and z.dtype != 'object' for z in (x,y)):
x = (x[1:] + x[:-1])/2
y = (y[1:] + y[:-1])/2
elif Z.shape[1] != xlen or Z.shape[0] != ylen:
raise ValueError(f'Input shapes x {x.shape} and y {y.shape} must match Z centers {Z.shape} 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', '') == 'cartopy' and
isinstance(kwargs.get('transform', None), PlateCarree)):
iZs = []
x, y = _fix_latlon(x, y)
if not globe or x.ndim != 1 or y.ndim != 1:
iZs, Zs = Zs, []
for Z in Zs:
# Fix holes over poles by *interpolating* there
y, Z = _fix_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):
x = ma.concatenate((x, [x[0] + 360]))
Z = ma.concatenate((Z, Z[:,:1]), axis=1)
iZs.append(Z)
Zs = iZs
# Basemap projection axes
elif getattr(self, 'name', '') == 'basemap' and kwargs.get('latlon', None):
# Fix grid
iZs = []
x, y = _fix_latlon(x, y)
xmin, xmax = self.projection.lonmin, self.projection.lonmax
if x.ndim != 1 or y.ndim != 1:
iZs, Zs = Zs, [] # leave them alone
for Z in Zs:
# Special basemap fixes
# Roll, accounting for whether ends are identical
roll = -np.argmin(x)
if x[0] == x[-1]:
x = np.roll(x[:-1], roll)
x = ma.append(x, x[0] + 360)
else:
x = np.roll(x, roll)
Z = np.roll(Z, roll, axis=1)
# 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() # e.g. if 10 lons, xmax id is 9, we want to roll once
x = np.roll(x, roll)
Z = np.roll(Z, 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
Z = Z.copy()
if x.size-1 == Z.shape[1]: # test western/eastern grid cell edges
Z[:,(x[1:] < xmin) | (x[:-1] > xmax)] = np.nan
elif x.size == Z.shape[1]: # test the centers and pad by one for safety
where = np.where((x < xmin) | (x > xmax))[0]
Z[:,where[1:-1]] = np.nan
# Globe coverage fixes
if globe:
# Fix holes over poles by interpolating there (equivalent to
# simple mean of highest/lowest latitude points)
y, Z = _fix_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 x[0] == xmin and x.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 x.size-1 == Z.shape[1]: # just add grid cell
x = ma.append(xmin, x)
x[-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 x.size == Z.shape[1]:
xi = np.array([x[-1], x[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])
Z = ma.concatenate((Zq, Z, Zq), axis=1)
x = ma.concatenate(([xmin], x, [xmin + 360]))
else:
raise ValueError('Unexpected shape of longitude, latitude, data arrays.')
iZs.append(Z)
Zs = 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
return func(self, x, y, *Zs, **kwargs)
#------------------------------------------------------------------------------#
# Add errorbars during function call
#------------------------------------------------------------------------------#
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]}), 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):
"""
Wraps %(methods)s, adds support for drawing error bars. 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). Defaults
to ``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. Defaults to ``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. Defaults to ``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. Defaults to ``'k'``.
barlw, boxlw : float, optional
Line widths for the thin and thick error bars, in points. `barlw`
defaults to ``0.7`` and `boxlw` defaults to ``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``.
Defaults to ``True``.
boxmarkercolor : color-spec, optional
Color for the `boxmarker` marker. Defaults to ``'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:
bars = _notNone(bars, False) # e.g. if boxdata passed but bardata not passed, use 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, 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: # note it is 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
#-----------------------------------------------------------------------------#
# Method-specific wrappers
#-----------------------------------------------------------------------------#
def plot_wrapper(self, func, *args, cmap=None, values=None, **kwargs):
"""
Wraps %(methods)s, draws a "colormap line" if the ``cmap`` argument was passed.
"Colormap lines" change color as a function of the parametric coordinate
``values`` using the input colormap ``cmap``.
Parameters
----------
*args : (y,), (x,y), or (x,y,fmt)
Passed to `~matplotlib.axes.Axes.plot`.
cmap, values : optional
Passed to `~proplot.axes.Axes.cmapline`.
**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.cmapline(*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):
"""
Wraps `~matplotlib.axes.Axes.scatter`, adds optional keyword args
more consistent with the `~matplotlib.axes.Axes.plot` keywords.
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 to 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 to 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, N=None, **cmap_kw)
if norm is not None:
norm = styletools.Norm(norm, N=None, **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)/(smax_true - smin_true)
return func(self, *args, c=c, s=s,
cmap=cmap, vmin=vmin, vmax=vmax,
norm=norm, linewidths=lw, edgecolors=ec,
**kwargs)
def _fill_between_apply(self, func, *args,
negcolor='blue', poscolor='red', negpos=False,
**kwargs):
"""Parse args and call function."""
# Allow common keyword usage
x = 'y' if 'x' in func.__name__ else 'y'
y = 'x' if x == 'y' else 'y'
if x in kwargs:
args = (kwargs.pop(x), *args)
for y in (y + '1', y + '2'):
if y in kwargs:
args = (*args, kwargs.pop(y))
if len(args) == 1:
args = (np.arange(len(args[0])), *args)
if len(args) == 2:
if kwargs.get('stacked', False):
args = (*args, 0)
else:
args = (args[0], 0, args[1]) # default behavior
if len(args) != 3:
raise ValueError(f'Expected 2-3 positional args, got {len(args)}.')
if not negpos:
obj = func(self, *args, **kwargs)
return obj
# Get zero points
objs = []
kwargs.setdefault('interpolate', True)
y1, y2 = np.atleast_1d(args[-2]).squeeze(), np.atleast_1d(args[-1]).squeeze()
if y1.ndim > 1 or y2.ndim > 1:
raise ValueError(f'When "negpos" is True, y must be 1-dimensional.')
if kwargs.get('where', None) is not None:
raise ValueError('When "negpos" is True, you cannot set the "where" keyword.')
for i in range(2):
kw = {**kwargs}
kw.setdefault('color', negcolor if i == 0 else poscolor)
where = (y2 < y1) if i == 0 else (y2 >= y1)
obj = func(self, *args, where=where, **kw)
objs.append(obj)
return (*objs,)
def fill_between_wrapper(self, func, *args, **kwargs):
"""
Wraps `~matplotlib.axes.Axes.fill_between`, also accessible via the
`~proplot.axes.Axes.area` alias.
Parameters
----------
*args : (y1,), (x,y1), or (x,y1,y2)
The *x* and *y* coordinates. If `x` is not provided, it will be
inferred from `y1`. If `y1` and `y2` are provided, their shapes
must be identical, and we fill between respective columns of these
arrays.
stacked : bool, optional
If `y2` is ``None``, this indicates whether to "stack" successive
columns of the `y1` array.
negpos : bool, optional
Whether to shade where `y2` is greater than `y1` with the color `poscolor`,
and where `y1` is greater than `y2` with the color `negcolor`. For
example, to shade positive values red and negtive blue, use
``ax.fill_between(x, 0, y)``.
negcolor, poscolor : color-spec, optional
Colors to use for the negative and positive values. Ignored if `negpos`
is ``False``.
where : ndarray, optional
Boolean ndarray mask for points you want to shade. See
`this matplotlib example <https://matplotlib.org/3.1.0/gallery/pyplots/whats_new_98_4_fill_between.html#sphx-glr-gallery-pyplots-whats-new-98-4-fill-between-py>`__.
**kwargs
Passed to `~matplotlib.axes.Axes.fill_between`.
"""
return _fill_between_apply(self, func, *args, **kwargs)
def fill_betweenx_wrapper(self, func, *args, **kwargs):
"""Wraps %(methods)s, also accessible via the `~proplot.axes.Axes.areax`
alias. Usage is same as `fill_between_wrapper`."""
return _fill_between_apply(self, func, *args, **kwargs)
def hist_wrapper(self, func, x, bins=None, **kwargs):
"""Wraps %(methods)s, enforces that all arguments after `bins` are
keyword-only and sets the default patch linewidth to ``0``."""
kwargs.setdefault('linewidth', 0)
return func(self, x, bins=bins, **kwargs)
def barh_wrapper(self, func, y=None, width=None, height=0.8, left=None, **kwargs):
"""Wraps %(methods)s, usage is same as `bar`."""
kwargs.setdefault('orientation', 'horizontal')
if y is None and width is None:
raise ValueError(f'barh() requires at least 1 positional argument, got 0.')
return self.bar(x=left, height=height, width=width, bottom=y, **kwargs)
def bar_wrapper(self, func, x=None, height=None, width=0.8, bottom=None, *, left=None,
vert=None, orientation='vertical', stacked=False,
lw=None, linewidth=0.7, edgecolor='k',
**kwargs):
"""
Wraps %(methods)s, permits bar stacking and bar grouping.
Parameters
----------
x, height, width, bottom : float or list of float, optional
The dimensions of the bars. If the *x* coordinates are not provided,
they are set to ``np.arange(0, len(height))``.
orientation : {'vertical', 'horizontal'}, optional
The orientation of the bars.
vert : bool, optional
Alternative to the `orientation` keyword arg. If ``False``, horizontal
bars are drawn. This is for consistency with `~matplotlib.axes.Axes.boxplot`
and `~matplotlib.axes.Axes.violinplot`.
stacked : bool, optional
Whether to stack columns of input data, or plot the bars side-by-side.
edgecolor : color-spec, optional
The edge color for the bar patches.
lw, linewidth : float, optional
The edge width for the bar patches.
"""
# Barh converts y-->bottom, left-->x, width-->height, height-->width.
# Convert back to (x, bottom, width, height) so we can pass stuff through
# cycle_wrapper.
# NOTE: You *must* do juggling of barh keyword order --> bar keyword order
# --> barh keyword order, because horizontal hist passes arguments to bar
# directly and will not use a 'barh' method with overridden argument order!
if vert is not None:
orientation = ('vertical' if vert else 'horizontal')
if orientation == 'horizontal':
x, bottom = bottom, x
width, height = height, width
# Parse args
# TODO: Stacked feature is implemented in `cycle_wrapper`, but makes more
# sense do document here; figure out way to move it here?
if left is not None:
warnings.warn(f'The "left" keyword with bar() is deprecated. Use "x" instead.')
x = left
if x is None and height is None:
raise ValueError(f'bar() requires at least 1 positional argument, got 0.')
elif height is None:
x, height = None, x
# Call func
# TODO: This *must* also be wrapped by cycle_wrapper, which ultimately
# permutes back the x/bottom args for horizontal bars! Need to clean this up.
lw = _notNone(lw, linewidth, None, names=('lw', 'linewidth'))
return func(self, x, height, width=width, bottom=bottom,
linewidth=lw, edgecolor=edgecolor,
stacked=stacked, orientation=orientation,
**kwargs)
def boxplot_wrapper(self, func, *args,
color='k', fill=True, fillcolor=None, fillalpha=0.7,
lw=None, linewidth=0.7, orientation=None,
marker=None, markersize=None,
boxcolor=None, boxlw=None,
capcolor=None, caplw=None,
meancolor=None, meanlw=None,
mediancolor=None, medianlw=None,
whiskercolor=None, whiskerlw=None,
fliercolor=None, flierlw=None,
**kwargs):
"""
Wraps %(methods)s, adds convenient keyword args.
Fills the objects with a cycle color by default.
Parameters
----------
*args : 1D or 2D ndarray
The data array.
color : color-spec, optional
The color of all objects.