-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathplot_api.js
3087 lines (2641 loc) · 109 KB
/
plot_api.js
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
/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var d3 = require('d3');
var m4FromQuat = require('gl-mat4/fromQuat');
var isNumeric = require('fast-isnumeric');
var Plotly = require('../plotly');
var Lib = require('../lib');
var Events = require('../lib/events');
var Queue = require('../lib/queue');
var Plots = require('../plots/plots');
var Fx = require('../plots/cartesian/graph_interact');
var Color = require('../components/color');
var Drawing = require('../components/drawing');
var ErrorBars = require('../components/errorbars');
var Images = require('../components/images');
var Legend = require('../components/legend');
var RangeSlider = require('../components/rangeslider');
var RangeSelector = require('../components/rangeselector');
var Shapes = require('../components/shapes');
var Titles = require('../components/titles');
var manageModeBar = require('../components/modebar/manage');
var xmlnsNamespaces = require('../constants/xmlns_namespaces');
/**
* Main plot-creation function
*
* Note: will call makePlotFramework if necessary to create the framework
*
* @param {string id or DOM element} gd
* the id or DOM element of the graph container div
* @param {array of objects} data
* array of traces, containing the data and display information for each trace
* @param {object} layout
* object describing the overall display of the plot,
* all the stuff that doesn't pertain to any individual trace
* @param {object} config
* configuration options (see ./plot_config.js for more info)
*
*/
Plotly.plot = function(gd, data, layout, config) {
gd = getGraphDiv(gd);
// Events.init is idempotent and bails early if gd has already been init'd
Events.init(gd);
var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
if(okToPlot === false) return Promise.reject();
// if there's no data or layout, and this isn't yet a plotly plot
// container, log a warning to help plotly.js users debug
if(!data && !layout && !Lib.isPlotDiv(gd)) {
Lib.warn('Calling Plotly.plot as if redrawing ' +
'but this container doesn\'t yet have a plot.', gd);
}
// transfer configuration options to gd until we move over to
// a more OO like model
setPlotContext(gd, config);
if(!layout) layout = {};
// hook class for plots main container (in case of plotly.js
// this won't be #embedded-graph or .js-tab-contents)
d3.select(gd).classed('js-plotly-plot', true);
// off-screen getBoundingClientRect testing space,
// in #js-plotly-tester (and stored as gd._tester)
// so we can share cached text across tabs
Drawing.makeTester(gd);
// collect promises for any async actions during plotting
// any part of the plotting code can push to gd._promises, then
// before we move to the next step, we check that they're all
// complete, and empty out the promise list again.
gd._promises = [];
var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data));
// if there is already data on the graph, append the new data
// if you only want to redraw, pass a non-array for data
if(Array.isArray(data)) {
cleanData(data, gd.data);
if(graphWasEmpty) gd.data = data;
else gd.data.push.apply(gd.data, data);
// for routines outside graph_obj that want a clean tab
// (rather than appending to an existing one) gd.empty
// is used to determine whether to make a new tab
gd.empty = false;
}
if(!gd.layout || graphWasEmpty) gd.layout = cleanLayout(layout);
// if the user is trying to drag the axes, allow new data and layout
// to come in but don't allow a replot.
if(gd._dragging) {
// signal to drag handler that after everything else is done
// we need to replot, because something has changed
gd._replotPending = true;
return Promise.reject();
} else {
// we're going ahead with a replot now
gd._replotPending = false;
}
Plots.supplyDefaults(gd);
// Polar plots
if(data && data[0] && data[0].r) return plotPolar(gd, data, layout);
// so we don't try to re-call Plotly.plot from inside
// legend and colorbar, if margins changed
gd._replotting = true;
var hasData = gd._fullData.length > 0;
var subplots = Plotly.Axes.getSubplots(gd).join(''),
oldSubplots = Object.keys(gd._fullLayout._plots || {}).join(''),
hasSameSubplots = (oldSubplots === subplots);
// Make or remake the framework (ie container and axes) if we need to
// note: if they container already exists and has data,
// the new layout gets ignored (as it should)
// but if there's no data there yet, it's just a placeholder...
// then it should destroy and remake the plot
if(hasData) {
if(gd.framework !== makePlotFramework || graphWasEmpty || !hasSameSubplots) {
gd.framework = makePlotFramework;
makePlotFramework(gd);
}
}
else if(!hasSameSubplots) {
gd.framework = makePlotFramework;
makePlotFramework(gd);
}
else if(graphWasEmpty) makePlotFramework(gd);
// save initial axis range once per graph
if(graphWasEmpty) Plotly.Axes.saveRangeInitial(gd);
var fullLayout = gd._fullLayout;
// prepare the data and find the autorange
// generate calcdata, if we need to
// to force redoing calcdata, just delete it before calling Plotly.plot
var recalc = !gd.calcdata || gd.calcdata.length !== (gd.data || []).length;
if(recalc) doCalcdata(gd);
// in case it has changed, attach fullData traces to calcdata
for(var i = 0; i < gd.calcdata.length; i++) {
gd.calcdata[i][0].trace = gd._fullData[i];
}
/*
* start async-friendly code - now we're actually drawing things
*/
var oldmargins = JSON.stringify(fullLayout._size);
// draw anything that can affect margins.
// currently this is legend and colorbars
function marginPushers() {
var calcdata = gd.calcdata;
var i, cd, trace;
Legend.draw(gd);
RangeSelector.draw(gd);
for(i = 0; i < calcdata.length; i++) {
cd = calcdata[i];
trace = cd[0].trace;
if(trace.visible !== true || !trace._module.colorbar) {
Plots.autoMargin(gd, 'cb' + trace.uid);
}
else trace._module.colorbar(gd, cd);
}
Plots.doAutoMargin(gd);
return Plots.previousPromises(gd);
}
function marginPushersAgain() {
// in case the margins changed, draw margin pushers again
var seq = JSON.stringify(fullLayout._size) === oldmargins ?
[] : [marginPushers, layoutStyles];
return Lib.syncOrAsync(seq.concat(Fx.init), gd);
}
function positionAndAutorange() {
if(!recalc) return;
var subplots = Plots.getSubplotIds(fullLayout, 'cartesian'),
modules = fullLayout._modules;
// position and range calculations for traces that
// depend on each other ie bars (stacked or grouped)
// and boxes (grouped) push each other out of the way
var subplotInfo, _module;
for(var i = 0; i < subplots.length; i++) {
subplotInfo = fullLayout._plots[subplots[i]];
for(var j = 0; j < modules.length; j++) {
_module = modules[j];
if(_module.setPositions) _module.setPositions(gd, subplotInfo);
}
}
// calc and autorange for errorbars
ErrorBars.calc(gd);
// TODO: autosize extra for text markers
return Lib.syncOrAsync([
Shapes.calcAutorange,
Plotly.Annotations.calcAutorange,
doAutoRange
], gd);
}
function doAutoRange() {
var axList = Plotly.Axes.list(gd, '', true);
for(var i = 0; i < axList.length; i++) {
Plotly.Axes.doAutoRange(axList[i]);
}
}
function drawAxes() {
// draw ticks, titles, and calculate axis scaling (._b, ._m)
return Plotly.Axes.doTicks(gd, 'redraw');
}
// Now plot the data
function drawData() {
var calcdata = gd.calcdata,
i;
// in case of traces that were heatmaps or contour maps
// previously, remove them and their colorbars explicitly
for(i = 0; i < calcdata.length; i++) {
var trace = calcdata[i][0].trace,
isVisible = (trace.visible === true),
uid = trace.uid;
if(!isVisible || !Plots.traceIs(trace, '2dMap')) {
fullLayout._paper.selectAll(
'.hm' + uid +
',.contour' + uid +
',#clip' + uid
).remove();
}
if(!isVisible || !trace._module.colorbar) {
fullLayout._infolayer.selectAll('.cb' + uid).remove();
}
}
// loop over the base plot modules present on graph
var basePlotModules = fullLayout._basePlotModules;
for(i = 0; i < basePlotModules.length; i++) {
basePlotModules[i].plot(gd);
}
// styling separate from drawing
Plots.style(gd);
// show annotations and shapes
Shapes.drawAll(gd);
Plotly.Annotations.drawAll(gd);
// source links
Plots.addLinks(gd);
// Mark the first render as complete
gd._replotting = false;
return Plots.previousPromises(gd);
}
// An initial paint must be completed before these components can be
// correctly sized and the whole plot re-margined. gd._replotting must
// be set to false before these will work properly.
function finalDraw() {
Shapes.drawAll(gd);
Images.draw(gd);
Plotly.Annotations.drawAll(gd);
Legend.draw(gd);
RangeSlider.draw(gd);
RangeSelector.draw(gd);
}
function cleanUp() {
// now we're REALLY TRULY done plotting...
// so mark it as done and let other procedures call a replot
gd.emit('plotly_afterplot');
}
Lib.syncOrAsync([
Plots.previousPromises,
marginPushers,
marginPushersAgain,
positionAndAutorange,
layoutStyles,
drawAxes,
drawData,
finalDraw
], gd, cleanUp);
// even if everything we did was synchronous, return a promise
// so that the caller doesn't care which route we took
return Promise.all(gd._promises).then(function() {
return gd;
});
};
// Get the container div: we store all variables for this plot as
// properties of this div
// some callers send this in by DOM element, others by id (string)
function getGraphDiv(gd) {
var gdElement;
if(typeof gd === 'string') {
gdElement = document.getElementById(gd);
if(gdElement === null) {
throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
}
return gdElement;
}
else if(gd === null || gd === undefined) {
throw new Error('DOM element provided is null or undefined');
}
return gd; // otherwise assume that gd is a DOM element
}
function opaqueSetBackground(gd, bgColor) {
gd._fullLayout._paperdiv.style('background', 'white');
Plotly.defaultConfig.setBackground(gd, bgColor);
}
function setPlotContext(gd, config) {
if(!gd._context) gd._context = Lib.extendFlat({}, Plotly.defaultConfig);
var context = gd._context;
if(config) {
Object.keys(config).forEach(function(key) {
if(key in context) {
if(key === 'setBackground' && config[key] === 'opaque') {
context[key] = opaqueSetBackground;
}
else context[key] = config[key];
}
});
// map plot3dPixelRatio to plotGlPixelRatio for backward compatibility
if(config.plot3dPixelRatio && !context.plotGlPixelRatio) {
context.plotGlPixelRatio = context.plot3dPixelRatio;
}
}
//staticPlot forces a bunch of others:
if(context.staticPlot) {
context.editable = false;
context.autosizable = false;
context.scrollZoom = false;
context.doubleClick = false;
context.showTips = false;
context.showLink = false;
context.displayModeBar = false;
}
}
function plotPolar(gd, data, layout) {
// build or reuse the container skeleton
var plotContainer = d3.select(gd).selectAll('.plot-container')
.data([0]);
plotContainer.enter()
.insert('div', ':first-child')
.classed('plot-container plotly', true);
var paperDiv = plotContainer.selectAll('.svg-container')
.data([0]);
paperDiv.enter().append('div')
.classed('svg-container', true)
.style('position', 'relative');
// empty it everytime for now
paperDiv.html('');
// fulfill gd requirements
if(data) gd.data = data;
if(layout) gd.layout = layout;
Plotly.micropolar.manager.fillLayout(gd);
if(gd._fullLayout.autosize === 'initial' && gd._context.autosizable) {
plotAutoSize(gd, {});
gd._fullLayout.autosize = layout.autosize = true;
}
// resize canvas
paperDiv.style({
width: gd._fullLayout.width + 'px',
height: gd._fullLayout.height + 'px'
});
// instantiate framework
gd.framework = Plotly.micropolar.manager.framework(gd);
// plot
gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node());
// set undo point
gd.framework.setUndoPoint();
// get the resulting svg for extending it
var polarPlotSVG = gd.framework.svg();
// editable title
var opacity = 1;
var txt = gd._fullLayout.title;
if(txt === '' || !txt) opacity = 0;
var placeholderText = 'Click to enter title';
var titleLayout = function() {
this.call(Plotly.util.convertToTspans);
//TODO: html/mathjax
//TODO: center title
};
var title = polarPlotSVG.select('.title-group text')
.call(titleLayout);
if(gd._context.editable) {
title.attr({'data-unformatted': txt});
if(!txt || txt === placeholderText) {
opacity = 0.2;
title.attr({'data-unformatted': placeholderText})
.text(placeholderText)
.style({opacity: opacity})
.on('mouseover.opacity', function() {
d3.select(this).transition().duration(100)
.style('opacity', 1);
})
.on('mouseout.opacity', function() {
d3.select(this).transition().duration(1000)
.style('opacity', 0);
});
}
var setContenteditable = function() {
this.call(Plotly.util.makeEditable)
.on('edit', function(text) {
gd.framework({layout: {title: text}});
this.attr({'data-unformatted': text})
.text(text)
.call(titleLayout);
this.call(setContenteditable);
})
.on('cancel', function() {
var txt = this.attr('data-unformatted');
this.text(txt).call(titleLayout);
});
};
title.call(setContenteditable);
}
gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor);
Plots.addLinks(gd);
return Promise.resolve();
}
function cleanLayout(layout) {
// make a few changes to the layout right away
// before it gets used for anything
// backward compatibility and cleanup of nonstandard options
var i, j;
if(!layout) layout = {};
// cannot have (x|y)axis1, numbering goes axis, axis2, axis3...
if(layout.xaxis1) {
if(!layout.xaxis) layout.xaxis = layout.xaxis1;
delete layout.xaxis1;
}
if(layout.yaxis1) {
if(!layout.yaxis) layout.yaxis = layout.yaxis1;
delete layout.yaxis1;
}
var axList = Plotly.Axes.list({_fullLayout: layout});
for(i = 0; i < axList.length; i++) {
var ax = axList[i];
if(ax.anchor && ax.anchor !== 'free') {
ax.anchor = Plotly.Axes.cleanId(ax.anchor);
}
if(ax.overlaying) ax.overlaying = Plotly.Axes.cleanId(ax.overlaying);
// old method of axis type - isdate and islog (before category existed)
if(!ax.type) {
if(ax.isdate) ax.type = 'date';
else if(ax.islog) ax.type = 'log';
else if(ax.isdate === false && ax.islog === false) ax.type = 'linear';
}
if(ax.autorange === 'withzero' || ax.autorange === 'tozero') {
ax.autorange = true;
ax.rangemode = 'tozero';
}
delete ax.islog;
delete ax.isdate;
delete ax.categories; // replaced by _categories
// prune empty domain arrays made before the new nestedProperty
if(emptyContainer(ax, 'domain')) delete ax.domain;
// autotick -> tickmode
if(ax.autotick !== undefined) {
if(ax.tickmode === undefined) {
ax.tickmode = ax.autotick ? 'auto' : 'linear';
}
delete ax.autotick;
}
}
if(layout.annotations !== undefined && !Array.isArray(layout.annotations)) {
Lib.warn('Annotations must be an array.');
delete layout.annotations;
}
var annotationsLen = (layout.annotations || []).length;
for(i = 0; i < annotationsLen; i++) {
var ann = layout.annotations[i];
if(ann.ref) {
if(ann.ref === 'paper') {
ann.xref = 'paper';
ann.yref = 'paper';
}
else if(ann.ref === 'data') {
ann.xref = 'x';
ann.yref = 'y';
}
delete ann.ref;
}
cleanAxRef(ann, 'xref');
cleanAxRef(ann, 'yref');
}
if(layout.shapes !== undefined && !Array.isArray(layout.shapes)) {
Lib.warn('Shapes must be an array.');
delete layout.shapes;
}
var shapesLen = (layout.shapes || []).length;
for(i = 0; i < shapesLen; i++) {
var shape = layout.shapes[i];
cleanAxRef(shape, 'xref');
cleanAxRef(shape, 'yref');
}
var legend = layout.legend;
if(legend) {
// check for old-style legend positioning (x or y is +/- 100)
if(legend.x > 3) {
legend.x = 1.02;
legend.xanchor = 'left';
}
else if(legend.x < -2) {
legend.x = -0.02;
legend.xanchor = 'right';
}
if(legend.y > 3) {
legend.y = 1.02;
legend.yanchor = 'bottom';
}
else if(legend.y < -2) {
legend.y = -0.02;
legend.yanchor = 'top';
}
}
/*
* Moved from rotate -> orbit for dragmode
*/
if(layout.dragmode === 'rotate') layout.dragmode = 'orbit';
// cannot have scene1, numbering goes scene, scene2, scene3...
if(layout.scene1) {
if(!layout.scene) layout.scene = layout.scene1;
delete layout.scene1;
}
/*
* Clean up Scene layouts
*/
var sceneIds = Plots.getSubplotIds(layout, 'gl3d');
for(i = 0; i < sceneIds.length; i++) {
var scene = layout[sceneIds[i]];
// clean old Camera coords
var cameraposition = scene.cameraposition;
if(Array.isArray(cameraposition) && cameraposition[0].length === 4) {
var rotation = cameraposition[0],
center = cameraposition[1],
radius = cameraposition[2],
mat = m4FromQuat([], rotation),
eye = [];
for(j = 0; j < 3; ++j) {
eye[j] = center[i] + radius * mat[2 + 4 * j];
}
scene.camera = {
eye: {x: eye[0], y: eye[1], z: eye[2]},
center: {x: center[0], y: center[1], z: center[2]},
up: {x: mat[1], y: mat[5], z: mat[9]}
};
delete scene.cameraposition;
}
}
// sanitize rgb(fractions) and rgba(fractions) that old tinycolor
// supported, but new tinycolor does not because they're not valid css
Color.clean(layout);
return layout;
}
function cleanAxRef(container, attr) {
var valIn = container[attr],
axLetter = attr.charAt(0);
if(valIn && valIn !== 'paper') {
container[attr] = Plotly.Axes.cleanId(valIn, axLetter);
}
}
// Make a few changes to the data right away
// before it gets used for anything
function cleanData(data, existingData) {
// Enforce unique IDs
var suids = [], // seen uids --- so we can weed out incoming repeats
uids = data.concat(Array.isArray(existingData) ? existingData : [])
.filter(function(trace) { return 'uid' in trace; })
.map(function(trace) { return trace.uid; });
for(var tracei = 0; tracei < data.length; tracei++) {
var trace = data[tracei];
var i;
// assign uids to each trace and detect collisions.
if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) {
var newUid;
for(i = 0; i < 100; i++) {
newUid = Lib.randstr(uids);
if(suids.indexOf(newUid) === -1) break;
}
trace.uid = Lib.randstr(uids);
uids.push(trace.uid);
}
// keep track of already seen uids, so that if there are
// doubles we force the trace with a repeat uid to
// acquire a new one
suids.push(trace.uid);
// BACKWARD COMPATIBILITY FIXES
// use xbins to bin data in x, and ybins to bin data in y
if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) {
trace.ybins = trace.xbins;
delete trace.xbins;
}
// error_y.opacity is obsolete - merge into color
if(trace.error_y && 'opacity' in trace.error_y) {
var dc = Color.defaults,
yeColor = trace.error_y.color ||
(Plots.traceIs(trace, 'bar') ? Color.defaultLine : dc[tracei % dc.length]);
trace.error_y.color = Color.addOpacity(
Color.rgb(yeColor),
Color.opacity(yeColor) * trace.error_y.opacity);
delete trace.error_y.opacity;
}
// convert bardir to orientation, and put the data into
// the axes it's eventually going to be used with
if('bardir' in trace) {
if(trace.bardir === 'h' && (Plots.traceIs(trace, 'bar') ||
trace.type.substr(0, 9) === 'histogram')) {
trace.orientation = 'h';
swapXYData(trace);
}
delete trace.bardir;
}
// now we have only one 1D histogram type, and whether
// it uses x or y data depends on trace.orientation
if(trace.type === 'histogramy') swapXYData(trace);
if(trace.type === 'histogramx' || trace.type === 'histogramy') {
trace.type = 'histogram';
}
// scl->scale, reversescl->reversescale
if('scl' in trace) {
trace.colorscale = trace.scl;
delete trace.scl;
}
if('reversescl' in trace) {
trace.reversescale = trace.reversescl;
delete trace.reversescl;
}
// axis ids x1 -> x, y1-> y
if(trace.xaxis) trace.xaxis = Plotly.Axes.cleanId(trace.xaxis, 'x');
if(trace.yaxis) trace.yaxis = Plotly.Axes.cleanId(trace.yaxis, 'y');
// scene ids scene1 -> scene
if(Plots.traceIs(trace, 'gl3d') && trace.scene) {
trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
}
if(!Plots.traceIs(trace, 'pie')) {
if(Array.isArray(trace.textposition)) {
trace.textposition = trace.textposition.map(cleanTextPosition);
}
else if(trace.textposition) {
trace.textposition = cleanTextPosition(trace.textposition);
}
}
// fix typo in colorscale definition
if(Plots.traceIs(trace, '2dMap')) {
if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu';
if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd';
}
if(Plots.traceIs(trace, 'markerColorscale') && trace.marker) {
var cont = trace.marker;
if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu';
if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd';
}
// fix typo in surface 'highlight*' definitions
if(trace.type === 'surface' && Lib.isPlainObject(trace.contours)) {
var dims = ['x', 'y', 'z'];
for(i = 0; i < dims.length; i++) {
var opts = trace.contours[dims[i]];
if(!Lib.isPlainObject(opts)) continue;
if(opts.highlightColor) {
opts.highlightcolor = opts.highlightColor;
delete opts.highlightColor;
}
if(opts.highlightWidth) {
opts.highlightwidth = opts.highlightWidth;
delete opts.highlightWidth;
}
}
}
// prune empty containers made before the new nestedProperty
if(emptyContainer(trace, 'line')) delete trace.line;
if('marker' in trace) {
if(emptyContainer(trace.marker, 'line')) delete trace.marker.line;
if(emptyContainer(trace, 'marker')) delete trace.marker;
}
// sanitize rgb(fractions) and rgba(fractions) that old tinycolor
// supported, but new tinycolor does not because they're not valid css
Color.clean(trace);
}
}
// textposition - support partial attributes (ie just 'top')
// and incorrect use of middle / center etc.
function cleanTextPosition(textposition) {
var posY = 'middle',
posX = 'center';
if(textposition.indexOf('top') !== -1) posY = 'top';
else if(textposition.indexOf('bottom') !== -1) posY = 'bottom';
if(textposition.indexOf('left') !== -1) posX = 'left';
else if(textposition.indexOf('right') !== -1) posX = 'right';
return posY + ' ' + posX;
}
function emptyContainer(outer, innerStr) {
return (innerStr in outer) &&
(typeof outer[innerStr] === 'object') &&
(Object.keys(outer[innerStr]).length === 0);
}
// convenience function to force a full redraw, mostly for use by plotly.js
Plotly.redraw = function(gd) {
gd = getGraphDiv(gd);
if(!Lib.isPlotDiv(gd)) {
Lib.warn('This element is not a Plotly plot.', gd);
return;
}
gd.calcdata = undefined;
return Plotly.plot(gd).then(function() {
gd.emit('plotly_redraw');
return gd;
});
};
/**
* Convenience function to make idempotent plot option obvious to users.
*
* @param gd
* @param {Object[]} data
* @param {Object} layout
* @param {Object} config
*/
Plotly.newPlot = function(gd, data, layout, config) {
gd = getGraphDiv(gd);
// remove gl contexts
Plots.cleanPlot([], {}, gd._fullData || {}, gd._fullLayout || {});
Plots.purge(gd);
return Plotly.plot(gd, data, layout, config);
};
function doCalcdata(gd) {
var axList = Plotly.Axes.list(gd),
fullData = gd._fullData,
fullLayout = gd._fullLayout;
var i, trace, module, cd;
var calcdata = gd.calcdata = new Array(fullData.length);
// extra helper variables
// firstscatter: fill-to-next on the first trace goes to zero
gd.firstscatter = true;
// how many box plots do we have (in case they're grouped)
gd.numboxes = 0;
// for calculating avg luminosity of heatmaps
gd._hmpixcount = 0;
gd._hmlumcount = 0;
// for sharing colors across pies (and for legend)
fullLayout._piecolormap = {};
fullLayout._piedefaultcolorcount = 0;
// initialize the category list, if there is one, so we start over
// to be filled in later by ax.d2c
for(i = 0; i < axList.length; i++) {
axList[i]._categories = axList[i]._initialCategories.slice();
}
for(i = 0; i < fullData.length; i++) {
trace = fullData[i];
module = trace._module;
cd = [];
if(module && trace.visible === true) {
if(module.calc) cd = module.calc(gd, trace);
}
// make sure there is a first point
// this ensures there is a calcdata item for every trace,
// even if cartesian logic doesn't handle it
if(!Array.isArray(cd) || !cd[0]) cd = [{x: false, y: false}];
// add the trace-wide properties to the first point,
// per point properties to every point
// t is the holder for trace-wide properties
if(!cd[0].t) cd[0].t = {};
cd[0].trace = trace;
calcdata[i] = cd;
}
}
/**
* Wrap negative indicies to their positive counterparts.
*
* @param {Number[]} indices An array of indices
* @param {Number} maxIndex The maximum index allowable (arr.length - 1)
*/
function positivifyIndices(indices, maxIndex) {
var parentLength = maxIndex + 1,
positiveIndices = [],
i,
index;
for(i = 0; i < indices.length; i++) {
index = indices[i];
if(index < 0) {
positiveIndices.push(parentLength + index);
} else {
positiveIndices.push(index);
}
}
return positiveIndices;
}
/**
* Ensures that an index array for manipulating gd.data is valid.
*
* Intended for use with addTraces, deleteTraces, and moveTraces.
*
* @param gd
* @param indices
* @param arrayName
*/
function assertIndexArray(gd, indices, arrayName) {
var i,
index;
for(i = 0; i < indices.length; i++) {
index = indices[i];
// validate that indices are indeed integers
if(index !== parseInt(index, 10)) {
throw new Error('all values in ' + arrayName + ' must be integers');
}
// check that all indices are in bounds for given gd.data array length
if(index >= gd.data.length || index < -gd.data.length) {
throw new Error(arrayName + ' must be valid indices for gd.data.');
}
// check that indices aren't repeated
if(indices.indexOf(index, i + 1) > -1 ||
index >= 0 && indices.indexOf(-gd.data.length + index) > -1 ||
index < 0 && indices.indexOf(gd.data.length + index) > -1) {
throw new Error('each index in ' + arrayName + ' must be unique.');
}
}
}
/**
* Private function used by Plotly.moveTraces to check input args
*
* @param gd
* @param currentIndices
* @param newIndices
*/
function checkMoveTracesArgs(gd, currentIndices, newIndices) {
// check that gd has attribute 'data' and 'data' is array
if(!Array.isArray(gd.data)) {
throw new Error('gd.data must be an array.');
}
// validate currentIndices array
if(typeof currentIndices === 'undefined') {
throw new Error('currentIndices is a required argument.');
} else if(!Array.isArray(currentIndices)) {
currentIndices = [currentIndices];
}
assertIndexArray(gd, currentIndices, 'currentIndices');
// validate newIndices array if it exists
if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
newIndices = [newIndices];
}
if(typeof newIndices !== 'undefined') {
assertIndexArray(gd, newIndices, 'newIndices');
}
// check currentIndices and newIndices are the same length if newIdices exists
if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
throw new Error('current and new indices must be of equal length.');
}
}
/**
* A private function to reduce the type checking clutter in addTraces.
*
* @param gd
* @param traces
* @param newIndices
*/