/
plot.py
760 lines (634 loc) · 29.7 KB
/
plot.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
from itertools import groupby
import numpy as np
import param
from bokeh.models import (ColumnDataSource, VBox, HBox, Column, Div)
from bokeh.models.widgets import Panel, Tabs
from ...core import (OrderedDict, CompositeOverlay, Store, Layout, GridMatrix,
AdjointLayout, NdLayout, Empty, GridSpace, HoloMap)
from ...core import traversal
from ...core.options import Compositor, SkipRendering
from ...core.util import basestring, wrap_tuple, unique_iterator
from ...element import Histogram
from ..plot import (DimensionedPlot, GenericCompositePlot, GenericLayoutPlot,
GenericElementPlot)
from ..util import get_dynamic_mode, initialize_sampled
from .renderer import BokehRenderer
from .util import (bokeh_version, layout_padding, pad_plots,
filter_toolboxes, make_axis)
if bokeh_version >= '0.12':
from bokeh.layouts import gridplot
else:
from bokeh.models import GridPlot as BokehGridPlot
from bokeh.plotting.helpers import _known_tools as known_tools
TOOLS = {name: tool if isinstance(tool, basestring) else type(tool())
for name, tool in known_tools.items()}
class BokehPlot(DimensionedPlot):
"""
Plotting baseclass for the Bokeh backends, implementing the basic
plotting interface for Bokeh based plots.
"""
width = param.Integer(default=300, doc="""
Width of the plot in pixels""")
height = param.Integer(default=300, doc="""
Height of the plot in pixels""")
shared_datasource = param.Boolean(default=True, doc="""
Whether Elements drawing the data from the same object should
share their Bokeh data source allowing for linked brushing
and other linked behaviors.""")
title_format = param.String(default="{label} {group} {dimensions}", doc="""
The formatting string for the title of this plot, allows defining
a label group separator and dimension labels.""")
backend = 'bokeh'
@property
def document(self):
return self._document
@document.setter
def document(self, doc):
self._document = doc
if self.subplots:
for plot in self.subplots.values():
plot.document = doc
def __init__(self, *args, **params):
super(BokehPlot, self).__init__(*args, **params)
self._document = None
self.root = None
def get_data(self, element, ranges=None, empty=False):
"""
Returns the data from an element in the appropriate format for
initializing or updating a ColumnDataSource and a dictionary
which maps the expected keywords arguments of a glyph to
the column in the datasource.
"""
raise NotImplementedError
def push(self):
"""
Pushes updated plot data via the Comm.
"""
if self.renderer.mode == 'server':
return
if self.comm is None:
raise Exception('Renderer does not have a comm.')
diff = self.renderer.diff(self)
self.comm.send(diff)
def set_root(self, root):
"""
Sets the current document on all subplots.
"""
for plot in self.traverse(lambda x: x):
plot.root = root
def _init_datasource(self, data):
"""
Initializes a data source to be passed into the bokeh glyph.
"""
return ColumnDataSource(data=data)
def _update_datasource(self, source, data):
"""
Update datasource with data for a new frame.
"""
source.data.update(data)
@property
def state(self):
"""
The plotting state that gets updated via the update method and
used by the renderer to generate output.
"""
return self.handles['plot']
@property
def current_handles(self):
"""
Should return a list of plot objects that have changed and
should be updated.
"""
return []
def _fontsize(self, key, label='fontsize', common=True):
"""
Converts integer fontsizes to a string specifying
fontsize in pt.
"""
size = super(BokehPlot, self)._fontsize(key, label, common)
return {k: v if isinstance(v, basestring) else '%spt' % v
for k, v in size.items()}
def sync_sources(self):
"""
Syncs data sources between Elements, which draw data
from the same object.
"""
get_sources = lambda x: (id(x.current_frame.data), x)
filter_fn = lambda x: (x.shared_datasource and x.current_frame and
not isinstance(x.current_frame.data, np.ndarray)
and 'source' in x.handles)
data_sources = self.traverse(get_sources, [filter_fn])
grouped_sources = groupby(sorted(data_sources, key=lambda x: x[0]), lambda x: x[0])
for _, group in grouped_sources:
group = list(group)
if len(group) > 1:
source_data = {}
for _, plot in group:
source_data.update(plot.handles['source'].data)
new_source = ColumnDataSource(source_data)
for _, plot in group:
renderer = plot.handles.get('glyph_renderer')
if renderer is None:
continue
elif 'data_source' in renderer.properties():
renderer.update(data_source=new_source)
else:
renderer.update(source=new_source)
plot.handles['source'] = new_source
class CompositePlot(BokehPlot):
"""
CompositePlot is an abstract baseclass for plot types that draw
render multiple axes. It implements methods to add an overall title
to such a plot.
"""
fontsize = param.Parameter(default={'title': '16pt'}, 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:
{'title': '15pt'}""")
_title_template = "<span style='font-size: {fontsize}'><b>{title}</b></font>"
_merged_tools = ['pan', 'box_zoom', 'box_select', 'lasso_select',
'poly_select', 'ypan', 'xpan']
def _update_callbacks(self, plot):
"""
Iterates over all subplots and updates existing CustomJS
callbacks with models that were replaced when compositing subplots
into a CompositePlot
"""
subplots = self.traverse(lambda x: x, [GenericElementPlot])
merged_tools = {t: list(plot.select({'type': TOOLS[t]}))
for t in self._merged_tools}
for subplot in subplots:
for cb in subplot.callbacks:
for c in cb.callbacks:
for tool, objs in merged_tools.items():
if tool in c.args and objs:
c.args[tool] = objs[0]
def _get_title(self, key):
title_div = None
title = self._format_title(key) if self.show_title else ''
if title:
fontsize = self._fontsize('title')
title_tags = self._title_template.format(title=title,
**fontsize)
if 'title' in self.handles:
title_div = self.handles['title']
else:
title_div = Div()
title_div.text = title_tags
return title_div
@property
def current_handles(self):
"""
Should return a list of plot objects that have changed and
should be updated.
"""
return [self.handles['title']] if 'title' in self.handles else []
class GridPlot(CompositePlot, GenericCompositePlot):
"""
Plot a group of elements in a grid layout based on a GridSpace element
object.
"""
axis_offset = param.Integer(default=50, doc="""
Number of pixels to adjust row and column widths and height by
to compensate for shared axes.""")
fontsize = param.Parameter(default={'title': '16pt'},
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:
{'title': '15pt'}""")
shared_xaxis = param.Boolean(default=False, doc="""
If enabled the x-axes of the GridSpace will be drawn from the
objects inside the Grid rather than the GridSpace dimensions.""")
shared_yaxis = param.Boolean(default=False, doc="""
If enabled the x-axes of the GridSpace will be drawn from the
objects inside the Grid rather than the GridSpace dimensions.""")
xaxis = param.ObjectSelector(default=True,
objects=['bottom', 'top', None, True, False], doc="""
Whether and where to display the xaxis, supported options are
'bottom', 'top' and None.""")
yaxis = param.ObjectSelector(default=True,
objects=['left', 'right', None, True, False], doc="""
Whether and where to display the yaxis, supported options are
'left', 'right' and None.""")
xrotation = param.Integer(default=0, bounds=(0, 360), doc="""
Rotation angle of the xticks.""")
yrotation = param.Integer(default=0, bounds=(0, 360), doc="""
Rotation angle of the yticks.""")
plot_size = param.Integer(default=120, doc="""
Defines the width and height of each plot in the grid""")
def __init__(self, layout, ranges=None, layout_num=1, **params):
if not isinstance(layout, GridSpace):
raise Exception("GridPlot only accepts GridSpace.")
super(GridPlot, self).__init__(layout=layout, layout_num=layout_num,
ranges=ranges, **params)
self.cols, self.rows = layout.shape
self.subplots, self.layout = self._create_subplots(layout, ranges)
def _create_subplots(self, layout, ranges):
layout = layout.map(Compositor.collapse_element, [CompositeOverlay],
clone=False)
subplots = OrderedDict()
frame_ranges = self.compute_ranges(layout, None, ranges)
frame_ranges = OrderedDict([(key, self.compute_ranges(layout, key, frame_ranges))
for key in self.keys])
collapsed_layout = layout.clone(shared_data=False, id=layout.id)
for i, coord in enumerate(layout.keys(full_grid=True)):
r = i % self.rows
c = i // self.rows
if not isinstance(coord, tuple): coord = (coord,)
view = layout.data.get(coord, None)
# Create subplot
if view is not None:
vtype = view.type if isinstance(view, HoloMap) else view.__class__
opts = self.lookup_options(view, 'plot').options
else:
vtype = None
# Create axes
offset = self.axis_offset
kwargs = {}
if c == 0 and r != 0:
kwargs['xaxis'] = None
kwargs['width'] = self.plot_size+offset
if c != 0 and r == 0:
kwargs['yaxis'] = None
kwargs['height'] = self.plot_size+offset
if c == 0 and r == 0:
kwargs['width'] = self.plot_size+offset
kwargs['height'] = self.plot_size+offset
if r != 0 and c != 0:
kwargs['xaxis'] = None
kwargs['yaxis'] = None
if 'width' not in kwargs or not self.shared_yaxis:
kwargs['width'] = self.plot_size
if 'height' not in kwargs or not self.shared_xaxis:
kwargs['height'] = self.plot_size
if 'border' not in kwargs:
kwargs['border'] = 3
kwargs['show_legend'] = False
if not self.shared_xaxis:
kwargs['xaxis'] = None
if not self.shared_yaxis:
kwargs['yaxis'] = None
if isinstance(layout, GridMatrix):
if view.traverse(lambda x: x, [Histogram]):
kwargs['shared_axes'] = False
# Create subplot
plotting_class = Store.registry[self.renderer.backend].get(vtype, None)
if plotting_class is None:
if view is not None:
self.warning("Bokeh plotting class for %s type not found, "
"object will not be rendered." % vtype.__name__)
else:
subplot = plotting_class(view, dimensions=self.dimensions,
show_title=False, subplot=True,
renderer=self.renderer,
ranges=frame_ranges, uniform=self.uniform,
keys=self.keys, **dict(opts, **kwargs))
collapsed_layout[coord] = (subplot.layout
if isinstance(subplot, GenericCompositePlot)
else subplot.hmap)
subplots[coord] = subplot
return subplots, collapsed_layout
def initialize_plot(self, ranges=None, plots=[]):
ranges = self.compute_ranges(self.layout, self.keys[-1], None)
passed_plots = list(plots)
plots = [[None for c in range(self.cols)] for r in range(self.rows)]
for i, coord in enumerate(self.layout.keys(full_grid=True)):
r = i % self.rows
c = i // self.rows
subplot = self.subplots.get(wrap_tuple(coord), None)
if subplot is not None:
plot = subplot.initialize_plot(ranges=ranges, plots=passed_plots)
plots[r][c] = plot
passed_plots.append(plot)
else:
passed_plots.append(None)
if bokeh_version < '0.12':
plot = BokehGridPlot(children=plots[::-1])
else:
plot = gridplot(plots[::-1])
plot = self._make_axes(plot)
title = self._get_title(self.keys[-1])
if title:
plot = Column(title, plot)
self.handles['title'] = title
self._update_callbacks(plot)
self.handles['plot'] = plot
self.handles['plots'] = plots
if self.shared_datasource:
self.sync_sources()
self.drawn = True
return self.handles['plot']
def _make_axes(self, plot):
width, height = self.renderer.get_size(plot)
x_axis, y_axis = None, None
if self.xaxis:
flip = self.shared_xaxis
rotation = self.xrotation
lsize = self._fontsize('xlabel').get('fontsize')
tsize = self._fontsize('xticks', common=False).get('fontsize')
xfactors = list(unique_iterator(self.layout.dimension_values(0)))
x_axis = make_axis('x', width, xfactors, self.layout.kdims[0],
flip=flip, rotation=rotation, label_size=lsize,
tick_size=tsize)
if self.yaxis and self.layout.ndims > 1:
flip = self.shared_yaxis
rotation = self.yrotation
lsize = self._fontsize('ylabel').get('fontsize')
tsize = self._fontsize('yticks', common=False).get('fontsize')
yfactors = list(unique_iterator(self.layout.dimension_values(1)))
y_axis = make_axis('y', height, yfactors, self.layout.kdims[1],
flip=flip, rotation=rotation, label_size=lsize,
tick_size=tsize)
if x_axis and y_axis:
plot = filter_toolboxes(plot)
r1, r2 = ([y_axis, plot], [None, x_axis])
if self.shared_xaxis:
r1, r2 = r2, r1
if self.shared_yaxis:
r1, r2 = r1[::-1], r2[::-1]
models = layout_padding([r1, r2], self.renderer)
plot = gridplot(models)
elif y_axis:
models = [y_axis, plot]
if self.shared_yaxis: models = models[::-1]
plot = Row(*models)
elif x_axis:
models = [plot, x_axis]
if self.shared_xaxis: models = models[::-1]
plot = Column(*models)
return plot
def update_frame(self, key, ranges=None):
"""
Update the internal state of the Plot to represent the given
key tuple (where integers represent frames). Returns this
state.
"""
ranges = self.compute_ranges(self.layout, key, ranges)
for coord in self.layout.keys(full_grid=True):
subplot = self.subplots.get(coord, None)
if subplot is not None:
subplot.update_frame(key, ranges)
title = self._get_title(key)
if title:
self.handles['title']
class LayoutPlot(CompositePlot, GenericLayoutPlot):
shared_axes = param.Boolean(default=True, doc="""
Whether axes should be shared across plots""")
shared_datasource = param.Boolean(default=False, doc="""
Whether Elements drawing the data from the same object should
share their Bokeh data source allowing for linked brushing
and other linked behaviors.""")
tabs = param.Boolean(default=False, doc="""
Whether to display overlaid plots in separate panes""")
def __init__(self, layout, **params):
super(LayoutPlot, self).__init__(layout, **params)
self.layout, self.subplots, self.paths = self._init_layout(layout)
def _init_layout(self, layout):
# Situate all the Layouts in the grid and compute the gridspec
# indices for all the axes required by each LayoutPlot.
layout_count = 0
collapsed_layout = layout.clone(shared_data=False, id=layout.id)
frame_ranges = self.compute_ranges(layout, None, None)
frame_ranges = OrderedDict([(key, self.compute_ranges(layout, key, frame_ranges))
for key in self.keys])
layout_items = layout.grid_items()
layout_dimensions = layout.kdims if isinstance(layout, NdLayout) else None
layout_subplots, layouts, paths = {}, {}, {}
for r, c in self.coords:
# Get view at layout position and wrap in AdjointLayout
key, view = layout_items.get((c, r) if self.transpose else (r, c), (None, None))
view = view if isinstance(view, AdjointLayout) else AdjointLayout([view])
layouts[(r, c)] = view
paths[r, c] = key
# Compute the layout type from shape
layout_lens = {1:'Single', 2:'Dual', 3: 'Triple'}
layout_type = layout_lens.get(len(view), 'Single')
# Get the AdjoinLayout at the specified coordinate
positions = AdjointLayoutPlot.layout_dict[layout_type]['positions']
# Create temporary subplots to get projections types
# to create the correct subaxes for all plots in the layout
layout_key, _ = layout_items.get((r, c), (None, None))
if isinstance(layout, NdLayout) and layout_key:
layout_dimensions = OrderedDict(zip(layout_dimensions, layout_key))
# Generate the axes and create the subplots with the appropriate
# axis objects, handling any Empty objects.
obj = layouts[(r, c)]
empty = isinstance(obj.main, Empty)
if empty:
obj = AdjointLayout([])
else:
layout_count += 1
subplot_data = self._create_subplots(obj, positions,
layout_dimensions, frame_ranges,
num=0 if empty else layout_count)
subplots, adjoint_layout = subplot_data
# Generate the AdjointLayoutsPlot which will coordinate
# plotting of AdjointLayouts in the larger grid
plotopts = self.lookup_options(view, 'plot').options
layout_plot = AdjointLayoutPlot(adjoint_layout, layout_type, subplots, **plotopts)
layout_subplots[(r, c)] = layout_plot
if layout_key:
collapsed_layout[layout_key] = adjoint_layout
return collapsed_layout, layout_subplots, paths
def _create_subplots(self, layout, positions, layout_dimensions, ranges, num=0):
"""
Plot all the views contained in the AdjointLayout Object using axes
appropriate to the layout configuration. All the axes are
supplied by LayoutPlot - the purpose of the call is to
invoke subplots with correct options and styles and hide any
empty axes as necessary.
"""
subplots = {}
adjoint_clone = layout.clone(shared_data=False, id=layout.id)
main_plot = None
for pos in positions:
# Pos will be one of 'main', 'top' or 'right' or None
element = layout.get(pos, None)
if element is None:
continue
subplot_opts = dict(adjoined=main_plot)
# Options common for any subplot
vtype = element.type if isinstance(element, HoloMap) else element.__class__
plot_type = Store.registry[self.renderer.backend].get(vtype, None)
plotopts = self.lookup_options(element, 'plot').options
side_opts = {}
if pos != 'main':
plot_type = AdjointLayoutPlot.registry.get(vtype, plot_type)
if pos == 'right':
yaxis = 'right-bare' if 'bare' in plot_type.yaxis else 'right'
side_opts = dict(height=main_plot.height, yaxis=yaxis,
width=plot_type.width, invert_axes=True,
labelled=['y'], xticks=1, xaxis=main_plot.xaxis)
else:
xaxis = 'top-bare' if 'bare' in plot_type.xaxis else 'top'
side_opts = dict(width=main_plot.width, xaxis=xaxis,
height=plot_type.height, labelled=['x'],
yticks=1, yaxis=main_plot.yaxis)
# Override the plotopts as required
# Customize plotopts depending on position.
plotopts = dict(side_opts, **plotopts)
plotopts.update(subplot_opts)
if plot_type is None:
self.warning("Bokeh plotting class for %s type not found, object will "
"not be rendered." % vtype.__name__)
continue
num = num if len(self.coords) > 1 else 0
subplot = plot_type(element, keys=self.keys,
dimensions=self.dimensions,
layout_dimensions=layout_dimensions,
ranges=ranges, subplot=True,
uniform=self.uniform, layout_num=num,
renderer=self.renderer,
**dict({'shared_axes': self.shared_axes},
**plotopts))
subplots[pos] = subplot
if isinstance(plot_type, type) and issubclass(plot_type, GenericCompositePlot):
adjoint_clone[pos] = subplots[pos].layout
else:
adjoint_clone[pos] = subplots[pos].hmap
if pos == 'main':
main_plot = subplot
return subplots, adjoint_clone
def initialize_plot(self, plots=None, ranges=None):
ranges = self.compute_ranges(self.layout, self.keys[-1], None)
passed_plots = [] if plots is None else plots
plots = [[] for _ in range(self.rows)]
tab_titles = {}
insert_rows, insert_cols = [], []
adjoined = False
for r, c in self.coords:
subplot = self.subplots.get((r, c), None)
if subplot is not None:
shared_plots = passed_plots if self.shared_axes else None
subplots = subplot.initialize_plot(ranges=ranges, plots=shared_plots)
# Computes plotting offsets depending on
# number of adjoined plots
offset = sum(r >= ir for ir in insert_rows)
if len(subplots) > 2:
adjoined = True
# Add pad column in this position
insert_cols.append(c)
if r not in insert_rows:
# Insert and pad marginal row if none exists
plots.insert(r+offset, [None for _ in range(len(plots[r]))])
# Pad previous rows
for ir in range(r):
plots[ir].insert(c+1, None)
# Add to row offset
insert_rows.append(r)
offset += 1
# Add top marginal
plots[r+offset-1] += [subplots.pop(-1), None]
elif len(subplots) > 1:
adjoined = True
# Add pad column in this position
insert_cols.append(c)
# Pad previous rows
for ir in range(r):
plots[r].insert(c+1, None)
# Pad top marginal if one exists
if r in insert_rows:
plots[r+offset-1] += 2*[None]
else:
# Pad top marginal if one exists
if r in insert_rows:
plots[r+offset-1] += [None] * (1+(c in insert_cols))
plots[r+offset] += subplots
if len(subplots) == 1 and c in insert_cols:
plots[r+offset].append(None)
passed_plots.append(subplots[0])
if self.tabs:
if isinstance(self.layout, Layout):
tab_titles[r, c] = ' '.join(self.paths[r,c])
else:
dim_vals = zip(self.layout.kdims, self.paths[r, c])
tab_titles[r, c] = ', '.join([d.pprint_value_string(k)
for d, k in dim_vals])
# Replace None types with empty plots
# to avoid bokeh bug
if adjoined:
plots = layout_padding(plots, self.renderer)
# Wrap in appropriate layout model
if self.tabs:
panels = [Panel(child=child, title=str(tab_titles.get((r, c))))
for r, row in enumerate(plots)
for c, child in enumerate(row)
if child is not None]
layout_plot = Tabs(tabs=panels)
elif bokeh_version >= '0.12':
plots = filter_toolboxes(plots)
plots, width = pad_plots(plots)
layout_plot = gridplot(children=plots, width=width)
elif len(plots) == 1 and not adjoined:
layout_plot = VBox(children=[HBox(children=plots[0])])
elif len(plots[0]) == 1:
layout_plot = VBox(children=[p[0] for p in plots])
else:
layout_plot = BokehGridPlot(children=plots)
title = self._get_title(self.keys[-1])
if title:
self.handles['title'] = title
layout_plot = Column(title, layout_plot)
self._update_callbacks(layout_plot)
self.handles['plot'] = layout_plot
self.handles['plots'] = plots
if self.shared_datasource:
self.sync_sources()
self.drawn = True
return self.handles['plot']
def update_frame(self, key, ranges=None):
"""
Update the internal state of the Plot to represent the given
key tuple (where integers represent frames). Returns this
state.
"""
ranges = self.compute_ranges(self.layout, key, ranges)
for r, c in self.coords:
subplot = self.subplots.get((r, c), None)
if subplot is not None:
subplot.update_frame(key, ranges)
title = self._get_title(key)
if title:
self.handles['title'] = title
class AdjointLayoutPlot(BokehPlot):
layout_dict = {'Single': {'positions': ['main']},
'Dual': {'positions': ['main', 'right']},
'Triple': {'positions': ['main', 'right', 'top']}}
registry = {}
def __init__(self, layout, layout_type, subplots, **params):
# The AdjointLayout ViewableElement object
self.layout = layout
# Type may be set to 'Embedded Dual' by a call it grid_situate
self.layout_type = layout_type
self.view_positions = self.layout_dict[self.layout_type]['positions']
# The supplied (axes, view) objects as indexed by position
super(AdjointLayoutPlot, self).__init__(subplots=subplots, **params)
def initialize_plot(self, ranges=None, plots=[]):
"""
Plot all the views contained in the AdjointLayout Object using axes
appropriate to the layout configuration. All the axes are
supplied by LayoutPlot - the purpose of the call is to
invoke subplots with correct options and styles and hide any
empty axes as necessary.
"""
if plots is None: plots = []
adjoined_plots = []
for pos in ['main', 'right', 'top']:
# Pos will be one of 'main', 'top' or 'right' or None
subplot = self.subplots.get(pos, None)
# If no view object or empty position, disable the axis
if subplot:
passed_plots = plots + adjoined_plots
adjoined_plots.append(subplot.initialize_plot(ranges=ranges, plots=passed_plots))
self.drawn = True
if not adjoined_plots: adjoined_plots = [None]
return adjoined_plots
def update_frame(self, key, ranges=None):
plot = None
for pos in ['main', 'right', 'top']:
subplot = self.subplots.get(pos)
if subplot is not None:
plot = subplot.update_frame(key, ranges)
return plot