/
element.py
2226 lines (1901 loc) · 95.1 KB
/
element.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
from __future__ import absolute_import, division, unicode_literals
import warnings
from types import FunctionType
import param
import numpy as np
import bokeh
import bokeh.plotting
from bokeh.core.properties import value
from bokeh.document.events import ModelChangedEvent
from bokeh.models import Renderer, Title, Legend, ColorBar, tools
from bokeh.models.axes import CategoricalAxis, DatetimeAxis
from bokeh.models.formatters import (
FuncTickFormatter, TickFormatter, MercatorTickFormatter)
from bokeh.models.mappers import (
LinearColorMapper, LogColorMapper, CategoricalColorMapper)
from bokeh.models.ranges import Range1d, DataRange1d, FactorRange
from bokeh.models.tickers import (
Ticker, BasicTicker, FixedTicker, LogTicker, MercatorTicker)
from bokeh.models.widgets import Panel, Tabs
from bokeh.plotting.helpers import _known_tools as known_tools
from ...core import DynamicMap, CompositeOverlay, Element, Dimension, Dataset
from ...core.options import abbreviated_exception, SkipRendering
from ...core import util
from ...element import Graph, VectorField, Path, Contours, Tiles
from ...streams import Stream, Buffer, PlotSize
from ...util.transform import dim
from ..plot import GenericElementPlot, GenericOverlayPlot
from ..util import dynamic_update, process_cmap, color_intervals, dim_range_key
from .callbacks import PlotSizeCallback
from .plot import BokehPlot
from .styles import (
legend_dimensions, line_properties, mpl_to_bokeh, property_prefixes,
rgba_tuple, text_properties, validate)
from .util import (
TOOL_TYPES, bokeh_version, date_to_integer, decode_bytes, get_tab_title,
glyph_order, py2js_tickformatter, recursive_model_update,
theme_attr_json, cds_column_replace, hold_policy, match_dim_specs,
compute_layout_properties, wrap_formatter)
class ElementPlot(BokehPlot, GenericElementPlot):
active_tools = param.List(default=[], doc="""
Allows specifying which tools are active by default. Note
that only one tool per gesture type can be active, e.g.
both 'pan' and 'box_zoom' are drag tools, so if both are
listed only the last one will be active.""")
align = param.ObjectSelector(default=None, objects=['start', 'center', 'end'], doc="""
Alignment (vertical or horizontal) of the plot in a layout.""")
border = param.Number(default=10, doc="""
Minimum border around plot.""")
aspect = param.Parameter(default=None, doc="""
The aspect ratio mode of the plot. By default, a plot may
select its own appropriate aspect ratio but sometimes it may
be necessary to force a square aspect ratio (e.g. to display
the plot as an element of a grid). The modes 'auto' and
'equal' correspond to the axis modes of the same name in
matplotlib, a numeric value specifying the ratio between plot
width and height may also be passed. To control the aspect
ratio between the axis scales use the data_aspect option
instead.""")
data_aspect = param.Number(default=None, doc="""
Defines the aspect of the axis scaling, i.e. the ratio of
y-unit to x-unit.""")
width = param.Integer(default=300, allow_None=True, bounds=(0, None), doc="""
The width of the component (in pixels). This can be either
fixed or preferred width, depending on width sizing policy.""")
height = param.Integer(default=300, allow_None=True, bounds=(0, None), doc="""
The height of the component (in pixels). This can be either
fixed or preferred height, depending on height sizing policy.""")
frame_width = param.Integer(default=None, allow_None=True, bounds=(0, None), doc="""
The width of the component (in pixels). This can be either
fixed or preferred width, depending on width sizing policy.""")
frame_height = param.Integer(default=None, allow_None=True, bounds=(0, None), doc="""
The height of the component (in pixels). This can be either
fixed or preferred height, depending on height sizing policy.""")
min_width = param.Integer(default=None, bounds=(0, None), doc="""
Minimal width of the component (in pixels) if width is adjustable.""")
min_height = param.Integer(default=None, bounds=(0, None), doc="""
Minimal height of the component (in pixels) if height is adjustable.""")
max_width = param.Integer(default=None, bounds=(0, None), doc="""
Minimal width of the component (in pixels) if width is adjustable.""")
max_height = param.Integer(default=None, bounds=(0, None), doc="""
Minimal height of the component (in pixels) if height is adjustable.""")
margin = param.Parameter(default=None, doc="""
Allows to create additional space around the component. May
be specified as a two-tuple of the form (vertical, horizontal)
or a four-tuple (top, right, bottom, left).""")
responsive = param.ObjectSelector(default=False, objects=[False, True, 'width', 'height'])
finalize_hooks = param.HookList(default=[], doc="""
Deprecated; use hooks options instead.""")
hooks = param.HookList(default=[], doc="""
Optional list of hooks called when finalizing a plot. The
hook is passed the plot object and the displayed element, and
other plotting handles can be accessed via plot.handles.""")
fontsize = param.Parameter(default={'title': '12pt'}, allow_None=True, doc="""
Specifies various fontsizes of the displayed text.
Finer control is available by supplying a dictionary where any
unmentioned keys reverts to the default sizes, e.g:
{'ticks': '20pt', 'title': '15pt', 'ylabel': '5px', 'xlabel': '5px'}""")
gridstyle = param.Dict(default={}, doc="""
Allows customizing the grid style, e.g. grid_line_color defines
the line color for both grids while xgrid_line_color exclusively
customizes the x-axis grid lines.""")
labelled = param.List(default=['x', 'y'], doc="""
Whether to plot the 'x' and 'y' labels.""")
lod = param.Dict(default={'factor': 10, 'interval': 300,
'threshold': 2000, 'timeout': 500}, doc="""
Bokeh plots offer "Level of Detail" (LOD) capability to
accommodate large (but not huge) amounts of data. The available
options are:
* factor : Decimation factor to use when applying
decimation.
* interval : Interval (in ms) downsampling will be enabled
after an interactive event.
* threshold : Number of samples before downsampling is enabled.
* timeout : Timeout (in ms) for checking whether interactive
tool events are still occurring.""")
show_frame = param.Boolean(default=True, doc="""
Whether or not to show a complete frame around the plot.""")
shared_axes = param.Boolean(default=True, doc="""
Whether to invert the share axes across plots
for linked panning and zooming.""")
default_tools = param.List(default=['save', 'pan', 'wheel_zoom',
'box_zoom', 'reset'],
doc="A list of plugin tools to use on the plot.")
tools = param.List(default=[], doc="""
A list of plugin tools to use on the plot.""")
toolbar = param.ObjectSelector(default='right',
objects=["above", "below",
"left", "right", "disable", None],
doc="""
The toolbar location, must be one of 'above', 'below',
'left', 'right', None.""")
xformatter = param.ClassSelector(
default=None, class_=(util.basestring, TickFormatter, FunctionType), doc="""
Formatter for ticks along the x-axis.""")
yformatter = param.ClassSelector(
default=None, class_=(util.basestring, TickFormatter, FunctionType), doc="""
Formatter for ticks along the x-axis.""")
_categorical = False
# Declare which styles cannot be mapped to a non-scalar dimension
_nonvectorized_styles = []
# Declares the default types for continuous x- and y-axes
_x_range_type = Range1d
_y_range_type = Range1d
# Whether the plot supports streaming data
_stream_data = True
def __init__(self, element, plot=None, **params):
self.current_ranges = None
super(ElementPlot, self).__init__(element, **params)
self.handles = {} if plot is None else self.handles['plot']
self.static = len(self.hmap) == 1 and len(self.keys) == len(self.hmap)
self.callbacks = self._construct_callbacks()
self.static_source = False
self.streaming = [s for s in self.streams if isinstance(s, Buffer)]
self.geographic = bool(self.hmap.last.traverse(lambda x: x, Tiles))
if self.geographic and self.projection is None:
self.projection = 'mercator'
# Whether axes are shared between plots
self._shared = {'x': False, 'y': False}
def _hover_opts(self, element):
if self.batched:
dims = list(self.hmap.last.kdims)
else:
dims = list(self.overlay_dims.keys())
dims += element.dimensions()
return list(util.unique_iterator(dims)), {}
def _init_tools(self, element, callbacks=[]):
"""
Processes the list of tools to be supplied to the plot.
"""
tooltips, hover_opts = self._hover_opts(element)
tooltips = [(ttp.pprint_label, '@{%s}' % util.dimension_sanitizer(ttp.name))
if isinstance(ttp, Dimension) else ttp for ttp in tooltips]
if not tooltips: tooltips = None
callbacks = callbacks+self.callbacks
cb_tools, tool_names = [], []
hover = False
for cb in callbacks:
for handle in cb.models+cb.extra_models:
if handle and handle in known_tools:
tool_names.append(handle)
if handle == 'hover':
tool = tools.HoverTool(
tooltips=tooltips, tags=['hv_created'],
**hover_opts)
hover = tool
else:
tool = known_tools[handle]()
cb_tools.append(tool)
self.handles[handle] = tool
tool_list = [
t for t in cb_tools + self.default_tools + self.tools
if t not in tool_names]
copied_tools = []
for tool in tool_list:
if isinstance(tool, tools.Tool):
properties = tool.properties_with_values(include_defaults=False)
tool = type(tool)(**properties)
copied_tools.append(tool)
hover_tools = [t for t in copied_tools if isinstance(t, tools.HoverTool)]
if 'hover' in copied_tools:
hover = tools.HoverTool(tooltips=tooltips, tags=['hv_created'], **hover_opts)
copied_tools[copied_tools.index('hover')] = hover
elif any(hover_tools):
hover = hover_tools[0]
if hover:
self.handles['hover'] = hover
return copied_tools
def _update_hover(self, element):
tooltips, hover_opts = self._hover_opts(element)
tooltips = [(ttp.pprint_label, '@{%s}' % util.dimension_sanitizer(ttp.name))
if isinstance(ttp, Dimension) else ttp for ttp in tooltips]
self.handles['hover'].tooltips = tooltips
def _get_hover_data(self, data, element, dimensions=None):
"""
Initializes hover data based on Element dimension values.
If empty initializes with no data.
"""
if 'hover' not in self.handles or self.static_source:
return
for d in (dimensions or element.dimensions()):
dim = util.dimension_sanitizer(d.name)
if dim not in data:
data[dim] = element.dimension_values(d)
values = np.asarray(data[dim])
if (values.dtype.kind == 'M' or (
len(values) and isinstance(values[0], util.datetime_types))):
data[dim+'_dt_strings'] = [d.pprint_value(v) for v in values]
for k, v in self.overlay_dims.items():
dim = util.dimension_sanitizer(k.name)
if dim not in data:
data[dim] = [v for _ in range(len(list(data.values())[0]))]
def _merge_ranges(self, plots, xspecs, yspecs):
"""
Given a list of other plots return axes that are shared
with another plot by matching the dimensions specs stored
as tags on the dimensions.
"""
plot_ranges = {}
for plot in plots:
if plot is None:
continue
if hasattr(plot, 'x_range') and plot.x_range.tags and xspecs is not None:
if match_dim_specs(plot.x_range.tags[0], xspecs):
plot_ranges['x_range'] = plot.x_range
if match_dim_specs(plot.x_range.tags[0], yspecs):
plot_ranges['y_range'] = plot.x_range
if hasattr(plot, 'y_range') and plot.y_range.tags and yspecs is not None:
if match_dim_specs(plot.y_range.tags[0], yspecs):
plot_ranges['y_range'] = plot.y_range
if match_dim_specs(plot.y_range.tags[0], xspecs):
plot_ranges['x_range'] = plot.y_range
return plot_ranges
def _get_axis_dims(self, element):
"""Returns the dimensions corresponding to each axis.
Should return a list of dimensions or list of lists of
dimensions, which will be formatted to label the axis
and to link axes.
"""
dims = element.dimensions()[:2]
if len(dims) == 1:
return dims + [None, None]
else:
return dims + [None]
def _axes_props(self, plots, subplots, element, ranges):
# Get the bottom layer and range element
el = element.traverse(lambda x: x, [Element])
el = el[0] if el else element
dims = self._get_axis_dims(el)
xlabel, ylabel, zlabel = self._get_axis_labels(dims)
if self.invert_axes:
xlabel, ylabel = ylabel, xlabel
dims = dims[:2][::-1]
xdims, ydims = dims[:2]
if xdims:
if not isinstance(xdims, list):
xdims = [xdims]
xspecs = tuple((xd.name, xd.label, xd.unit) for xd in xdims)
else:
xspecs = None
if ydims:
if not isinstance(ydims, list):
ydims = [ydims]
yspecs = tuple((yd.name, yd.label, yd.unit) for yd in ydims)
else:
yspecs = None
plot_ranges = {}
# Try finding shared ranges in other plots in the same Layout
if plots and self.shared_axes:
plot_ranges = self._merge_ranges(plots, xspecs, yspecs)
# Get the Element that determines the range and get_extents
range_el = el if self.batched and not isinstance(self, OverlayPlot) else element
l, b, r, t = self.get_extents(range_el, ranges)
if self.invert_axes:
l, b, r, t = b, l, t, r
categorical = any(self.traverse(lambda x: x._categorical))
if xdims is not None and any(xdim.name in ranges and 'factors' in ranges[xdim.name] for xdim in xdims):
categorical_x = True
else:
categorical_x = any(isinstance(x, util.basestring) for x in (l, r))
if ydims is not None and any(ydim.name in ranges and 'factors' in ranges[ydim.name] for ydim in ydims):
categorical_y = True
else:
categorical_y = any(isinstance(y, util.basestring) for y in (b, t))
x_axis_type = 'log' if self.logx else 'auto'
if xdims:
if len(xdims) > 1:
x_axis_type = 'auto'
categorical_x = True
else:
if isinstance(el, Graph):
xtype = el.nodes.get_dimension_type(xdims[0])
else:
xtype = el.get_dimension_type(xdims[0])
if ((xtype is np.object_ and issubclass(type(l), util.datetime_types)) or
xtype in util.datetime_types):
x_axis_type = 'datetime'
y_axis_type = 'log' if self.logy else 'auto'
if ydims:
if len(ydims) > 1:
y_axis_type = 'auto'
categorical_y = True
else:
if isinstance(el, Graph):
ytype = el.nodes.get_dimension_type(ydims[0])
else:
ytype = el.get_dimension_type(ydims[0])
if ((ytype is np.object_ and issubclass(type(b), util.datetime_types))
or ytype in util.datetime_types):
y_axis_type = 'datetime'
# Declare shared axes
if 'x_range' in plot_ranges:
self._shared['x'] = True
if 'y_range' in plot_ranges:
self._shared['y'] = True
range_types = (self._x_range_type, self._y_range_type)
if self.invert_axes: range_types = range_types[::-1]
x_range_type, y_range_type = range_types
if categorical or categorical_x:
x_axis_type = 'auto'
plot_ranges['x_range'] = FactorRange()
elif 'x_range' not in plot_ranges:
plot_ranges['x_range'] = x_range_type()
if categorical or categorical_y:
y_axis_type = 'auto'
plot_ranges['y_range'] = FactorRange()
elif 'y_range' not in plot_ranges:
plot_ranges['y_range'] = y_range_type()
x_range, y_range = plot_ranges['x_range'], plot_ranges['y_range']
if not x_range.tags and xspecs is not None:
x_range.tags.append(xspecs)
if not y_range.tags and yspecs is not None:
y_range.tags.append(yspecs)
return (x_axis_type, y_axis_type), (xlabel, ylabel, zlabel), plot_ranges
def _init_plot(self, key, element, plots, ranges=None):
"""
Initializes Bokeh figure to draw Element into and sets basic
figure and axis attributes including axes types, labels,
titles and plot height and width.
"""
subplots = list(self.subplots.values()) if self.subplots else []
axis_types, labels, plot_ranges = self._axes_props(plots, subplots, element, ranges)
xlabel, ylabel, _ = labels
x_axis_type, y_axis_type = axis_types
properties = dict(plot_ranges)
properties['x_axis_label'] = xlabel if 'x' in self.labelled or self.xlabel else ' '
properties['y_axis_label'] = ylabel if 'y' in self.labelled or self.ylabel else ' '
if not self.show_frame:
properties['outline_line_alpha'] = 0
if self.show_title and self.adjoined is None:
title = self._format_title(key, separator=' ')
else:
title = ''
if self.toolbar != 'disable':
tools = self._init_tools(element)
properties['tools'] = tools
properties['toolbar_location'] = self.toolbar
else:
properties['tools'] = []
properties['toolbar_location'] = None
if self.renderer.webgl:
properties['output_backend'] = 'webgl'
properties.update(**self._plot_properties(key, element))
with warnings.catch_warnings():
# Bokeh raises warnings about duplicate tools but these
# are not really an issue
warnings.simplefilter('ignore', UserWarning)
return bokeh.plotting.Figure(x_axis_type=x_axis_type,
y_axis_type=y_axis_type, title=title,
**properties)
def _plot_properties(self, key, element):
"""
Returns a dictionary of plot properties.
"""
init = 'plot' not in self.handles
size_multiplier = self.renderer.size/100.
options = self._traverse_options(element, 'plot', ['width', 'height'], defaults=False)
logger = self.param if init else None
aspect_props, dimension_props = compute_layout_properties(
self.width, self.height, self.frame_width, self.frame_height,
options['width'], options['height'], self.aspect, self.data_aspect,
self.responsive, size_multiplier, logger=logger)
if not init:
if aspect_props['aspect_ratio'] is None:
aspect_props['aspect_ratio'] = self.state.aspect_ratio
if self.dynamic and aspect_props['match_aspect']:
# Sync the plot size on dynamic plots to support accurate
# scaling of dimension ranges
plot_size = [s for s in self.streams if isinstance(s, PlotSize)]
callbacks = [c for c in self.callbacks if isinstance(c, PlotSizeCallback)]
if plot_size:
stream = plot_size[0]
elif callbacks:
stream = callbacks[0].streams[0]
else:
stream = PlotSize()
self.callbacks.append(PlotSizeCallback(self, [stream], None))
stream.add_subscriber(self._update_size)
plot_props = {
'align': self.align,
'margin': self.margin,
'max_width': self.max_width,
'max_height': self.max_height,
'min_width': self.min_width,
'min_height': self.min_height
}
plot_props.update(aspect_props)
if not self.drawn:
plot_props.update(dimension_props)
if self.bgcolor:
plot_props['background_fill_color'] = self.bgcolor
if self.border is not None:
for p in ['left', 'right', 'top', 'bottom']:
plot_props['min_border_'+p] = self.border
lod = dict(self.param.defaults().get('lod', {}), **self.lod)
for lod_prop, v in lod.items():
plot_props['lod_'+lod_prop] = v
return plot_props
def _update_size(self, width, height, scale):
self.state.frame_width = width
self.state.frame_height = height
def _set_active_tools(self, plot):
"Activates the list of active tools"
for tool in self.active_tools:
if isinstance(tool, util.basestring):
tool_type = TOOL_TYPES[tool]
matching = [t for t in plot.toolbar.tools
if isinstance(t, tool_type)]
if not matching:
self.param.warning('Tool of type %r could not be found '
'and could not be activated by default.'
% tool)
continue
tool = matching[0]
if isinstance(tool, tools.Drag):
plot.toolbar.active_drag = tool
if isinstance(tool, tools.Scroll):
plot.toolbar.active_scroll = tool
if isinstance(tool, tools.Tap):
plot.toolbar.active_tap = tool
if isinstance(tool, tools.Inspection):
plot.toolbar.active_inspect.append(tool)
def _title_properties(self, key, plot, element):
if self.show_title and self.adjoined is None:
title = self._format_title(key, separator=' ')
else:
title = ''
opts = dict(text=title)
# this will override theme if not set to the default 12pt
title_font = self._fontsize('title').get('fontsize')
if title_font != '12pt':
opts['text_font_size'] = value(title_font)
return opts
def _init_axes(self, plot):
if self.xaxis is None:
plot.xaxis.visible = False
elif isinstance(self.xaxis, util.basestring) and 'top' in self.xaxis:
plot.above = plot.below
plot.below = []
plot.xaxis[:] = plot.above
self.handles['xaxis'] = plot.xaxis[0]
self.handles['x_range'] = plot.x_range
if self.yaxis is None:
plot.yaxis.visible = False
elif isinstance(self.yaxis, util.basestring) and'right' in self.yaxis:
plot.right = plot.left
plot.left = []
plot.yaxis[:] = plot.right
self.handles['yaxis'] = plot.yaxis[0]
self.handles['y_range'] = plot.y_range
def _axis_properties(self, axis, key, plot, dimension=None,
ax_mapping={'x': 0, 'y': 1}):
"""
Returns a dictionary of axis properties depending
on the specified axis.
"""
# need to copy dictionary by calling dict() on it
axis_props = dict(theme_attr_json(self.renderer.theme, 'Axis'))
if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare', 'bare']) or
(axis == 'y' and self.yaxis in ['left-bare', 'right-bare', 'bare'])):
axis_props['axis_label_text_font_size'] = value('0pt')
axis_props['major_label_text_font_size'] = value('0pt')
axis_props['major_tick_line_color'] = None
axis_props['minor_tick_line_color'] = None
else:
labelsize = self._fontsize('%slabel' % axis).get('fontsize')
if labelsize:
axis_props['axis_label_text_font_size'] = labelsize
ticksize = self._fontsize('%sticks' % axis, common=False).get('fontsize')
if ticksize:
axis_props['major_label_text_font_size'] = value(ticksize)
rotation = self.xrotation if axis == 'x' else self.yrotation
if rotation:
axis_props['major_label_orientation'] = np.radians(rotation)
ticker = self.xticks if axis == 'x' else self.yticks
if isinstance(ticker, Ticker):
axis_props['ticker'] = ticker
elif isinstance(ticker, int):
axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker)
elif isinstance(ticker, (tuple, list)):
if all(isinstance(t, tuple) for t in ticker):
ticks, labels = zip(*ticker)
# Ensure floats which are integers are serialized as ints
# because in JS the lookup fails otherwise
ticks = [int(t) if isinstance(t, float) and t.is_integer() else t
for t in ticks]
labels = [l if isinstance(l, util.basestring) else str(l)
for l in labels]
axis_props['ticker'] = FixedTicker(ticks=ticks)
axis_props['major_label_overrides'] = dict(zip(ticks, labels))
else:
axis_props['ticker'] = FixedTicker(ticks=ticker)
formatter = self.xformatter if axis == 'x' else self.yformatter
if formatter:
formatter = wrap_formatter(formatter, axis)
if formatter is not None:
axis_props['formatter'] = formatter
elif FuncTickFormatter is not None and ax_mapping and isinstance(dimension, Dimension):
formatter = None
if dimension.value_format:
formatter = dimension.value_format
elif dimension.type in dimension.type_formatters:
formatter = dimension.type_formatters[dimension.type]
if formatter:
msg = ('%s dimension formatter could not be '
'converted to tick formatter. ' % dimension.name)
jsfunc = py2js_tickformatter(formatter, msg)
if jsfunc:
formatter = FuncTickFormatter(code=jsfunc)
axis_props['formatter'] = formatter
if axis == 'x':
axis_obj = plot.xaxis[0]
elif axis == 'y':
axis_obj = plot.yaxis[0]
if self.geographic and self.projection == 'mercator':
dimension = 'lon' if axis == 'x' else 'lat'
axis_props['ticker'] = MercatorTicker(dimension=dimension)
axis_props['formatter'] = MercatorTickFormatter(dimension=dimension)
box_zoom = self.state.select(type=tools.BoxZoomTool)
if box_zoom:
box_zoom[0].match_aspect = True
elif isinstance(axis_obj, CategoricalAxis):
for key in list(axis_props):
if key.startswith('major_label'):
# set the group labels equal to major (actually minor)
new_key = key.replace('major_label', 'group')
axis_props[new_key] = axis_props[key]
# major ticks are actually minor ticks in a categorical
# so if user inputs minor ticks sizes, then use that;
# else keep major (group) == minor (subgroup)
msize = self._fontsize('minor_{0}ticks'.format(axis),
common=False).get('fontsize')
if msize is not None:
axis_props['major_label_text_font_size'] = msize
return axis_props
def _update_plot(self, key, plot, element=None):
"""
Updates plot parameters on every frame
"""
plot.update(**self._plot_properties(key, element))
self._update_labels(key, plot, element)
self._update_title(key, plot, element)
self._update_grid(plot)
def _update_labels(self, key, plot, element):
el = element.traverse(lambda x: x, [Element])
el = el[0] if el else element
dimensions = self._get_axis_dims(el)
props = {axis: self._axis_properties(axis, key, plot, dim)
for axis, dim in zip(['x', 'y'], dimensions)}
xlabel, ylabel, zlabel = self._get_axis_labels(dimensions)
if self.invert_axes:
xlabel, ylabel = ylabel, xlabel
props['x']['axis_label'] = xlabel if 'x' in self.labelled or self.xlabel else ''
props['y']['axis_label'] = ylabel if 'y' in self.labelled or self.ylabel else ''
recursive_model_update(plot.xaxis[0], props.get('x', {}))
recursive_model_update(plot.yaxis[0], props.get('y', {}))
def _update_title(self, key, plot, element):
if plot.title:
plot.title.update(**self._title_properties(key, plot, element))
else:
plot.title = Title(**self._title_properties(key, plot, element))
def _update_grid(self, plot):
if not self.show_grid:
plot.xgrid.grid_line_color = None
plot.ygrid.grid_line_color = None
return
replace = ['bounds', 'bands', 'visible', 'level', 'ticker', 'visible']
style_items = list(self.gridstyle.items())
both = {k: v for k, v in style_items if k.startswith('grid_') or k.startswith('minor_grid')}
xgrid = {k.replace('xgrid', 'grid'): v for k, v in style_items if 'xgrid' in k}
ygrid = {k.replace('ygrid', 'grid'): v for k, v in style_items if 'ygrid' in k}
xopts = {k.replace('grid_', '') if any(r in k for r in replace) else k: v
for k, v in dict(both, **xgrid).items()}
yopts = {k.replace('grid_', '') if any(r in k for r in replace) else k: v
for k, v in dict(both, **ygrid).items()}
if plot.xaxis and 'ticker' not in xopts:
xopts['ticker'] = plot.xaxis[0].ticker
if plot.yaxis and 'ticker' not in yopts:
yopts['ticker'] = plot.yaxis[0].ticker
plot.xgrid[0].update(**xopts)
plot.ygrid[0].update(**yopts)
def _update_ranges(self, element, ranges):
plot = self.handles['plot']
x_range = self.handles['x_range']
y_range = self.handles['y_range']
l, b, r, t = None, None, None, None
if any(isinstance(r, (Range1d, DataRange1d)) for r in [x_range, y_range]):
l, b, r, t = self.get_extents(element, ranges)
if self.invert_axes:
l, b, r, t = b, l, t, r
xfactors, yfactors = None, None
if any(isinstance(ax_range, FactorRange) for ax_range in [x_range, y_range]):
xfactors, yfactors = self._get_factors(element, ranges)
framewise = self.framewise
streaming = (self.streaming and any(stream._triggering and stream.following
for stream in self.streaming))
xupdate = ((not (self.model_changed(x_range) or self.model_changed(plot))
and (framewise or streaming))
or xfactors is not None)
yupdate = ((not (self.model_changed(x_range) or self.model_changed(plot))
and (framewise or streaming))
or yfactors is not None)
options = self._traverse_options(element, 'plot', ['width', 'height'], defaults=False)
fixed_width = (self.frame_width or options['width'])
fixed_height = (self.frame_height or options['height'])
data_aspect = (self.aspect == 'equal' or self.data_aspect)
xaxis, yaxis = self.handles['xaxis'], self.handles['yaxis']
categorical = isinstance(xaxis, CategoricalAxis) or isinstance(yaxis, CategoricalAxis)
datetime = isinstance(xaxis, DatetimeAxis) or isinstance(yaxis, CategoricalAxis)
if data_aspect and (categorical or datetime):
ax_type = 'categorical' if categorical else 'datetime axes'
self.param.warning('Cannot set data_aspect if one or both '
'axes are %s, the option will '
'be ignored.' % ax_type)
elif data_aspect:
plot = self.handles['plot']
xspan = r-l if util.is_number(l) and util.is_number(r) else None
yspan = t-b if util.is_number(b) and util.is_number(t) else None
if self.drawn or (fixed_width and fixed_height):
# After initial draw or if aspect is explicit
# adjust range to match the plot dimension aspect
ratio = self.data_aspect or 1
if self.aspect == 'square':
frame_aspect = 1
elif self.aspect and self.aspect != 'equal':
frame_aspect = self.aspect
else:
frame_aspect = plot.frame_height/plot.frame_width
desired_xspan = yspan*(ratio/frame_aspect)
desired_yspan = xspan/(ratio/frame_aspect)
if ((np.allclose(desired_xspan, xspan, rtol=0.01) and
np.allclose(desired_yspan, yspan, rtol=0.01)) or
not (util.isfinite(xspan) and util.isfinite(yspan))):
pass
elif desired_yspan >= yspan:
ypad = (desired_yspan-yspan)/2.
b, t = b-ypad, t+ypad
yupdate = True
else:
xpad = (desired_xspan-xspan)/2.
l, r = l-xpad, r+xpad
xupdate = True
elif not (fixed_height and fixed_width):
# Set initial aspect
aspect = self.get_aspect(xspan, yspan)
width = plot.frame_width or plot.plot_width or 300
height = plot.frame_height or plot.plot_height or 300
if not (fixed_width or fixed_height) and not self.responsive:
fixed_height = True
if fixed_height:
plot.frame_height = height
plot.frame_width = int(height/aspect)
plot.plot_width, plot.plot_height = None, None
elif fixed_width:
plot.frame_width = width
plot.frame_height = int(width*aspect)
plot.plot_width, plot.plot_height = None, None
else:
plot.aspect_ratio = 1./aspect
box_zoom = plot.select(type=tools.BoxZoomTool)
scroll_zoom = plot.select(type=tools.WheelZoomTool)
if box_zoom:
box_zoom.match_aspect = True
if scroll_zoom:
scroll_zoom.zoom_on_axis = False
if not self.drawn or xupdate:
self._update_range(x_range, l, r, xfactors, self.invert_xaxis,
self._shared['x'], self.logx, streaming)
if not self.drawn or yupdate:
self._update_range(y_range, b, t, yfactors, self.invert_yaxis,
self._shared['y'], self.logy, streaming)
def _update_range(self, axis_range, low, high, factors, invert, shared, log, streaming=False):
if isinstance(axis_range, (Range1d, DataRange1d)) and self.apply_ranges:
if isinstance(low, util.cftime_types):
pass
elif (low == high and low is not None):
if isinstance(low, util.datetime_types):
offset = np.timedelta64(500, 'ms')
low, high = np.datetime64(low), np.datetime64(high)
low -= offset
high += offset
else:
offset = abs(low*0.1 if low else 0.5)
low -= offset
high += offset
if shared:
shared = (axis_range.start, axis_range.end)
low, high = util.max_range([(low, high), shared])
if invert: low, high = high, low
if not isinstance(low, util.datetime_types) and log and (low is None or low <= 0):
low = 0.01 if high < 0.01 else 10**(np.log10(high)-2)
self.param.warning(
"Logarithmic axis range encountered value less "
"than or equal to zero, please supply explicit "
"lower-bound to override default of %.3f." % low)
updates = {}
if util.isfinite(low):
updates['start'] = (axis_range.start, low)
updates['reset_start'] = updates['start']
if util.isfinite(high):
updates['end'] = (axis_range.end, high)
updates['reset_end'] = updates['end']
for k, (old, new) in updates.items():
if isinstance(new, util.cftime_types):
new = date_to_integer(new)
axis_range.update(**{k:new})
if streaming and not k.startswith('reset_'):
axis_range.trigger(k, old, new)
elif isinstance(axis_range, FactorRange):
factors = list(decode_bytes(factors))
if invert: factors = factors[::-1]
axis_range.factors = factors
def _categorize_data(self, data, cols, dims):
"""
Transforms non-string or integer types in datasource if the
axis to be plotted on is categorical. Accepts the column data
source data, the columns corresponding to the axes and the
dimensions for each axis, changing the data inplace.
"""
if self.invert_axes:
cols = cols[::-1]
dims = dims[:2][::-1]
ranges = [self.handles['%s_range' % ax] for ax in 'xy']
for i, col in enumerate(cols):
column = data[col]
if (isinstance(ranges[i], FactorRange) and
(isinstance(column, list) or column.dtype.kind not in 'SU')):
data[col] = [dims[i].pprint_value(v) for v in column]
def get_aspect(self, xspan, yspan):
"""
Computes the aspect ratio of the plot
"""
if self.data_aspect:
return (yspan/xspan)*self.data_aspect
elif self.aspect == 'equal':
return yspan/xspan
elif self.aspect == 'square':
return 1
elif self.aspect is not None:
return self.aspect
elif self.width is not None and self.height is not None:
return self.width/self.height
else:
return 1
def _get_factors(self, element, ranges):
"""
Get factors for categorical axes.
"""
xdim, ydim = element.dimensions()[:2]
xvals = np.asarray(xdim.values or element.dimension_values(0, False))
yvals = np.asarray(ydim.values or element.dimension_values(1, False))
coords = tuple([v if vals.dtype.kind in 'SU' else dim.pprint_value(v) for v in vals]
for dim, vals in [(xdim, xvals), (ydim, yvals)])
if self.invert_axes: coords = coords[::-1]
return coords
def _process_legend(self):
"""
Disables legends if show_legend is disabled.
"""
for l in self.handles['plot'].legend:
l.items[:] = []
l.border_line_alpha = 0
l.background_fill_alpha = 0
def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
properties = mpl_to_bokeh(properties)
plot_method = self._plot_methods.get('batched' if self.batched else 'single')
if isinstance(plot_method, tuple):
# Handle alternative plot method for flipped axes
plot_method = plot_method[int(self.invert_axes)]
renderer = getattr(plot, plot_method)(**dict(properties, **mapping))
return renderer, renderer.glyph
def _apply_transforms(self, element, data, ranges, style, group=None):
new_style = dict(style)
prefix = group+'_' if group else ''
for k, v in dict(style).items():
if isinstance(v, util.basestring):
if validate(k, v) == True:
continue
elif v in element or (isinstance(element, Graph) and v in element.nodes):
v = dim(v)
elif any(d==v for d in self.overlay_dims):
v = dim([d for d in self.overlay_dims if d==v][0])
if (not isinstance(v, dim) or (group is not None and not k.startswith(group))):
continue
elif (not v.applies(element) and v.dimension not in self.overlay_dims):
new_style.pop(k)
self.param.warning(
'Specified %s dim transform %r could not be applied, '
'as not all dimensions could be resolved.' % (k, v))
continue
if v.dimension in self.overlay_dims:
ds = Dataset({d.name: v for d, v in self.overlay_dims.items()},
list(self.overlay_dims))
val = v.apply(ds, ranges=ranges, flat=True)[0]
elif isinstance(element, Path) and not isinstance(element, Contours):
val = np.concatenate([v.apply(el, ranges=ranges, flat=True)[:-1]
for el in element.split()])
else:
val = v.apply(element, ranges=ranges, flat=True)
if (not util.isscalar(val) and len(util.unique_array(val)) == 1 and
((not 'color' in k or validate('color', val)) or k in self._nonvectorized_styles)):
val = val[0]
if not util.isscalar(val):
if k in self._nonvectorized_styles:
element = type(element).__name__
raise ValueError('Mapping a dimension to the "{style}" '
'style option is not supported by the '
'{element} element using the {backend} '
'backend. To map the "{dim}" dimension '
'to the {style} use a groupby operation '