/
plotly.ts
429 lines (371 loc) · 13.8 KB
/
plotly.ts
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
import * as p from "@bokehjs/core/properties"
import {div} from "@bokehjs/core/dom"
import {clone} from "@bokehjs/core/util/object"
import {isEqual} from "@bokehjs/core/util/eq"
import {HTMLBox} from "@bokehjs/models/layouts/html_box"
import {ColumnDataSource} from "@bokehjs/models/sources/column_data_source";
import {debounce} from "debounce"
import {deepCopy, isPlainObject, get, throttle} from "./util"
import {PanelHTMLBoxView, set_size} from "./layout"
interface PlotlyHTMLElement extends HTMLDivElement {
_fullLayout: any
layout: any;
on(event: 'plotly_relayout', callback: (eventData: any) => void): void;
on(event: 'plotly_relayouting', callback: (eventData: any) => void): void;
on(event: 'plotly_restyle', callback: (eventData: any) => void): void;
on(event: 'plotly_click', callback: (eventData: any) => void): void;
on(event: 'plotly_hover', callback: (eventData: any) => void): void;
on(event: 'plotly_clickannotation', callback: (eventData: any) => void): void;
on(event: 'plotly_selected', callback: (eventData: any) => void): void;
on(event: 'plotly_deselect', callback: () => void): void;
on(event: 'plotly_unhover', callback: () => void): void;
}
const filterEventData = (gd: any, eventData: any, event: string) => {
// Ported from dash-core-components/src/components/Graph.react.js
let filteredEventData: {[k: string]: any} = Array.isArray(eventData)? []: {};
if (event === "click" || event === "hover" || event === "selected") {
const points = [];
if (eventData === undefined || eventData === null) {
return null;
}
/*
* remove `data`, `layout`, `xaxis`, etc
* objects from the event data since they're so big
* and cause JSON stringify ciricular structure errors.
*
* also, pull down the `customdata` point from the data array
* into the event object
*/
const data = gd.data;
for (let i = 0; i < eventData.points.length; i++) {
const fullPoint = eventData.points[i];
let pointData: {[k: string]: any} = {};
for (let property in fullPoint) {
const val = fullPoint[property];
if (fullPoint.hasOwnProperty(property) &&
!Array.isArray(val) && !isPlainObject(val)) {
pointData[property] = val;
}
}
if (fullPoint !== undefined && fullPoint !== null) {
if(fullPoint.hasOwnProperty("curveNumber") &&
fullPoint.hasOwnProperty("pointNumber") &&
data[fullPoint["curveNumber"]].hasOwnProperty("customdata")) {
pointData["customdata"] =
data[fullPoint["curveNumber"]].customdata[
fullPoint["pointNumber"]
]
}
// specific to histogram. see https://github.com/plotly/plotly.js/pull/2113/
if (fullPoint.hasOwnProperty('pointNumbers')) {
pointData["pointNumbers"] = fullPoint.pointNumbers;
}
}
points[i] = pointData;
}
filteredEventData["points"] = points;
} else if (event === 'relayout' || event === 'restyle') {
/*
* relayout shouldn't include any big objects
* it will usually just contain the ranges of the axes like
* "xaxis.range[0]": 0.7715822247381828,
* "xaxis.range[1]": 3.0095292008680063`
*/
for (let property in eventData) {
if (eventData.hasOwnProperty(property)) {
filteredEventData[property] = eventData[property];
}
}
}
if (eventData.hasOwnProperty('range')) {
filteredEventData["range"] = eventData["range"];
}
if (eventData.hasOwnProperty('lassoPoints')) {
filteredEventData["lassoPoints"] = eventData["lassoPoints"];
}
return filteredEventData;
};
const _isHidden = (gd: any) => {
var display = window.getComputedStyle(gd).display;
return !display || display === 'none';
};
export class PlotlyPlotView extends PanelHTMLBoxView {
model: PlotlyPlot
_setViewport: Function
_settingViewport: boolean = false
_plotInitialized: boolean = false
_reacting: boolean = false
_relayouting: boolean = false
_layout_wrapper: PlotlyHTMLElement
_watched_sources: string[]
_end_relayouting = debounce(() => {
this._relayouting = false
}, 2000, false)
initialize(): void {
super.initialize()
this._layout_wrapper = <PlotlyHTMLElement>div({style: "height: 100%; width: 100%;"})
}
connect_signals(): void {
super.connect_signals();
const {data, data_sources, layout, relayout, restyle} = this.model.properties
this.on_change([data, data_sources, layout], () => {
const render_count = this.model._render_count
setTimeout(() => {
if (this.model._render_count === render_count)
this.model._render_count += 1;
}, 250)
});
this.on_change([relayout], () => {
if (this.model.relayout == null)
return
(window as any).Plotly.relayout(this._layout_wrapper, this.model.relayout)
this.model.relayout = null
})
this.on_change([restyle], () => {
if (this.model.restyle == null)
return
(window as any).Plotly.restyle(this._layout_wrapper, this.model.restyle.data, this.model.restyle.traces)
this.model.restyle = null
})
this.connect(this.model.properties.viewport_update_policy.change, () => {
this._updateSetViewportFunction()
});
this.connect(this.model.properties.viewport_update_throttle.change, () => {
this._updateSetViewportFunction()
});
this.connect(this.model.properties._render_count.change, () => {
this.plot()
});
this.connect(this.model.properties.viewport.change, () => this._updateViewportFromProperty());
}
async render(): Promise<void> {
super.render()
this.el.appendChild(this._layout_wrapper);
await this.plot();
(window as any).Plotly.relayout(this._layout_wrapper, this.model.relayout)
}
_trace_data(): any {
const data = [];
for (let i = 0; i < this.model.data.length; i++)
data.push(this._get_trace(i, false))
return data
}
_layout_data(): any {
const newLayout = deepCopy(this.model.layout);
if (this._relayouting) {
const {layout} = this._layout_wrapper;
// For each xaxis* and yaxis* property of layout, if the value has a 'range'
// property then use this in newLayout
Object.keys(layout).reduce((value: any, key: string) => {
if (key.slice(1, 5) === "axis" && 'range' in value) {
newLayout[key].range = value.range;
}
}, {});
}
return newLayout
}
_install_callbacks(): void {
// - plotly_relayout
this._layout_wrapper.on('plotly_relayout', (eventData: any) => {
if (eventData['_update_from_property'] !== true) {
this.model.relayout_data = filterEventData(
this._layout_wrapper, eventData, 'relayout');
this._updateViewportProperty();
this._end_relayouting();
}
});
// - plotly_relayouting
this._layout_wrapper.on('plotly_relayouting', () => {
if (this.model.viewport_update_policy !== 'mouseup') {
this._relayouting = true;
this._updateViewportProperty();
}
});
// - plotly_restyle
this._layout_wrapper.on('plotly_restyle', (eventData: any) => {
this.model.restyle_data = filterEventData(
this._layout_wrapper, eventData, 'restyle');
this._updateViewportProperty();
});
// - plotly_click
this._layout_wrapper.on('plotly_click', (eventData: any) => {
this.model.click_data = filterEventData(
this._layout_wrapper, eventData, 'click');
});
// - plotly_hover
this._layout_wrapper.on('plotly_hover', (eventData: any) => {
this.model.hover_data = filterEventData(
this._layout_wrapper, eventData, 'hover');
});
// - plotly_selected
this._layout_wrapper.on('plotly_selected', (eventData: any) => {
this.model.selected_data = filterEventData(
this._layout_wrapper, eventData, 'selected');
});
// - plotly_clickannotation
this._layout_wrapper.on('plotly_clickannotation', (eventData: any) => {
delete eventData["event"];
delete eventData["fullAnnotation"];
this.model.clickannotation_data = eventData
});
// - plotly_deselect
this._layout_wrapper.on('plotly_deselect', () => {
this.model.selected_data = null;
});
// - plotly_unhover
this._layout_wrapper.on('plotly_unhover', () => {
this.model.hover_data = null;
});
}
async plot(): Promise<void> {
if (!(window as any).Plotly)
return
const data = this._trace_data()
const newLayout = this._layout_data()
this._reacting = true
await (window as any).Plotly.react(this._layout_wrapper, data, newLayout, this.model.config)
this._updateSetViewportFunction()
this._updateViewportProperty()
if (!this._plotInitialized)
this._install_callbacks()
else if (!_isHidden(this._layout_wrapper))
(window as any).Plotly.Plots.resize(this._layout_wrapper)
this._reacting = false
this._plotInitialized = true
}
after_layout(): void{
super.after_layout()
set_size(this.el, this.model)
if ((window as any).Plotly && this._plotInitialized)
(window as any).Plotly.Plots.resize(this._layout_wrapper)
}
_get_trace(index: number, update: boolean): any {
const trace = clone(this.model.data[index]);
const cds = this.model.data_sources[index];
for (const column of cds.columns()) {
let array = cds.get_array(column)[0];
if (array.shape != null && array.shape.length > 1) {
const arrays = [];
const shape = array.shape;
for (let s = 0; s < shape[0]; s++) {
arrays.push(array.slice(s*shape[1], (s+1)*shape[1]));
}
array = arrays;
}
let prop_path = column.split(".");
let prop = prop_path[prop_path.length - 1];
let prop_parent = trace;
for (let k of prop_path.slice(0, -1)) {
prop_parent = (prop_parent[k] as any)
}
if (update && prop_path.length == 1) {
prop_parent[prop] = [array];
} else {
prop_parent[prop] = array;
}
}
return trace;
}
_updateViewportFromProperty(): void {
if (!(window as any).Plotly || this._settingViewport || this._reacting || !this.model.viewport ) { return }
const fullLayout = this._layout_wrapper._fullLayout;
// Call relayout if viewport differs from fullLayout
Object.keys(this.model.viewport).reduce((value: any, key: string) => {
if (!isEqual(get(fullLayout, key), value)) {
let clonedViewport = deepCopy(this.model.viewport)
clonedViewport['_update_from_property'] = true
this._settingViewport = true;
(window as any).Plotly.relayout(this.el, clonedViewport).then(() => {
this._settingViewport = false;
})
return false
} else {
return true
}
}, {});
}
_updateViewportProperty(): void {
const fullLayout = this._layout_wrapper._fullLayout;
let viewport: any = {};
// Get range for all xaxis and yaxis properties
for (let prop in fullLayout) {
if (!fullLayout.hasOwnProperty(prop))
continue
let maybe_axis = prop.slice(0, 5);
if (maybe_axis === 'xaxis' || maybe_axis === 'yaxis')
viewport[prop + '.range'] = deepCopy(fullLayout[prop].range)
}
if (!isEqual(viewport, this.model.viewport))
this._setViewport(viewport)
}
_updateSetViewportFunction(): void {
if (this.model.viewport_update_policy === "continuous" ||
this.model.viewport_update_policy === "mouseup") {
this._setViewport = (viewport: any) => {
if (!this._settingViewport) {
this._settingViewport = true
this.model.viewport = viewport
this._settingViewport = false
}
}
} else {
this._setViewport = throttle((viewport: any) => {
if (!this._settingViewport) {
this._settingViewport = true
this.model.viewport = viewport
this._settingViewport = false
}
}, this.model.viewport_update_throttle)
}
}
}
export namespace PlotlyPlot {
export type Attrs = p.AttrsOf<Props>
export type Props = HTMLBox.Props & {
data: p.Property<any[]>
layout: p.Property<any>
config: p.Property<any>
data_sources: p.Property<any[]>
relayout: p.Property<any>
restyle: p.Property<any>
relayout_data: p.Property<any>
restyle_data: p.Property<any>
click_data: p.Property<any>
hover_data: p.Property<any>
clickannotation_data: p.Property<any>
selected_data: p.Property<any>
viewport: p.Property<any>
viewport_update_policy: p.Property<string>
viewport_update_throttle: p.Property<number>
_render_count: p.Property<number>
}
}
export interface PlotlyPlot extends PlotlyPlot.Attrs {}
export class PlotlyPlot extends HTMLBox {
properties: PlotlyPlot.Props
constructor(attrs?: Partial<PlotlyPlot.Attrs>) {
super(attrs)
}
static __module__ = "panel.models.plotly"
static init_PlotlyPlot(): void {
this.prototype.default_view = PlotlyPlotView
this.define<PlotlyPlot.Props>(({Array, Any, Ref, String, Nullable, Number}) => ({
data: [ Array(Any), [] ],
layout: [ Any, {} ],
config: [ Any, {} ],
data_sources: [ Array(Ref(ColumnDataSource)), [] ],
relayout: [ Nullable(Any), {} ],
restyle: [ Nullable(Any), {} ],
relayout_data: [ Any, {} ],
restyle_data: [ Array(Any), [] ],
click_data: [ Any, {} ],
hover_data: [ Any, {} ],
clickannotation_data: [ Any, {} ],
selected_data: [ Any, {} ],
viewport: [ Any, {} ],
viewport_update_policy: [ String, "mouseup" ],
viewport_update_throttle: [ Number, 200 ],
_render_count: [ Number, 0 ],
}))
}
}