/
converter.py
2361 lines (2104 loc) · 99.4 KB
/
converter.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
import difflib
from functools import partial
import param
import holoviews as hv
import pandas as pd
import numpy as np
import colorcet as cc
from bokeh.models import HoverTool
from holoviews.core.dimension import Dimension
from holoviews.core.spaces import DynamicMap, HoloMap, Callable
from holoviews.core.overlay import NdOverlay
from holoviews.core.options import Store, Cycle, Palette
from holoviews.core.layout import NdLayout
from holoviews.core.util import max_range
from holoviews.element import (
Curve, Scatter, Area, Bars, BoxWhisker, Dataset, Distribution,
Table, HeatMap, Image, HexTiles, QuadMesh, Bivariate, Histogram,
Violin, Contours, Polygons, Points, Path, Labels, RGB, ErrorBars,
VectorField, Rectangles, Segments
)
from holoviews.plotting.bokeh import OverlayPlot, colormap_generator
from holoviews.plotting.util import process_cmap
from holoviews.operation import histogram, apply_when
from holoviews.streams import Buffer, Pipe
from holoviews.util.transform import dim
from packaging.version import Version
from pandas import DatetimeIndex, MultiIndex
from .backend_transforms import _transfer_opts_cur_backend
from .util import (
filter_opts, hv_version, is_tabular, is_series, is_dask, is_intake, is_cudf,
is_streamz, is_ibis, is_xarray, is_xarray_dataarray, process_crs,
process_intake, process_xarray, check_library, is_geodataframe,
process_derived_datetime_xarray, process_derived_datetime_pandas,
_convert_col_names_to_str,
)
from .utilities import hvplot_extension
renderer = hv.renderer('bokeh')
class StreamingCallable(Callable):
"""
StreamingCallable is a DynamicMap callback wrapper which keeps
a handle to start and stop a dynamic stream.
"""
periodic = param.Parameter()
def clone(self, callable=None, **overrides):
"""
Allows making a copy of the Callable optionally overriding
the callable and other parameters.
"""
old = {k: v for k, v in self.param.get_param_values()
if k not in ['callable', 'name']}
params = dict(old, **overrides)
callable = self.callable if callable is None else callable
return self.__class__(callable, **params)
def start(self):
"""
Start the periodic callback
"""
if not self.periodic._running:
self.periodic.start()
else:
raise Exception('PeriodicCallback already running.')
def stop(self):
"""
Stop the periodic callback
"""
if self.periodic._running:
self.periodic.stop()
else:
raise Exception('PeriodicCallback not running.')
class HoloViewsConverter:
"""
Generic options
---------------
autorange (default=None): Literal['x', 'y'] | None
Whether to enable auto-ranging along the x- or y-axis when
zooming. Requires HoloViews >= 1.16.
clim: tuple
Lower and upper bound of the color scale
cnorm (default='linear'): str
Color scaling which must be one of 'linear', 'log' or 'eq_hist'
colorbar (default=False): boolean
Enables a colorbar
fontscale: number
Scales the size of all fonts by the same amount, e.g. fontscale=1.5
enlarges all fonts (title, xticks, labels etc.) by 50%
fontsize: number or dict
Set title, label and legend text to the same fontsize. Finer control
by using a dict: {'title': '15pt', 'ylabel': '5px', 'ticks': 20}
flip_xaxis/flip_yaxis: boolean
Whether to flip the axis left to right or up and down respectively
grid (default=False): boolean
Whether to show a grid
hover : boolean
Whether to show hover tooltips, default is True unless datashade is
True in which case hover is False by default
hover_cols (default=[]): list or str
Additional columns to add to the hover tool or 'all' which will
includes all columns (including indexes if use_index is True).
invert (default=False): boolean
Swaps x- and y-axis
frame_width/frame_height: int
The width and height of the data area of the plot
legend (default=True): boolean or str
Whether to show a legend, or a legend position
('top', 'bottom', 'left', 'right')
logx/logy (default=False): boolean
Enables logarithmic x- and y-axis respectively
logz (default=False): boolean
Enables logarithmic colormapping
loglog (default=False): boolean
Enables logarithmic x- and y-axis
max_width/max_height: int
The maximum width and height of the plot for responsive modes
min_width/min_height: int
The minimum width and height of the plot for responsive modes
padding: number or tuple
Fraction by which to increase auto-ranged extents to make
datapoints more visible around borders. Supports tuples to
specify different amount of padding for x- and y-axis and
tuples of tuples to specify different amounts of padding for
upper and lower bounds.
rescale_discrete_levels (default=True): boolean
If `cnorm='eq_hist'` and there are only a few discrete values,
then `rescale_discrete_levels=True` (the default) decreases
the lower limit of the autoranged span so that the values are
rendering towards the (more visible) top of the `cmap` range,
thus avoiding washout of the lower values. Has no effect if
`cnorm!=`eq_hist`.
responsive: boolean
Whether the plot should responsively resize depending on the
size of the browser. Responsive mode will only work if at
least one dimension of the plot is left undefined, e.g. when
width and height or width and aspect are set the plot is set
to a fixed size, ignoring any responsive option.
rot: number
Rotates the axis ticks along the x-axis by the specified
number of degrees.
shared_axes (default=True): boolean
Whether to link axes between plots
transforms (default={}): dict
A dictionary of HoloViews dim transforms to apply before plotting
title (default=''): str
Title for the plot
tools (default=[]): list
List of tool instances or strings (e.g. ['tap', 'box_select'])
xaxis/yaxis: str or None
Whether to show the x/y-axis and whether to place it at the
'top'/'bottom' and 'left'/'right' respectively.
xformatter/yformatter (default=None): str or TickFormatter
Formatter for the x-axis and y-axis (accepts printf formatter,
e.g. '%.3f', and bokeh TickFormatter)
xlabel/ylabel/clabel (default=None): str
Axis labels for the x-axis, y-axis, and colorbar
xlim/ylim (default=None): tuple or list
Plot limits of the x- and y-axis
xticks/yticks (default=None): int or list
Ticks along x- and y-axis specified as an integer, list of
ticks positions, or list of tuples of the tick positions and labels
width (default=700)/height (default=300): int
The width and height of the plot in pixels
attr_labels (default=None): bool
Whether to use an xarray object's attributes as labels, defaults to
None to allow best effort without throwing a warning. Set to True
to see warning if the attrs can't be found, set to False to disable
the behavior.
sort_date (default=True): bool
Whether to sort the x-axis by date before plotting
symmetric (default=None): bool
Whether the data are symmetric around zero. If left unset, the data
will be checked for symmetry as long as the size is less than
``check_symmetric_max``.
check_symmetric_max (default=1000000):
Size above which to stop checking for symmetry by default on the data.
Resampling options
------------------
aggregator (default=None):
Aggregator to use when applying rasterize or datashade operation
(valid options include 'mean', 'count', 'min', 'max' and more, and
datashader reduction objects)
dynamic (default=True):
Whether to return a dynamic plot which sends updates on widget and
zoom/pan events or whether all the data should be embedded
(warning: for large groupby operations embedded data can become
very large if dynamic=False)
datashade (default=False):
Whether to apply rasterization and shading (colormapping) using
the Datashader library, returning an RGB object instead of
individual points
downsample (default=False):
Whether to apply LTTB (Largest Triangle Three Buckets)
downsampling to the element (note this is only well behaved for
timeseries data). Requires HoloViews >= 1.16.
dynspread (default=False):
For plots generated with datashade=True or rasterize=True,
automatically increase the point size when the data is sparse
so that individual points become more visible
rasterize (default=False):
Whether to apply rasterization using the Datashader library,
returning an aggregated Image (to be colormapped by the
plotting backend) instead of individual points
resample_when (default=None):
Applies a resampling operation (datashade, rasterize or downsample) if
the number of individual data points present in the current zoom range
is above this threshold. The raw plot is displayed otherwise.
x_sampling/y_sampling (default=None):
Specifies the smallest allowed sampling interval along the x/y axis.
Geographic options
------------------
coastline (default=False):
Whether to display a coastline on top of the plot, setting
coastline='10m'/'50m'/'110m' specifies a specific scale.
crs (default=None):
Coordinate reference system of the data specified as Cartopy
CRS object, proj.4 string or EPSG code.
features (default=None): dict or list
A list of features or a dictionary of features and the scale
at which to render it. Available features include 'borders',
'coastline', 'lakes', 'land', 'ocean', 'rivers' and 'states'.
Available scales include '10m'/'50m'/'110m'.
geo (default=False):
Whether the plot should be treated as geographic (and assume
PlateCarree, i.e. lat/lon coordinates).
global_extent (default=False):
Whether to expand the plot extent to span the whole globe.
project (default=False):
Whether to project the data before plotting (adds initial
overhead but avoids projecting data when plot is dynamically
updated).
projection (default=None): str or Cartopy CRS
Coordinate reference system of the plot specified as Cartopy
CRS object or class name.
tiles (default=False):
Whether to overlay the plot on a tile source. Tiles sources
can be selected by name or a tiles object or class can be passed,
the default is 'Wikipedia'.
"""
_gridded_types = [
'image', 'contour', 'contourf', 'quadmesh', 'rgb', 'points',
'dataset'
]
_geom_types = ['paths', 'polygons']
_geo_types = sorted(_gridded_types + _geom_types + [
'points', 'vectorfield', 'labels', 'hexbin', 'bivariate'])
_stats_types = ['hist', 'kde', 'violin', 'box', 'density']
_data_options = [
'x', 'y', 'kind', 'by', 'use_index', 'use_dask', 'dynamic',
'crs', 'value_label', 'group_label', 'backlog', 'persist',
'sort_date'
]
_geo_options = [
'geo', 'crs', 'features', 'project', 'coastline', 'tiles',
'projection', 'global_extents'
]
_axis_options = [
'width', 'height', 'shared_axes', 'grid', 'legend',
'rot', 'xlim', 'ylim', 'xticks', 'yticks', 'colorbar',
'invert', 'title', 'logx', 'logy', 'loglog', 'xaxis',
'yaxis', 'xformatter', 'yformatter', 'xlabel', 'ylabel',
'clabel', 'padding', 'responsive', 'max_height', 'max_width',
'min_height', 'min_width', 'frame_height', 'frame_width',
'aspect', 'data_aspect', 'fontscale'
]
_style_options = [
'color', 'alpha', 'colormap', 'fontsize', 'c', 'cmap',
'color_key', 'cnorm', 'rescale_discrete_levels'
]
_op_options = [
'datashade', 'rasterize', 'x_sampling', 'y_sampling',
'downsample', 'aggregator', 'resample_when'
]
# Options specific to a particular plot type
_kind_options = {
'area' : ['y2'],
'errorbars': ['yerr1', 'yerr2'],
'bivariate': ['bandwidth', 'cut', 'filled', 'levels'],
'contour' : ['z', 'levels', 'logz'],
'contourf' : ['z', 'levels', 'logz'],
'dataset' : ['columns'],
'heatmap' : ['C', 'reduce_function', 'logz'],
'hexbin' : ['C', 'reduce_function', 'gridsize', 'logz', 'min_count'],
'hist' : ['bins', 'bin_range', 'normed', 'cumulative'],
'image' : ['z', 'logz'],
'kde' : ['bw_method', 'ind', 'bandwidth', 'cut', 'filled'],
'labels' : ['text', 'c', 'xoffset', 'yoffset', 'text_font', 'text_font_size'],
'ohlc' : ['bar_width', 'pos_color', 'neg_color', 'line_color'],
'points' : ['s', 'marker', 'c', 'scale', 'logz'],
'polygons' : ['logz', 'c'],
'rgb' : ['z', 'bands'],
'scatter' : ['s', 'c', 'scale', 'logz', 'marker'],
'step' : ['where'],
'table' : ['columns'],
'quadmesh' : ['z', 'logz'],
'vectorfield': ['angle', 'mag'],
}
# Mapping from kind to HoloViews element type
_kind_mapping = {
'area': Area,
'bar': Bars,
'barh': Bars,
'bivariate': Bivariate,
'box': BoxWhisker,
'contour': Contours,
'contourf': Polygons,
'dataset': Dataset,
'density': Distribution,
'errorbars': ErrorBars,
'hist': Histogram,
'image': Image,
'kde': Distribution,
'labels': Labels,
'line': Curve,
'scatter': Scatter,
'heatmap': HeatMap,
'hexbin': HexTiles,
'ohlc': Rectangles,
'paths': Path,
'points': Points,
'polygons': Polygons,
'quadmesh': QuadMesh,
'rgb': RGB,
'step': Curve,
'table': Table,
'vectorfield': VectorField,
'violin': Violin
}
# Types which have a colorbar by default
_colorbar_types = [
'bivariate', 'contour', 'contourf', 'heatmap', 'image',
'hexbin', 'quadmesh', 'polygons'
]
_legend_positions = (
"top_right", "top_left", "bottom_left", "bottom_right",
"right", "left", "top", "bottom"
)
_default_plot_opts = {
'logx': False,
'logy': False,
'show_legend': True,
'legend_position': 'right',
'show_grid': False,
'responsive': False,
'shared_axes': True
}
_default_cmaps = {
'linear': 'kbc_r',
'categorical': cc.palette['glasbey_category10'],
'cyclic': 'colorwheel',
'diverging': 'coolwarm'
}
def __init__(
self, data, x, y, kind=None, by=None, use_index=True,
group_label=None, value_label='value', backlog=1000,
persist=False, use_dask=False, crs=None, fields={},
groupby=None, dynamic=True, grid=None, legend=None, rot=None,
title=None, xlim=None, ylim=None, clim=None, symmetric=None,
logx=None, logy=None, loglog=None, hover=None, subplots=False,
label=None, invert=False, stacked=False, colorbar=None,
datashade=False, rasterize=False, downsample=None,
resample_when=None, row=None, col=None,
debug=False, framewise=True, aggregator=None,
projection=None, global_extent=None, geo=False,
precompute=False, flip_xaxis=None, flip_yaxis=None,
dynspread=False, hover_cols=[], x_sampling=None,
y_sampling=None, project=False, tools=[], attr_labels=None,
coastline=False, tiles=False, sort_date=True,
check_symmetric_max=1000000, transforms={}, stream=None,
cnorm=None, features=None, rescale_discrete_levels=None,
autorange=None, **kwds
):
# Process data and related options
self._redim = fields
self.use_index = use_index
self.value_label = value_label
self.label = label
self._process_data(
kind, data, x, y, by, groupby, row, col, use_dask,
persist, backlog, label, group_label, value_label,
hover_cols, attr_labels, transforms, stream, kwds
)
self.dynamic = dynamic
self.geo = any([geo, crs, global_extent, projection, project, coastline, features])
self.crs = self._process_crs(data, crs) if self.geo else None
self.output_projection = self.crs
self.project = project
self.coastline = coastline
self.features = features
self.tiles = tiles
self.sort_date = sort_date
# Import geoviews if geo-features requested
if self.geo or self.datatype == 'geopandas':
try:
import geoviews # noqa
except ImportError:
raise ImportError('In order to use geo-related features '
'the geoviews library must be available. '
'It can be installed with:\n conda '
'install geoviews')
if self.geo:
if self.kind not in self._geo_types:
param.main.param.warning(
f"geo option cannot be used with kind={self.kind!r} plot "
"type. Geographic plots are only supported for "
f"following plot types: {self._geo_types!r}")
from cartopy import crs as ccrs
from geoviews.util import project_extents
if isinstance(projection, str):
all_crs = [proj for proj in dir(ccrs) if
callable(getattr(ccrs, proj)) and
proj not in ['ABCMeta', 'CRS'] and
proj[0].isupper() or
proj == 'GOOGLE_MERCATOR']
if projection in all_crs and projection != 'GOOGLE_MERCATOR':
projection = getattr(ccrs, projection)()
elif projection == 'GOOGLE_MERCATOR':
projection = getattr(ccrs, projection)
else:
raise ValueError(
"Projection must be defined as cartopy CRS or "
f"one of the following CRS string:\n {all_crs}")
self.output_projection = projection or (ccrs.GOOGLE_MERCATOR if tiles else self.crs)
if tiles and self.output_projection != ccrs.GOOGLE_MERCATOR:
raise ValueError(
"Tiles can only be used with output projection of "
"`cartopy.crs.GOOGLE_MERCATOR`. To get rid of this error "
"remove `projection=` or `tiles=`"
)
if self.crs != projection and (xlim or ylim):
px0, py0, px1, py1 = ccrs.GOOGLE_MERCATOR.boundary.bounds
x0, x1 = xlim or (px0, px1)
y0, y1 = ylim or (py0, py1)
extents = (x0, y0, x1, y1)
x0, y0, x1, y1 = project_extents(extents, self.crs, self.output_projection)
if xlim:
xlim = (x0, x1)
if ylim:
ylim = (y0, y1)
# Operations
if resample_when is not None and not any([rasterize, datashade, downsample]):
raise ValueError(
'At least one resampling operation (rasterize, datashader, '
'downsample) must be enabled when resample_when is set.'
)
self.resample_when = resample_when
self.datashade = datashade
self.rasterize = rasterize
self.downsample = downsample
self.dynspread = dynspread
self.aggregator = aggregator
self.precompute = precompute
self.x_sampling = x_sampling
self.y_sampling = y_sampling
# By type
self.subplots = subplots
self._by_type = NdLayout if subplots else NdOverlay
self._backend = Store.current_backend
if hvplot_extension.compatibility is None:
self._backend_compat = self._backend
else:
self._backend_compat = hvplot_extension.compatibility
self.stacked = stacked
plot_opts = dict(self._default_plot_opts,
**self._process_plot())
if xlim is not None:
plot_opts['xlim'] = tuple(xlim)
if ylim is not None:
plot_opts['ylim'] = tuple(ylim)
if autorange is not None:
if hv_version < Version('1.16.0'):
param.main.param.warning('autorange option requires HoloViews >= 1.16')
else:
plot_opts['autorange'] = autorange
self.invert = invert
if loglog is not None:
logx = logx or loglog
logy = logy or loglog
if logx is not None:
plot_opts['logx'] = logx
if logy is not None:
plot_opts['logy'] = logy
if grid is not None:
plot_opts['show_grid'] = grid
if legend is not None:
plot_opts['show_legend'] = bool(legend)
if legend in self._legend_positions:
plot_opts['legend_position'] = legend
elif legend not in (True, False, None):
raise ValueError('The legend option should be a boolean or '
'a valid legend position (i.e. one of %s).'
% list(self._legend_positions))
plotwds = ['xticks', 'yticks', 'xlabel', 'ylabel', 'clabel',
'padding', 'xformatter', 'yformatter',
'height', 'width', 'frame_height', 'frame_width',
'min_width', 'min_height', 'max_width', 'max_height',
'fontsize', 'fontscale', 'responsive', 'shared_axes',
'aspect', 'data_aspect']
for plotwd in plotwds:
if plotwd in kwds:
plot_opts[plotwd] = kwds.pop(plotwd)
self._style_opts, plot_opts, kwds = self._process_style(kwds, plot_opts)
for axis_name in ['xaxis', 'yaxis']:
if axis_name in kwds:
axis = kwds.pop(axis_name)
if not axis:
plot_opts[axis_name] = None
elif axis != True:
plot_opts[axis_name] = axis
elif axis_name in plot_opts:
plot_opts.pop(axis_name, None)
if flip_xaxis:
plot_opts['invert_xaxis'] = True
if flip_yaxis:
plot_opts['invert_yaxis'] = True
if self.geo and not plot_opts.get('data_aspect'):
plot_opts['data_aspect'] = 1
ignore_opts = ['responsive', 'aspect', 'data_aspect', 'frame_height', 'frame_width']
if not any(plot_opts.get(opt) for opt in ignore_opts):
plot_opts['width'] = plot_opts.get('width', 700)
plot_opts['height'] = plot_opts.get('height', 300)
if isinstance(colorbar, bool):
plot_opts['colorbar'] = colorbar
elif self.kind in self._colorbar_types:
plot_opts['colorbar'] = True
elif self.rasterize:
plot_opts['colorbar'] = plot_opts.get('colorbar', True)
if 'logz' in kwds and 'logz' in self._kind_options.get(self.kind, {}):
plot_opts['logz'] = kwds.pop('logz')
if invert:
plot_opts['invert_axes'] = self.kind != 'barh'
if rot:
axis = 'yrotation' if invert else 'xrotation'
plot_opts[axis] = rot
tools = list(tools) or list(plot_opts.get('tools', []))
# Disable hover for errorbars plot as Bokeh annotations can't be hovered.
if kind == 'errorbars':
hover = False
elif hover is None:
hover = not self.datashade
if hover and not any(t for t in tools if isinstance(t, HoverTool)
or t in ['hover', 'vline', 'hline']):
if hover in ['vline', 'hline']:
tools.append(hover)
else:
tools.append('hover')
plot_opts['tools'] = tools
if self.crs and global_extent:
plot_opts['global_extent'] = global_extent
if projection:
plot_opts['projection'] = self.output_projection
title = title if title is not None else getattr(self, '_title', None)
if title is not None:
plot_opts['title'] = title
if (self.kind in self._colorbar_types or self.rasterize or self.datashade or self._color_dim):
try:
if not use_dask:
symmetric = self._process_symmetric(symmetric, clim, check_symmetric_max)
if self._style_opts.get('cmap') is None:
# Default to categorical camp if we detect categorical shading
if ((self.datashade or self.rasterize) and (self.aggregator is None or 'count_cat' in str(self.aggregator)) and
((self.by and not self.subplots) or
(isinstance(self.y, list) or (self.y is None and len(set(self.variables) - set(self.indexes)) > 1)))):
self._style_opts['cmap'] = self._default_cmaps['categorical']
elif symmetric:
self._style_opts['cmap'] = self._default_cmaps['diverging']
else:
self._style_opts['cmap'] = self._default_cmaps['linear']
if symmetric is not None:
plot_opts['symmetric'] = symmetric
except TypeError:
pass
if cnorm is not None:
plot_opts['cnorm'] = cnorm
if rescale_discrete_levels is not None and hv_version >= Version('1.15.0'):
plot_opts['rescale_discrete_levels'] = rescale_discrete_levels
self._plot_opts = plot_opts
self._overlay_opts = {k: v for k, v in self._plot_opts.items()
if k in OverlayPlot.param.objects()}
self._norm_opts = {'framewise': framewise, 'axiswise': not plot_opts.get('shared_axes')}
self.kwds = kwds
# Process dimensions and labels
self.label = label
self._relabel = {'label': label} if label else {}
self._dim_ranges = {'c': clim or (None, None)}
# High-level options
self._validate_kwds(kwds)
if debug:
kwds = dict(x=self.x, y=self.y, by=self.by, kind=self.kind,
groupby=self.groupby, grid=self.grid)
param.main.param.warning('Plotting {kind} plot with parameters x: {x}, '
'y: {y}, by: {by}, groupby: {groupby}, row/col: {grid}'.format(**kwds))
def _process_symmetric(self, symmetric, clim, check_symmetric_max):
if symmetric is not None or clim is not None:
return symmetric
if is_xarray(self.data):
# chunks mean it's lazily loaded; nanquantile will eagerly load
data = self.data[self.z]
if not getattr(data, '_in_memory', True) or data.chunks:
return False
if is_xarray_dataarray(data):
if data.size > check_symmetric_max:
return False
else:
return False
elif self._color_dim:
data = self.data[self._color_dim]
else:
return
if data.size == 0:
return False
cmin = np.nanquantile(data, 0.05)
cmax = np.nanquantile(data, 0.95)
return bool(cmin < 0 and cmax > 0)
def _process_crs(self, data, crs):
"""Given crs as proj4 string, data.attr, or cartopy.crs return cartopy.crs
"""
if hasattr(data, 'rio') and data.rio.crs is not None:
# if data is a rioxarray
_crs = data.rio.crs.to_wkt()
else:
# get the proj string: either the value of data.attrs[crs] or crs itself
_crs = getattr(data, 'attrs', {}).get(crs or 'crs', crs)
try:
return process_crs(_crs)
except ValueError as e:
# only raise error if crs was specified in kwargs
if crs:
raise ValueError(
f"'{crs}' must be either a valid crs or an reference to "
f"a `data.attr` containing a valid crs: {e}")
def _process_data(self, kind, data, x, y, by, groupby, row, col,
use_dask, persist, backlog, label, group_label,
value_label, hover_cols, attr_labels, transforms,
stream, kwds):
gridded = kind in self._gridded_types
gridded_data = False
da = None
# Validate DataSource
self.data_source = data
self.is_series = is_series(data)
if self.is_series:
data = data.to_frame()
if is_intake(data):
data = process_intake(data, use_dask or persist)
# Pandas interface in HoloViews doesn't accept non-string columns.
# The converter stores a reference to the source data to
# update the `_dataset` property (of the hv object its __call__ method
# returns) with a hv Dataset created from the source data, which
# is done for optimizating some operations in HoloViews.
data = _convert_col_names_to_str(data)
self.source_data = data
if groupby is not None and not isinstance(groupby, list):
groupby = [groupby]
if by is not None and not isinstance(by, list):
by = [by]
grid = []
if row is not None: grid.append(row)
if col is not None: grid.append(col)
streaming = False
if is_geodataframe(data):
datatype = 'geopandas' if hasattr(data, 'geom_type') else 'spatialpandas'
self.data = data
if kind is None:
if datatype == 'geopandas':
geom_types = {gt[5:] if 'Multi' in gt else gt for gt in data.geom_type}
else:
geom_types = [type(data.geometry.dtype).__name__.replace('Multi', '').replace('Dtype', '')]
if len(geom_types) > 1:
raise ValueError('The GeopandasInterface can only read dataframes which '
'share a common geometry type')
geom_type = list(geom_types)[0]
if geom_type == 'Point':
kind = 'points'
elif geom_type == 'Polygon':
kind = 'polygons'
elif geom_type in ('LineString', 'LineRing', 'Line'):
kind = 'paths'
# if only one arg is provided, treat it like color
if x is not None and y is None:
kwds['color'] = kwds.pop('color', kwds.pop('c', x))
x = None
elif isinstance(data, pd.DataFrame):
datatype = 'pandas'
self.data = data
elif is_dask(data):
datatype = 'dask'
self.data = data.persist() if persist else data
elif is_cudf(data):
datatype = 'cudf'
self.data = data
elif is_ibis(data):
datatype = 'ibis'
self.data = data
elif is_streamz(data):
datatype = 'streamz'
self.data = data.example
if isinstance(self.data, pd.DataFrame):
self.data = self.data.iloc[:0]
self.stream_type = data._stream_type
streaming = True
self.cb = data
if data._stream_type == 'updating':
self.stream = Pipe(data=self.data)
else:
self.stream = Buffer(data=self.data, length=backlog, index=False)
data.stream.gather().sink(self.stream.send)
elif is_xarray(data):
import xarray as xr
z = kwds.get('z')
if isinstance(data, xr.Dataset):
if len(data.data_vars) == 0:
raise ValueError("Cannot plot an empty xarray.Dataset object.")
if z is None:
if isinstance(data, xr.Dataset):
z = list(data.data_vars)[0]
else:
z = data.name or label or value_label
if gridded and isinstance(data, xr.Dataset) and not isinstance(z, list):
data = data[z]
self.z = z
ignore = (groupby or []) + (by or []) + grid
coords = [c for c in data.coords if data[c].shape != ()
and c not in ignore]
dims = [c for c in data.dims if data[c].shape != ()
and c not in ignore]
if kind is None and (not (x or y) or all(c in data.coords for c in (x, y))):
if list(data.coords) == ['band', 'y', 'x']:
kind = 'rgb'
gridded = True
elif len(coords) == 1:
kind = 'line'
elif len(coords) == 2 or (x and y) or len([c for c in coords if c in dims]) == 2:
kind = 'image'
gridded = True
else:
kind = 'hist'
datatype = 'dask' if use_dask else 'pandas'
if gridded:
datatype = 'xarray'
gridded_data = True
if kind == 'rgb':
if 'bands' in kwds:
other_dims = [kwds['bands']]
else:
other_dims = [d for d in data.coords if d not in (groupby or [])][0]
else:
other_dims = []
da = data
data, x, y, by_new, groupby_new = process_xarray(
data, x, y, by, groupby, use_dask, persist, gridded,
label, value_label, other_dims, kind=kind)
if kind not in self._stats_types:
if by is None: by = by_new
if groupby is None: groupby = groupby_new
if groupby:
groupby = [g for g in groupby if g not in grid]
# Add a title to hvplot.xarray plots that displays scalar coords values,
# as done by xarray.plot()
if not groupby and not grid:
if isinstance(da, xr.DataArray):
self._title = da._title_for_slice()
elif isinstance(da, xr.Dataset):
self._title = partial(xr.DataArray._title_for_slice, da)()
self.data = data
else:
raise ValueError('Supplied data type %s not understood' % type(data).__name__)
if stream is not None:
if streaming:
raise ValueError("Cannot supply streamz.DataFrame and stream argument.")
self.stream = stream
self.cb = None
if isinstance(stream, Pipe):
self.stream_type = 'updating'
elif isinstance(stream, Buffer):
self.stream_type = 'streaming'
else:
raise ValueError("Stream of type %s not recognized." % type(stream))
streaming = True
# Validate data and arguments
if by is None: by = []
if groupby is None: groupby = []
if gridded_data:
not_found = [g for g in groupby if g not in data.coords]
not_found, _, _ = process_derived_datetime_xarray(data, not_found)
data_vars = list(data.data_vars) if isinstance(data, xr.Dataset) else [data.name]
indexes = list(data.coords.indexes)
# Handle undeclared indexes
if x is not None and x not in indexes:
indexes.append(x)
if y is not None and y not in indexes:
indexes.append(y)
for data_dim in data.dims:
if not any(data_dim in data[c].dims for c in indexes):
for coord in data.coords:
if coord not in indexes and {data_dim} == set(data[coord].dims):
indexes.append(data_dim)
self.data = self.data.set_index({data_dim: coord})
if coord not in groupby+by:
groupby.append(data_dim)
self.variables = list(data.coords) + data_vars
if groupby and not_found:
raise ValueError(f'The supplied groupby dimension(s) {not_found} '
'could not be found, expected one or '
f'more of: {list(data.coords)}')
else:
if gridded and kind not in ('points', 'dataset'):
raise ValueError(f'{kind} plot type requires gridded data, '
'e.g. a NumPy array or xarray Dataset, '
f'found {type(self.data).__name__} type')
if hasattr(data, 'columns') and hasattr(data.columns, 'name') and data.columns.name and not group_label:
group_label = data.columns.name
elif not group_label:
group_label = 'Variable'
if isinstance(data.columns, pd.MultiIndex) and x in (None, 'index') and y is None and not by:
self.data = data.stack().reset_index(1).rename(columns={'level_1': group_label})
by = group_label
x = 'index'
# Determine valid indexes
if isinstance(self.data, pd.DataFrame):
if self.data.index.names == [None]:
indexes = [self.data.index.name or 'index']
else:
indexes = list(self.data.index.names)
elif hasattr(self.data, 'reset_index'):
indexes = [c for c in self.data.reset_index().columns
if c not in self.data.columns]
else:
indexes = [c for c in self.data.columns
if c not in self.data.columns]
if len(indexes) == 2 and not (x or y or by):
if kind == 'heatmap':
x, y = indexes
elif kind in ('bar', 'barh'):
x, by = indexes
self.variables = indexes + list(self.data.columns)
# Reset groupby dimensions
groupby_index = [g for g in groupby if g in indexes]
if groupby_index:
self.data = self.data.reset_index(groupby_index)
if isinstance(by, (np.ndarray, pd.Series)):
by_cols = []
else:
by_cols = by if isinstance(by, list) else [by]
not_found = [g for g in groupby+by_cols if g not in list(self.data.columns)+indexes]
not_found, self.data = process_derived_datetime_pandas(self.data, not_found, indexes)
if groupby and not_found:
raise ValueError(f'The supplied groupby dimension(s) {not_found} '
'could not be found, expected one or '
f'more of: {list(self.data.columns)}')
if transforms:
self.data = Dataset(self.data, indexes).transform(**transforms).data
# Set data-level options
self.x = x
self.y = y
self.kind = kind or 'line'
self.datatype = datatype
self.gridded = gridded
self.gridded_data = gridded_data
self.use_dask = use_dask
self.indexes = indexes
self.group_label = group_label or 'Variable'
if isinstance(by, (np.ndarray, pd.Series)):
self.data = self.data.assign(_by=by)
self.by = ['_by']
self.variables.append('_by')
elif not by:
self.by = []
else:
self.by = by if isinstance(by, list) else [by]
self.groupby = groupby
self.grid = grid
self.streaming = streaming
if not hover_cols:
self.hover_cols = []
elif isinstance(hover_cols, list):
self.hover_cols = hover_cols
elif hover_cols == 'all' and self.use_index:
self.hover_cols = self.variables
elif hover_cols == 'all' and not self.use_index:
self.hover_cols = [v for v in self.variables if v not in self.indexes]
elif hover_cols !='all' and isinstance(hover_cols,str):
self.hover_cols = [hover_cols]
if self.datatype in ('geopandas', 'spatialpandas'):
self.hover_cols = [c for c in self.hover_cols if c!= 'geometry']
if da is not None and attr_labels is True or attr_labels is None:
try:
var_tuples = [(var, da[var].attrs) for var in da.coords]
if isinstance(da, xr.Dataset):
var_tuples.extend([(var, da[var].attrs) for var in da.data_vars])
else:
var_tuples.append((da.name, da.attrs))
labels = {}
units = {}
for var_name, var_attrs in var_tuples:
if var_name is None:
var_name = 'value'
if isinstance(var_attrs.get('long_name'), str):
labels[var_name] = var_attrs['long_name']
if 'units' in var_attrs:
units[var_name] = var_attrs['units']
self._redim = self._merge_redim(labels, 'label')
self._redim = self._merge_redim(units, 'unit')
except Exception as e:
if attr_labels is True:
param.main.param.warning('Unable to auto label using xarray attrs '
f'because {e}')
def _process_plot(self):
kind = self.kind
options = Store.options(backend='bokeh')
elname = self._kind_mapping[kind].__name__