-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathplotters.py
More file actions
6600 lines (5418 loc) · 195 KB
/
Copy pathplotters.py
File metadata and controls
6600 lines (5418 loc) · 195 KB
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
"""Plotters and formatoptions for the psy-simple plugin."""
# SPDX-FileCopyrightText: 2021-2024 Helmholtz-Zentrum Hereon
# SPDX-FileCopyrightText: 2020-2021 Helmholtz-Zentrum Geesthacht
# SPDX-FileCopyrightText: 2016-2024 University of Lausanne
#
# SPDX-License-Identifier: LGPL-3.0-only
import re
import weakref
from abc import abstractmethod, abstractproperty
from functools import partial
from itertools import chain, cycle, islice, repeat, starmap
from warnings import warn
import matplotlib as mpl
import numpy as np
import six
import xarray as xr
from matplotlib.dates import AutoDateFormatter, DateFormatter
from matplotlib.ticker import FixedFormatter, FixedLocator, FormatStrFormatter
from pandas import (
DatetimeIndex,
MultiIndex,
date_range,
to_datetime,
to_timedelta,
)
from pandas.tseries import offsets
from psyplot.data import (
CFDecoder,
InteractiveList,
_infer_interval_breaks,
isstring,
)
from psyplot.docstring import dedent, docstrings
from psyplot.plotter import (
BEFOREPLOTTING,
END,
START,
DictFormatoption,
Formatoption,
Plotter,
)
from psyplot.utils import is_iterable
from psyplot.warning import PsyPlotRuntimeWarning
from psy_simple.base import (
BasePlotter,
Mask,
MaskBetween,
MaskGeq,
MaskGreater,
MaskLeq,
MaskLess,
TextBase,
label_props,
label_size,
label_weight,
)
from psy_simple.colors import get_cmap
from psy_simple.plugin import safe_list as slist
from psy_simple.plugin import validate_color, validate_float
def _get_index_vals(index):
if isinstance(index, MultiIndex) and len(index.names) == 1:
return index.get_level_values(0).values
else:
return index.values
mpl_version = float(".".join(mpl.__version__.split(".")[:2]))
def round_to_05(n, exp=None, mode="s"):
"""
Round to the next 0.5-value.
This function applies the round function `func` to round `n` to the
next 0.5-value with respect to its exponent with base 10 (i.e.
1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect
to the given exponent in `exp`.
Parameters
----------
n: numpy.ndarray
number to round
exp: int or numpy.ndarray
Exponent for rounding. If None, it will be computed from `n` to be the
exponents for base 10.
mode: {'s', 'l'}
rounding mode. If 's', it will be rounded to value whose absolute
value is below `n`, if 'l' it will rounded to the value whose absolute
value is above `n`.
Returns
-------
numpy.ndarray
rounded `n`
Examples
--------
The effects of the different parameters are show in the example below::
>>> from psyplot.plotter.simple import round_to_05
>>> a = [-100.3, 40.6, 8.7, -0.00023]
>>>round_to_05(a, mode='s')
array([ -1.00000000e+02, 4.00000000e+01, 8.50000000e+00,
-2.00000000e-04])
>>> round_to_05(a, mode='l')
array([ -1.50000000e+02, 4.50000000e+01, 9.00000000e+00,
-2.50000000e-04])
"""
n = np.asarray(n)
if exp is None:
exp = np.floor(np.log10(np.abs(n))) # exponent for base 10
ntmp = np.abs(n) / 10.0**exp # mantissa for base 10
if mode == "s":
n1 = ntmp
s = 1.0
n2 = nret = np.floor(ntmp)
else:
n1 = nret = np.ceil(ntmp)
s = -1.0
n2 = ntmp
return np.where(
n1 - n2 > 0.5,
np.sign(n) * (nret + s * 0.5) * 10.0**exp,
np.sign(n) * nret * 10.0**exp,
)
def convert_radian(coord, *variables):
"""Convert the given coordinate from radian to degree
Parameters
----------
coord: xr.Variable
The variable to transform
``*variables``
The variables that are on the same unit.
Returns
-------
xr.Variable
The transformed variable if one of the given `variables` has units in
radian"""
warn(
"The psy_simple.plotters.convert_radian method has been deprecated."
"Please use the `plotter.convert_coordinate` instead.",
DeprecationWarning,
)
if any(v.attrs.get("units", "").startswith("radian") for v in variables):
return coord * 180.0 / np.pi
return coord
class AlternativeXCoord(Formatoption):
"""
Use an alternative variable as x-coordinate
This formatoption let's you specify another variable in the base dataset
of the data array in case you want to use this as the x-coordinate instead
of the raw data
Possible types
--------------
None
Use the default
str
The name of the variable to use in the base dataset
xarray.DataArray
An alternative variable with the same shape as the displayed array
Examples
--------
To see the difference, we create a simple test dataset::
>>> import xarray as xr
>>> import numpy as np
>>> import psyplot.project as psy
>>> ds = xr.Dataset({
... 'temp': xr.Variable(('time', ), np.arange(5)),
... 'std': xr.Variable(('time', ), np.arange(5, 10))})
>>> ds
<xarray.Dataset>
Dimensions: (time: 5)
Coordinates:
* time (time) int64 0 1 2 3 4
Data variables:
temp (time) int64 0 1 2 3 4
std (time) int64 5 6 7 8 9
If we create a plot with it, we get the ``'time'`` dimension on the
x-axis::
>>> plotter = psy.plot.lineplot(ds, name=['temp']).plotters[0]
>>> plotter.plot_data[0].dims
('time',)
If we however set the ``'coord'`` keyword, we get::
>>> plotter = psy.plot.lineplot(
... ds, name=['temp'], coord='std').plotters[0]
>>> plotter.plot_data[0].dims
('std',)
and ``'std'`` is plotted on the x-axis.
"""
name = "Alternative X-Variable"
group = "data"
priority = START
data_dependent = True
#: Bool. If True, this Formatoption directly uses the raw_data, otherwise
#: use the normal data
use_raw_data = True
@property
def data_iterator(self):
return self.iter_raw_data if self.use_raw_data else self.iter_data
def update(self, value):
if value is not None:
for i, da in enumerate(self.data_iterator):
self.set_data(self.replace_coord(i), i)
def diff(self, value):
try:
return not (
(np.shape(value) == np.shape(self.value))
and np.all(value == self.value)
)
except TypeError:
return True
def replace_coord(self, i):
"""Replace the coordinate for the data array at the given position
Parameters
----------
i: int
The number of the data array in the raw data (if the raw data is
not an interactive list, use 0)
Returns
xarray.DataArray
The data array with the replaced coordinate"""
da = next(islice(self.data_iterator, i, i + 1))
name, coord = self.get_alternative_coord(da, i)
other_coords = {
key: da.coords[key] for key in set(da.coords).difference(da.dims)
}
ret = (
da.rename({da.dims[-1]: name})
.assign_coords(**{name: coord})
.assign_coords(**other_coords)
)
return ret
def get_alternative_coord(self, da, i):
if isinstance(self.value, xr.DataArray):
return self.value.name, self.value.variable
alternative_name = next(islice(cycle(slist(self.value)), i, i + 1))
coord_da = InteractiveList.from_dataset(
da.psy.base, name=alternative_name, dims=da.psy.idims
)[0]
coord = xr.Variable((coord_da.name,), coord_da, coord_da.attrs)
return coord_da.name, coord
class AlternativeXCoordPost(AlternativeXCoord):
# The same as the :class:`AlternativeXCoord, but it uses the
# :attr:`psyplot.plotter.Formatoption.data` attribute as a src, not the
# :attr:`psyplot.plotter.Formatoption.raw_data`
__doc__ = AlternativeXCoord.__doc__
use_raw_data = False
class Grid(Formatoption):
"""
Display the grid
Show the grid on the plot with the specified color.
Possible types
--------------
None
If the grid is currently shown, it will not be displayed any longer. If
the grid is not shown, it will be drawn
bool
If True, the grid is displayed with the automatic settings (usually
black)
string, tuple.
Defines the color of the grid.
Notes
-----
%(colors)s"""
group = "axes"
name = "Grid lines"
def update(self, value):
if self.plotter._initialized and mpl_version == 3.3:
warn("Updating grids is known to malfunction for matplotlib 3.3!")
try:
value = validate_color(value)
self.ax.grid(color=value)
except (ValueError, TypeError, AttributeError):
self.ax.grid(value)
class AxisColor(DictFormatoption):
"""
Color the x- and y-axes
This formatoption colors the left, right, bottom and top axis bar.
Possible types
--------------
dict
Keys may be one of {'right', 'left', 'bottom', 'top'}, the values can
be any valid color or None.
Notes
-----
%(colors)s"""
group = "axes"
name = "Color of x- and y-axes"
@property
def value2pickle(self):
"""Return the current axis colors"""
return {key: s.get_edgecolor() for key, s in self.ax.spines.items()}
def initialize_plot(self, value):
positions = ["right", "left", "bottom", "top"]
#: :class:`dict` storing the default linewidths
self.default_lw = dict(
zip(
positions,
map(
lambda pos: self.ax.spines[pos].get_linewidth(), positions
),
)
)
self.update(value)
def update(self, value):
for pos, color in six.iteritems(value):
spine = self.ax.spines[pos]
spine.set_color(color)
if color is not None and spine.get_linewidth() == 0.0:
spine.set_linewidth(1.0)
elif color is None:
spine.set_color(mpl.rcParams["axes.edgecolor"])
spine.set_linewidth(self.default_lw[pos])
class TicksManagerBase(Formatoption):
"""
Abstract base class for formatoptions handling ticks"""
@abstractmethod
def update_axis(self, val):
pass
@docstrings.get_sections(base="TicksManager")
class TicksManager(TicksManagerBase, DictFormatoption):
"""
Abstract base class for ticks formatoptions controlling major and minor
ticks
This formatoption simply serves as a base that allows the simultaneous
managment of major and minor ticks
Possible types
--------------
dict
A dictionary with the keys ``'minor'`` and (or) ``'major'`` to specify
which ticks are managed. If the given value is not a dictionary with
those keys, it is put into a dictionary with the key determined by the
rcParams ``'ticks.which'`` key (usually ``'major'``).
The values in the dictionary can be one types below."""
group = "ticks"
def update(self, value):
for which, val in six.iteritems(value):
self.which = which
self.update_axis(val)
@docstrings.get_sections(base="DataTicksCalculator")
class DataTicksCalculator(Formatoption):
"""
Abstract base formatoption to calculate ticks and bounds from the data
Possible types
--------------
numeric array
specifies the ticks manually
str or list [str, ...]
A list of the below mentioned values of the mapping like
``[method, N, percmin, percmax, vmin, vmax]``, where only the first
one is absolutely necessary
dict
Automatically determine the ticks corresponding to the data. The
mapping can have the following keys, but only `method` is not optional.
N
An integer describing the number of boundaries (or ticks per
power of ten, see `log` and `symlog` above)
percmin
The percentile to use for the minimum (by default, 0, i.e. the
minimum of the array)
percmax
The percentile to use for the maximum (by default, 100, i.e. the
maximum of the array)
vmin
The minimum to use (in which case it is not calculated from the
specified `method`)
vmax
The maximum to use (in which case it is not calculated from the
specified `method`)
method
A string that defines how minimum and maximum shall be set. This
argument is **not optional** and can be one of the following:
data
plot the ticks exactly where the data is.
mid
plot the ticks in the middle of the data.
rounded
Sets the minimum and maximum of the ticks to the rounded data
minimum or maximum. Ticks are rounded to the next 0.5 value
with to the difference between data max- and minimum. The
minimal tick will always be lower or equal than the data
minimum, the maximal tick will always be higher or equal than
the data maximum.
roundedsym
Same as `rounded` above but the ticks are chose such that they
are symmetric around zero
minmax
Uses the minimum as minimal tick and maximum as maximal tick
sym
Same as minmax but symmetric around zero
log
Use logarithmic bounds. In this case, the given number `N`
determines the number of bounds per power of tenth (i.e.
``N == 2`` results in something like ``1.0, 5.0, 10.0, 50.0``,
etc., If this second number is None, then it will be chosen
such that we have around 11 boundaries but at least one per
power of ten.
symlog
The same as ``log`` but symmetric around 0. If the number `N`
is None, then we have around 12 boundaries but at least one
per power of ten"""
data_dependent = True
@property
def full_array(self):
"""The full array of this and the shared data"""
return np.concatenate(
[self.array] + [fmto.array for fmto in self.shared]
)
@property
def array(self):
"""The numpy array of the data"""
data = self.data
if not hasattr(data, "notnull"):
data = data.to_series()
mask = np.asarray(data.notnull())
return data.values[mask]
def _data_ticks(self, step=None, *args, **kwargs):
step = step or 1
"""Array of ticks that match exactly the data"""
return np.unique(self.array)[::step]
def _mid_data_ticks(self, step=None, *args, **kwargs):
step = step or 1
"""Array of ticks in the middle between the data points"""
arr = np.unique(self.array)
return ((arr[:-1] + arr[1:]) / 2.0)[::step]
def _collect_array(self, percmin=None, percmax=None):
"""Collect the data from the shared formatoptions (if necessary)."""
def nanmin(arr):
try:
return np.nanmin(arr)
except TypeError:
return arr.min()
def nanmax(arr):
try:
return np.nanmax(arr)
except TypeError:
return arr.max()
def minmax(arr):
return [nanmin(arr), nanmax(arr)]
def shared_arrays():
for fmto in self.shared:
fmto._lock_children()
# do not lock the fmto itself, because this breaks the plotter
# update procedure. But make sure, that the dependencies are
# locked
arr = fmto.array
yield arr
# release the locks
fmto._release_children()
if not self.shared:
arr = self.array
else:
# np.concatenate all arrays if any of the percentiles are required
if percmin is not None or percmax is not None:
arr = np.concatenate(
tuple(chain([self.array], shared_arrays()))
)
# np.concatenate only min and max-values instead of the full arrays
else:
arr = np.concatenate(
tuple(map(minmax, chain([self.array], shared_arrays())))
)
return arr
def _calc_vmin_vmax(
self, percmin=None, percmax=None, vmin=None, vmax=None
):
def nanmin(arr):
try:
return np.nanmin(arr)
except TypeError:
return arr.min()
def nanmax(arr):
try:
return np.nanmax(arr)
except TypeError:
return arr.max()
if vmin is not None and vmax is not None:
return vmin, vmax
percentiles = []
arr = self._collect_array(percmin, percmax)
try:
if vmin is not None:
pass
elif not percmin:
vmin = nanmin(arr)
else:
percentiles.append(percmin)
if vmax is not None:
pass
elif percmax is None or percmax == 100:
vmax = nanmax(arr)
else:
percentiles.append(percmax)
except ValueError:
self.logger.warn(
"Cannot calculate minimum and maximum of the data!",
exc_info=True,
)
return 0, 1
if percentiles:
percentiles = iter(np.percentile(arr, percentiles))
if percmin:
vmin = next(percentiles)
if percmax and percmax < 100:
vmax = next(percentiles)
return vmin, vmax
@staticmethod
def _round_min_max(vmin, vmax):
if vmin == vmax:
return vmin, vmax
exp = np.floor(np.log10(abs(vmax - vmin)))
larger = round_to_05([vmin, vmax], exp, mode="l")
smaller = round_to_05([vmin, vmax], exp, mode="s")
return min([larger[0], smaller[0]]), max([larger[1], smaller[1]])
def _rounded_ticks(self, N=None, *args, **kwargs):
N = N or 11
vmin, vmax = self._round_min_max(
*self._calc_vmin_vmax(*args, **kwargs)
)
return np.linspace(vmin, vmax, N, endpoint=True)
def _log_bounds(self, expmin, expmax, N):
bounds = []
for i in range(int(expmax - expmin)):
new_vals = np.linspace(
1 * 10 ** (expmin + i), 9 * 10 ** (expmin + i), N + 1
)[:-1]
bounds.extend(new_vals)
return bounds
def _log_ticks(self, symmetric=False, N=None, *args, **kwargs):
vmin, vmax = self._calc_vmin_vmax(*args, **kwargs)
larger = round_to_05([vmin, vmax], mode="l")
smaller = round_to_05([vmin, vmax], mode="s")
vmin, vmax = min([larger[0], smaller[0]]), max([larger[1], smaller[1]])
if symmetric and np.sign(vmin) == np.sign(vmax):
if vmin < 0: # make vmax positive
vmax = -vmax
else: # make vmin negative
vmin = -vmin
elif symmetric:
vmax = np.max([-vmin, vmax])
vmin = -vmax
if vmin == vmax:
return vmin, vmax
signs = np.sign([vmin, vmax])
crossing0 = vmin != 0 and vmax != 0 and signs[0] != signs[1]
if not crossing0:
vmin, vmax = np.sort(np.abs([vmin, vmax]))
vmin0 = vmax
vmax0 = vmin
expmin, expmax = np.floor(np.log10(np.abs([vmin, vmax])))
dexp = int(expmax - expmin)
expmax0 = np.inf
else: # vmin < 0, vmax > 0
arr = self._collect_array()
less0 = arr < 0
greater0 = arr > 0
if not less0.size:
vmin0 = round_to_05(arr[arr > 0].min(), mode="s")
vmax0 = -vmin0
elif not greater0.size:
vmax0 = round_to_05(arr[arr < 0].max(), mode="l")
vmin0 = -vmax0
else:
vmin0 = round_to_05(arr[arr > 0].min(), mode="s")
vmax0 = round_to_05(arr[arr < 0].max(), mode="l")
if symmetric:
vmin0 = min(-vmax0, vmin0)
vmax0 = -vmin0
expmin, expmax0 = np.floor(np.log10(np.abs([vmax0, vmin])))
expmin0, expmax = np.floor(np.log10(np.abs([vmin0, vmax])))
dexp_neg = int(expmax0 - expmin)
dexp_pos = int(expmax - expmin0)
dexp = int(dexp_neg + dexp_pos)
if dexp == 0 or (dexp == 1 and vmax == 1 * 10**expmax):
# effectively only one factor of 10 (e.g. vmin = 1, vmax = 10)
N = N or (11 if not symmetric else 12)
return np.linspace(vmin, vmax, N, endpoint=True)
else:
if N is None:
# we go close to 11 bounds in total
N = int(max(np.floor((11 if not symmetric else 12) / dexp), 1))
if not crossing0:
bounds = self._log_bounds(expmin, expmax, N)
bounds += [1 * 10**expmax]
if signs[0] == -1 and signs[1] == -1:
bounds = -np.array(bounds)
else:
bounds_neg = -np.array(self._log_bounds(expmin, expmax0, N))
bounds_pos = self._log_bounds(expmin0, expmax, N)
bounds = np.unique(
np.r_[
bounds_neg,
bounds_pos,
-1 * 10**expmin,
-1 * 10**expmax0,
1 * 10**expmin0,
1 * 10**expmax,
]
)
bounds = bounds[(bounds <= vmax0) | (bounds >= vmin0)]
return np.unique(bounds)
def _roundedsym_ticks(self, N=None, *args, **kwargs):
N = N or 10
vmax = max(
map(
abs,
self._round_min_max(*self._calc_vmin_vmax(*args, **kwargs)),
)
)
vmin = -vmax
return np.linspace(vmin, vmax, N, endpoint=True)
def _data_minmax_ticks(self, N=None, *args, **kwargs):
N = N or 11
vmin, vmax = self._calc_vmin_vmax(*args, **kwargs)
return np.linspace(vmin, vmax, N, endpoint=True)
def _data_symminmax_ticks(self, N=None, *args, **kwargs):
N = N or 10
vmax = max(map(abs, self._calc_vmin_vmax(*args, **kwargs)))
vmin = -vmax
return np.linspace(vmin, vmax, N, endpoint=True)
def __init__(self, *args, **kwargs):
super(DataTicksCalculator, self).__init__(*args, **kwargs)
self.calc_funcs = {
"data": self._data_ticks,
"mid": self._mid_data_ticks,
"rounded": self._rounded_ticks,
"roundedsym": self._roundedsym_ticks,
"minmax": self._data_minmax_ticks,
"sym": self._data_symminmax_ticks,
"log": partial(self._log_ticks, False),
"symlog": partial(self._log_ticks, True),
}
@docstrings.get_sections(base="TicksBase")
class TicksBase(TicksManagerBase, DataTicksCalculator):
"""
Abstract base class for calculating ticks
Possible types
--------------
None
use the default ticks
int
for an integer *i*, only every *i-th* tick of the default ticks are
used"""
dependencies = ["transpose", "plot"]
group = "ticks"
@abstractproperty
def axis(self):
pass
def __init__(self, *args, **kwargs):
super(TicksBase, self).__init__(*args, **kwargs)
self.default_locators = {}
def initialize_plot(self, value):
self.set_default_locators()
self.update(value)
def update_axis(self, value):
which = self.which
if value is None:
self.set_locator(self.default_locators[which])
elif isinstance(value, int):
return self._reduce_ticks(value)
elif len(value) and isinstance(value[0], six.string_types):
return self.set_ticks(self.calc_funcs[value[0]](*value[1:]))
elif isinstance(value, tuple):
steps = 11 if len(value) == 2 else value[3]
self.set_ticks(
np.linspace(value[0], value[1], steps, endpoint=True)
)
else:
self.set_ticks(value)
def set_ticks(self, value):
self.axis.set_ticks(value, minor=self.which == "minor")
def get_locator(self):
return getattr(self.axis, "get_%s_locator" % self.which)()
def set_locator(self, locator):
"""Sets the locator corresponding of the axis
Parameters
----------
locator: matplotlib.ticker.Locator
The locator to set
which: {None, 'minor', 'major'}
Specify which locator shall be set. If None, it will be taken from
the :attr:`which` attribute"""
getattr(self.axis, "set_%s_locator" % self.which)(locator)
def set_default_locators(self, which=None):
"""Sets the default locator that is used for updating to None or int
Parameters
----------
which: {None, 'minor', 'major'}
Specify which locator shall be set"""
if which is None or which == "minor":
self.default_locators["minor"] = self.axis.get_minor_locator()
if which is None or which == "major":
self.default_locators["major"] = self.axis.get_major_locator()
def _reduce_ticks(self, i):
loc = self.default_locators[self.which]
self.set_locator(FixedLocator(loc()[::i]))
@docstrings.get_sections(base="DtTicksBase")
class DtTicksBase(TicksBase, TicksManager):
"""
Abstract base class for x- and y-tick formatoptions
Possible types
--------------
%(TicksManager.possible_types)s
%(TicksBase.possible_types)s
%(DataTicksCalculator.possible_types)s
hour
draw ticks every hour
day
draw ticks every day
week
draw ticks every week
month, monthend, monthbegin
draw ticks in the middle, at the end or at the beginning of each
month
year, yearend, yearbegin
draw ticks in the middle, at the end or at the beginning of each
year
For data, mid, hour, day, week, month, etc., the optional second value
can be an integer i determining that every i-th data point shall be
used (by default, it is set to 1). For rounded, roundedsym, minmax and
sym, the second value determines the total number of ticks (defaults to
11)."""
def __init__(self, *args, **kwargs):
super(DtTicksBase, self).__init__(*args, **kwargs)
self.calc_funcs.update(
{
"hour": self._frequent_ticks("H"),
"day": self._frequent_ticks("D"),
"week": self._frequent_ticks(offsets.Week()),
"month": self._mid_dt_ticks("M"),
"monthend": self._frequent_ticks(
offsets.MonthEnd(), onset=offsets.MonthBegin()
),
"monthbegin": self._frequent_ticks(
offsets.MonthBegin(),
onset=offsets.MonthBegin(),
offset=offsets.MonthBegin(),
),
"year": self._mid_dt_ticks(offsets.YearBegin()),
"yearend": self._frequent_ticks(
offsets.YearEnd(), onset=offsets.YearBegin()
),
"yearbegin": self._frequent_ticks(
offsets.YearBegin(),
onset=offsets.YearBegin(),
offset=offsets.YearBegin(),
),
}
)
def update(self, value):
value = value or {"minor": None, "major": None}
super(DtTicksBase, self).update(value)
@property
def dtdata(self):
"""The np.unique :attr:`data` as datetime objects"""
data = self.data
# do nothing if the data is a pandas.Index without time informations
# or not a pandas.Index
if not isinstance(data, DatetimeIndex):
warn(
"[%s] - Could not convert time informations for %s ticks "
"with object %r." % (self.logger.name, self.key, type(data))
)
return None
else:
return data
def _frequent_ticks(self, freq, onset=None, offset=None):
def func(N=None, *args, **kwargs):
step = N or 1
data = self.dtdata
if data is None:
return
mindata = data.min() if onset is None else data.min() - onset
maxdata = data.max() if offset is None else data.max() + offset
return date_range(mindata, maxdata, freq=freq)[
::step
].to_pydatetime()
return func
def _mid_dt_ticks(self, freq):
def func(N=None, *args, **kwargs):
step = N or 1
data = self.dtdata
if data is None:
return
data = date_range(
data.min(), data.max(), freq=freq
).to_pydatetime()
data[:-1] += (data[1:] - data[:-1]) / 2
return data[:-1:step]
return func
class XTicks(DtTicksBase):
"""
Modify the x-axis ticks
Possible types
--------------
%(DtTicksBase.possible_types)s
Examples
--------
Plot 11 ticks over the whole data range::
>>> plotter.update(xticks='rounded')
Plot 7 ticks over the whole data range where the maximal and minimal
tick matches the data maximum and minimum::
>>> plotter.update(xticks=['minmax', 7])
Plot ticks every year and minor ticks every month::
>>> plotter.update(xticks={'major': 'year', 'minor': 'month'})
See Also
--------
xticklabels, ticksize, tickweight, xtickprops, yticks
"""
children = TicksBase.children + ["yticks"]
dependencies = DtTicksBase.dependencies + ["plot"]
name = "Location of the x-Axis ticks"
@property
def axis(self):
return self.ax.xaxis
@property
def data(self):
def select_array(arr):
if arr.ndim > 1:
return arr.psy[0]
return arr
data = getattr(self.plot, "plotted_data", super(XTicks, self).data)
if not len(data):
data = super(XTicks, self).data
if isinstance(data, InteractiveList):
df = InteractiveList(map(select_array, data)).to_dataframe()
else:
df = data.to_series()
if self.transpose.value:
return df
else:
if isinstance(df.index, MultiIndex) and len(df.index.names) == 1:
return df.index.get_level_values(0)
else:
return df.index
def initialize_plot(self, *args, **kwargs):
super(XTicks, self).initialize_plot(*args, **kwargs)
self.transpose.swap_funcs["ticks"] = self._swap_ticks
def _swap_ticks(self):
xticks = self
yticks = self.yticks
old_xlocators = xticks.default_locators
xticks.default_locators = yticks.default_locators
yticks.default_locators = old_xlocators
old_xval = self.value
with self.plotter.no_validation: