forked from danvk/dygraphs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dygraph.js
3566 lines (3196 loc) · 115 KB
/
dygraph.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
/**
* @license
* Copyright 2006 Dan Vanderkam ([email protected])
* MIT-licensed (http://opensource.org/licenses/MIT)
*/
/**
* @fileoverview Creates an interactive, zoomable graph based on a CSV file or
* string. Dygraph can handle multiple series with or without error bars. The
* date/value ranges will be automatically set. Dygraph uses the
* <canvas> tag, so it only works in FF1.5+.
* @author [email protected] (Dan Vanderkam)
Usage:
<div id="graphdiv" style="width:800px; height:500px;"></div>
<script type="text/javascript">
new Dygraph(document.getElementById("graphdiv"),
"datafile.csv", // CSV file with headers
{ }); // options
</script>
The CSV file is of the form
Date,SeriesA,SeriesB,SeriesC
YYYYMMDD,A1,B1,C1
YYYYMMDD,A2,B2,C2
If the 'errorBars' option is set in the constructor, the input should be of
the form
Date,SeriesA,SeriesB,...
YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
If the 'fractions' option is set, the input should be of the form:
Date,SeriesA,SeriesB,...
YYYYMMDD,A1/B1,A2/B2,...
YYYYMMDD,A1/B1,A2/B2,...
And error bars will be calculated automatically using a binomial distribution.
For further documentation and examples, see http://dygraphs.com/
*/
/*jshint globalstrict: true */
/*global DygraphLayout:false, DygraphCanvasRenderer:false, DygraphOptions:false, G_vmlCanvasManager:false */
"use strict";
/**
* Creates an interactive, zoomable chart.
*
* @constructor
* @param {div | String} div A div or the id of a div into which to construct
* the chart.
* @param {String | Function} file A file containing CSV data or a function
* that returns this data. The most basic expected format for each line is
* "YYYY/MM/DD,val1,val2,...". For more information, see
* http://dygraphs.com/data.html.
* @param {Object} attrs Various other attributes, e.g. errorBars determines
* whether the input data contains error ranges. For a complete list of
* options, see http://dygraphs.com/options.html.
*/
var Dygraph = function(div, data, opts, opt_fourth_param) {
if (opt_fourth_param !== undefined) {
// Old versions of dygraphs took in the series labels as a constructor
// parameter. This doesn't make sense anymore, but it's easy to continue
// to support this usage.
this.warn("Using deprecated four-argument dygraph constructor");
this.__old_init__(div, data, opts, opt_fourth_param);
} else {
this.__init__(div, data, opts);
}
};
Dygraph.NAME = "Dygraph";
Dygraph.VERSION = "1.2";
Dygraph.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
/**
* Returns information about the Dygraph class.
*/
Dygraph.toString = function() {
return this.__repr__();
};
// Various default values
Dygraph.DEFAULT_ROLL_PERIOD = 1;
Dygraph.DEFAULT_WIDTH = 480;
Dygraph.DEFAULT_HEIGHT = 320;
// For max 60 Hz. animation:
Dygraph.ANIMATION_STEPS = 12;
Dygraph.ANIMATION_DURATION = 200;
// These are defined before DEFAULT_ATTRS so that it can refer to them.
/**
* @private
* Return a string version of a number. This respects the digitsAfterDecimal
* and maxNumberWidth options.
* @param {Number} x The number to be formatted
* @param {Dygraph} opts An options view
* @param {String} name The name of the point's data series
* @param {Dygraph} g The dygraph object
*/
Dygraph.numberValueFormatter = function(x, opts, pt, g) {
var sigFigs = opts('sigFigs');
if (sigFigs !== null) {
// User has opted for a fixed number of significant figures.
return Dygraph.floatFormat(x, sigFigs);
}
var digits = opts('digitsAfterDecimal');
var maxNumberWidth = opts('maxNumberWidth');
// switch to scientific notation if we underflow or overflow fixed display.
if (x !== 0.0 &&
(Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
Math.abs(x) < Math.pow(10, -digits))) {
return x.toExponential(digits);
} else {
return '' + Dygraph.round_(x, digits);
}
};
/**
* variant for use as an axisLabelFormatter.
* @private
*/
Dygraph.numberAxisLabelFormatter = function(x, granularity, opts, g) {
return Dygraph.numberValueFormatter(x, opts, g);
};
/**
* Convert a JS date (millis since epoch) to YYYY/MM/DD
* @param {Number} date The JavaScript date (ms since epoch)
* @return {String} A date of the form "YYYY/MM/DD"
* @private
*/
Dygraph.dateString_ = function(date) {
var zeropad = Dygraph.zeropad;
var d = new Date(date);
// Get the year:
var year = "" + d.getFullYear();
// Get a 0 padded month string
var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
// Get a 0 padded day string
var day = zeropad(d.getDate());
var ret = "";
var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
if (frac) ret = " " + Dygraph.hmsString_(date);
return year + "/" + month + "/" + day + ret;
};
/**
* Convert a JS date to a string appropriate to display on an axis that
* is displaying values at the stated granularity.
* @param {Date} date The date to format
* @param {Number} granularity One of the Dygraph granularity constants
* @return {String} The formatted date
* @private
*/
Dygraph.dateAxisFormatter = function(date, granularity) {
if (granularity >= Dygraph.DECADAL) {
return date.strftime('%Y');
} else if (granularity >= Dygraph.MONTHLY) {
return date.strftime('%b %y');
} else {
var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
if (frac === 0 || granularity >= Dygraph.DAILY) {
return new Date(date.getTime() + 3600*1000).strftime('%d%b');
} else {
return Dygraph.hmsString_(date.getTime());
}
}
};
/**
* Standard plotters. These may be used by clients.
* Available plotters are:
* - Dygraph.Plotters.linePlotter: draws central lines (most common)
* - Dygraph.Plotters.errorPlotter: draws error bars
* - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph)
*
* By default, the plotter is [fillPlotter, errorPlotter, linePlotter].
* This causes all the lines to be drawn over all the fills/error bars.
*/
Dygraph.Plotters = DygraphCanvasRenderer._Plotters;
// Default attribute values.
Dygraph.DEFAULT_ATTRS = {
highlightCircleSize: 3,
highlightSeriesOpts: null,
highlightSeriesBackgroundAlpha: 0.5,
labelsDivWidth: 250,
labelsDivStyles: {
// TODO(danvk): move defaults from createStatusMessage_ here.
},
labelsSeparateLines: false,
labelsShowZeroValues: true,
labelsKMB: false,
labelsKMG2: false,
showLabelsOnHighlight: true,
digitsAfterDecimal: 2,
maxNumberWidth: 6,
sigFigs: null,
strokeWidth: 1.0,
strokeBorderWidth: 0,
strokeBorderColor: "white",
axisTickSize: 3,
axisLabelFontSize: 14,
xAxisLabelWidth: 50,
yAxisLabelWidth: 50,
rightGap: 5,
showRoller: false,
xValueParser: Dygraph.dateParser,
delimiter: ',',
sigma: 2.0,
errorBars: false,
fractions: false,
wilsonInterval: true, // only relevant if fractions is true
customBars: false,
fillGraph: false,
fillAlpha: 0.15,
connectSeparatedPoints: false,
stackedGraph: false,
hideOverlayOnMouseOut: true,
// TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
legend: 'onmouseover', // the only relevant value at the moment is 'always'.
stepPlot: false,
avoidMinZero: false,
drawAxesAtZero: false,
// Sizes of the various chart labels.
titleHeight: 28,
xLabelHeight: 18,
yLabelWidth: 18,
drawXAxis: true,
drawYAxis: true,
axisLineColor: "black",
axisLineWidth: 0.3,
gridLineWidth: 0.3,
axisLabelColor: "black",
axisLabelFont: "Arial", // TODO(danvk): is this implemented?
axisLabelWidth: 50,
drawYGrid: true,
drawXGrid: true,
gridLineColor: "rgb(128,128,128)",
interactionModel: null, // will be set to Dygraph.Interaction.defaultModel
animatedZooms: false, // (for now)
// Range selector options
showRangeSelector: false,
rangeSelectorHeight: 40,
rangeSelectorPlotStrokeColor: "#808FAB",
rangeSelectorPlotFillColor: "#A7B1C4",
// The ordering here ensures that central lines always appear above any
// fill bars/error bars.
plotter: [
Dygraph.Plotters.fillPlotter,
Dygraph.Plotters.errorPlotter,
Dygraph.Plotters.linePlotter
],
plugins: [ ],
// per-axis options
axes: {
x: {
pixelsPerLabel: 60,
axisLabelFormatter: Dygraph.dateAxisFormatter,
valueFormatter: Dygraph.dateString_,
ticker: null // will be set in dygraph-tickers.js
},
y: {
pixelsPerLabel: 30,
valueFormatter: Dygraph.numberValueFormatter,
axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
ticker: null // will be set in dygraph-tickers.js
},
y2: {
pixelsPerLabel: 30,
valueFormatter: Dygraph.numberValueFormatter,
axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
ticker: null // will be set in dygraph-tickers.js
}
}
};
// Directions for panning and zooming. Use bit operations when combined
// values are possible.
Dygraph.HORIZONTAL = 1;
Dygraph.VERTICAL = 2;
// Installed plugins, in order of precedence (most-general to most-specific).
// Plugins are installed after they are defined, in plugins/install.js.
Dygraph.PLUGINS = [
];
// Used for initializing annotation CSS rules only once.
Dygraph.addedAnnotationCSS = false;
Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
// Labels is no longer a constructor parameter, since it's typically set
// directly from the data source. It also conains a name for the x-axis,
// which the previous constructor form did not.
if (labels !== null) {
var new_labels = ["Date"];
for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
Dygraph.update(attrs, { 'labels': new_labels });
}
this.__init__(div, file, attrs);
};
/**
* Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
* and context <canvas> inside of it. See the constructor for details.
* on the parameters.
* @param {Element} div the Element to render the graph into.
* @param {String | Function} file Source data
* @param {Object} attrs Miscellaneous other options
* @private
*/
Dygraph.prototype.__init__ = function(div, file, attrs) {
// Hack for IE: if we're using excanvas and the document hasn't finished
// loading yet (and hence may not have initialized whatever it needs to
// initialize), then keep calling this routine periodically until it has.
if (/MSIE/.test(navigator.userAgent) && !window.opera &&
typeof(G_vmlCanvasManager) != 'undefined' &&
document.readyState != 'complete') {
var self = this;
setTimeout(function() { self.__init__(div, file, attrs); }, 100);
return;
}
// Support two-argument constructor
if (attrs === null || attrs === undefined) { attrs = {}; }
attrs = Dygraph.mapLegacyOptions_(attrs);
if (typeof(div) == 'string') {
div = document.getElementById(div);
}
if (!div) {
Dygraph.error("Constructing dygraph with a non-existent div!");
return;
}
this.isUsingExcanvas_ = typeof(G_vmlCanvasManager) != 'undefined';
// Copy the important bits into the object
// TODO(danvk): most of these should just stay in the attrs_ dictionary.
this.maindiv_ = div;
this.file_ = file;
this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
this.previousVerticalX_ = -1;
this.fractions_ = attrs.fractions || false;
this.dateWindow_ = attrs.dateWindow || null;
this.is_initial_draw_ = true;
this.annotations_ = [];
// Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
this.zoomed_x_ = false;
this.zoomed_y_ = false;
// Clear the div. This ensure that, if multiple dygraphs are passed the same
// div, then only one will be drawn.
div.innerHTML = "";
// For historical reasons, the 'width' and 'height' options trump all CSS
// rules _except_ for an explicit 'width' or 'height' on the div.
// As an added convenience, if the div has zero height (like <div></div> does
// without any styles), then we use a default height/width.
if (div.style.width === '' && attrs.width) {
div.style.width = attrs.width + "px";
}
if (div.style.height === '' && attrs.height) {
div.style.height = attrs.height + "px";
}
if (div.style.height === '' && div.clientHeight === 0) {
div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
if (div.style.width === '') {
div.style.width = Dygraph.DEFAULT_WIDTH + "px";
}
}
// these will be zero if the dygraph's div is hidden.
this.width_ = div.clientWidth;
this.height_ = div.clientHeight;
// TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
if (attrs.stackedGraph) {
attrs.fillGraph = true;
// TODO(nikhilk): Add any other stackedGraph checks here.
}
// DEPRECATION WARNING: All option processing should be moved from
// attrs_ and user_attrs_ to options_, which holds all this information.
//
// Dygraphs has many options, some of which interact with one another.
// To keep track of everything, we maintain two sets of options:
//
// this.user_attrs_ only options explicitly set by the user.
// this.attrs_ defaults, options derived from user_attrs_, data.
//
// Options are then accessed this.attr_('attr'), which first looks at
// user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
// defaults without overriding behavior that the user specifically asks for.
this.user_attrs_ = {};
Dygraph.update(this.user_attrs_, attrs);
// This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
this.attrs_ = {};
Dygraph.updateDeep(this.attrs_, Dygraph.DEFAULT_ATTRS);
this.boundaryIds_ = [];
this.setIndexByName_ = {};
this.datasetIndex_ = [];
this.registeredEvents_ = [];
this.eventListeners_ = {};
this.attributes_ = new DygraphOptions(this);
// Create the containing DIV and other interactive elements
this.createInterface_();
// Activate plugins.
this.plugins_ = [];
var plugins = Dygraph.PLUGINS.concat(this.getOption('plugins'));
for (var i = 0; i < plugins.length; i++) {
var Plugin = plugins[i];
var pluginInstance = new Plugin();
var pluginDict = {
plugin: pluginInstance,
events: {},
options: {},
pluginOptions: {}
};
var handlers = pluginInstance.activate(this);
for (var eventName in handlers) {
// TODO(danvk): validate eventName.
pluginDict.events[eventName] = handlers[eventName];
}
this.plugins_.push(pluginDict);
}
// At this point, plugins can no longer register event handlers.
// Construct a map from event -> ordered list of [callback, plugin].
for (var i = 0; i < this.plugins_.length; i++) {
var plugin_dict = this.plugins_[i];
for (var eventName in plugin_dict.events) {
if (!plugin_dict.events.hasOwnProperty(eventName)) continue;
var callback = plugin_dict.events[eventName];
var pair = [plugin_dict.plugin, callback];
if (!(eventName in this.eventListeners_)) {
this.eventListeners_[eventName] = [pair];
} else {
this.eventListeners_[eventName].push(pair);
}
}
}
this.createDragInterface_();
this.start_();
};
/**
* Triggers a cascade of events to the various plugins which are interested in them.
* Returns true if the "default behavior" should be performed, i.e. if none of
* the event listeners called event.preventDefault().
* @private
*/
Dygraph.prototype.cascadeEvents_ = function(name, extra_props) {
if (!(name in this.eventListeners_)) return true;
// QUESTION: can we use objects & prototypes to speed this up?
var e = {
dygraph: this,
cancelable: false,
defaultPrevented: false,
preventDefault: function() {
if (!e.cancelable) throw "Cannot call preventDefault on non-cancelable event.";
e.defaultPrevented = true;
},
propagationStopped: false,
stopPropagation: function() {
e.propagationStopped = true;
}
};
Dygraph.update(e, extra_props);
var callback_plugin_pairs = this.eventListeners_[name];
if (callback_plugin_pairs) {
for (var i = callback_plugin_pairs.length - 1; i >= 0; i--) {
var plugin = callback_plugin_pairs[i][0];
var callback = callback_plugin_pairs[i][1];
callback.call(plugin, e);
if (e.propagationStopped) break;
}
}
return e.defaultPrevented;
};
/**
* Returns the zoomed status of the chart for one or both axes.
*
* Axis is an optional parameter. Can be set to 'x' or 'y'.
*
* The zoomed status for an axis is set whenever a user zooms using the mouse
* or when the dateWindow or valueRange are updated (unless the
* isZoomedIgnoreProgrammaticZoom option is also specified).
*/
Dygraph.prototype.isZoomed = function(axis) {
if (axis === null || axis === undefined) {
return this.zoomed_x_ || this.zoomed_y_;
}
if (axis === 'x') return this.zoomed_x_;
if (axis === 'y') return this.zoomed_y_;
throw "axis parameter is [" + axis + "] must be null, 'x' or 'y'.";
};
/**
* Returns information about the Dygraph object, including its containing ID.
*/
Dygraph.prototype.toString = function() {
var maindiv = this.maindiv_;
var id = (maindiv && maindiv.id) ? maindiv.id : maindiv;
return "[Dygraph " + id + "]";
};
/**
* @private
* Returns the value of an option. This may be set by the user (either in the
* constructor or by calling updateOptions) or by dygraphs, and may be set to a
* per-series value.
* @param { String } name The name of the option, e.g. 'rollPeriod'.
* @param { String } [seriesName] The name of the series to which the option
* will be applied. If no per-series value of this option is available, then
* the global value is returned. This is optional.
* @return { ... } The value of the option.
*/
Dygraph.prototype.attr_ = function(name, seriesName) {
// <REMOVE_FOR_COMBINED>
if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
this.error('Must include options reference JS for testing');
} else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
this.error('Dygraphs is using property ' + name + ', which has no entry ' +
'in the Dygraphs.OPTIONS_REFERENCE listing.');
// Only log this error once.
Dygraph.OPTIONS_REFERENCE[name] = true;
}
// </REMOVE_FOR_COMBINED>
return seriesName ? this.attributes_.getForSeries(name, seriesName) : this.attributes_.get(name);
};
/**
* Returns the current value for an option, as set in the constructor or via
* updateOptions. You may pass in an (optional) series name to get per-series
* values for the option.
*
* All values returned by this method should be considered immutable. If you
* modify them, there is no guarantee that the changes will be honored or that
* dygraphs will remain in a consistent state. If you want to modify an option,
* use updateOptions() instead.
*
* @param { String } name The name of the option (e.g. 'strokeWidth')
* @param { String } [opt_seriesName] Series name to get per-series values.
* @return { ... } The value of the option.
*/
Dygraph.prototype.getOption = function(name, opt_seriesName) {
return this.attr_(name, opt_seriesName);
};
Dygraph.prototype.getOptionForAxis = function(name, axis) {
return this.attributes_.getForAxis(name, axis);
};
/**
* @private
* @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
* @return { ... } A function mapping string -> option value
*/
Dygraph.prototype.optionsViewForAxis_ = function(axis) {
var self = this;
return function(opt) {
var axis_opts = self.user_attrs_.axes;
if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
return axis_opts[axis][opt];
}
// user-specified attributes always trump defaults, even if they're less
// specific.
if (typeof(self.user_attrs_[opt]) != 'undefined') {
return self.user_attrs_[opt];
}
axis_opts = self.attrs_.axes;
if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
return axis_opts[axis][opt];
}
// check old-style axis options
// TODO(danvk): add a deprecation warning if either of these match.
if (axis == 'y' && self.axes_[0].hasOwnProperty(opt)) {
return self.axes_[0][opt];
} else if (axis == 'y2' && self.axes_[1].hasOwnProperty(opt)) {
return self.axes_[1][opt];
}
return self.attr_(opt);
};
};
/**
* Returns the current rolling period, as set by the user or an option.
* @return {Number} The number of points in the rolling window
*/
Dygraph.prototype.rollPeriod = function() {
return this.rollPeriod_;
};
/**
* Returns the currently-visible x-range. This can be affected by zooming,
* panning or a call to updateOptions.
* Returns a two-element array: [left, right].
* If the Dygraph has dates on the x-axis, these will be millis since epoch.
*/
Dygraph.prototype.xAxisRange = function() {
return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
};
/**
* Returns the lower- and upper-bound x-axis values of the
* data set.
*/
Dygraph.prototype.xAxisExtremes = function() {
var left = this.rawData_[0][0];
var right = this.rawData_[this.rawData_.length - 1][0];
return [left, right];
};
/**
* Returns the currently-visible y-range for an axis. This can be affected by
* zooming, panning or a call to updateOptions. Axis indices are zero-based. If
* called with no arguments, returns the range of the first axis.
* Returns a two-element array: [bottom, top].
*/
Dygraph.prototype.yAxisRange = function(idx) {
if (typeof(idx) == "undefined") idx = 0;
if (idx < 0 || idx >= this.axes_.length) {
return null;
}
var axis = this.axes_[idx];
return [ axis.computedValueRange[0], axis.computedValueRange[1] ];
};
/**
* Returns the currently-visible y-ranges for each axis. This can be affected by
* zooming, panning, calls to updateOptions, etc.
* Returns an array of [bottom, top] pairs, one for each y-axis.
*/
Dygraph.prototype.yAxisRanges = function() {
var ret = [];
for (var i = 0; i < this.axes_.length; i++) {
ret.push(this.yAxisRange(i));
}
return ret;
};
// TODO(danvk): use these functions throughout dygraphs.
/**
* Convert from data coordinates to canvas/div X/Y coordinates.
* If specified, do this conversion for the coordinate system of a particular
* axis. Uses the first axis by default.
* Returns a two-element array: [X, Y]
*
* Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
* instead of toDomCoords(null, y, axis).
*/
Dygraph.prototype.toDomCoords = function(x, y, axis) {
return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
};
/**
* Convert from data x coordinates to canvas/div X coordinate.
* If specified, do this conversion for the coordinate system of a particular
* axis.
* Returns a single value or null if x is null.
*/
Dygraph.prototype.toDomXCoord = function(x) {
if (x === null) {
return null;
}
var area = this.plotter_.area;
var xRange = this.xAxisRange();
return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
};
/**
* Convert from data x coordinates to canvas/div Y coordinate and optional
* axis. Uses the first axis by default.
*
* returns a single value or null if y is null.
*/
Dygraph.prototype.toDomYCoord = function(y, axis) {
var pct = this.toPercentYCoord(y, axis);
if (pct === null) {
return null;
}
var area = this.plotter_.area;
return area.y + pct * area.h;
};
/**
* Convert from canvas/div coords to data coordinates.
* If specified, do this conversion for the coordinate system of a particular
* axis. Uses the first axis by default.
* Returns a two-element array: [X, Y].
*
* Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
* instead of toDataCoords(null, y, axis).
*/
Dygraph.prototype.toDataCoords = function(x, y, axis) {
return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
};
/**
* Convert from canvas/div x coordinate to data coordinate.
*
* If x is null, this returns null.
*/
Dygraph.prototype.toDataXCoord = function(x) {
if (x === null) {
return null;
}
var area = this.plotter_.area;
var xRange = this.xAxisRange();
return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
};
/**
* Convert from canvas/div y coord to value.
*
* If y is null, this returns null.
* if axis is null, this uses the first axis.
*/
Dygraph.prototype.toDataYCoord = function(y, axis) {
if (y === null) {
return null;
}
var area = this.plotter_.area;
var yRange = this.yAxisRange(axis);
if (typeof(axis) == "undefined") axis = 0;
if (!this.axes_[axis].logscale) {
return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
} else {
// Computing the inverse of toDomCoord.
var pct = (y - area.y) / area.h;
// Computing the inverse of toPercentYCoord. The function was arrived at with
// the following steps:
//
// Original calcuation:
// pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
//
// Move denominator to both sides:
// pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
//
// subtract logr1, and take the negative value.
// logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
//
// Swap both sides of the equation, and we can compute the log of the
// return value. Which means we just need to use that as the exponent in
// e^exponent.
// Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
var logr1 = Dygraph.log10(yRange[1]);
var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
var value = Math.pow(Dygraph.LOG_SCALE, exponent);
return value;
}
};
/**
* Converts a y for an axis to a percentage from the top to the
* bottom of the drawing area.
*
* If the coordinate represents a value visible on the canvas, then
* the value will be between 0 and 1, where 0 is the top of the canvas.
* However, this method will return values outside the range, as
* values can fall outside the canvas.
*
* If y is null, this returns null.
* if axis is null, this uses the first axis.
*
* @param { Number } y The data y-coordinate.
* @param { Number } [axis] The axis number on which the data coordinate lives.
* @return { Number } A fraction in [0, 1] where 0 = the top edge.
*/
Dygraph.prototype.toPercentYCoord = function(y, axis) {
if (y === null) {
return null;
}
if (typeof(axis) == "undefined") axis = 0;
var yRange = this.yAxisRange(axis);
var pct;
var logscale = this.attributes_.getForAxis("logscale", axis);
if (!logscale) {
// yRange[1] - y is unit distance from the bottom.
// yRange[1] - yRange[0] is the scale of the range.
// (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
} else {
var logr1 = Dygraph.log10(yRange[1]);
pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
}
return pct;
};
/**
* Converts an x value to a percentage from the left to the right of
* the drawing area.
*
* If the coordinate represents a value visible on the canvas, then
* the value will be between 0 and 1, where 0 is the left of the canvas.
* However, this method will return values outside the range, as
* values can fall outside the canvas.
*
* If x is null, this returns null.
* @param { Number } x The data x-coordinate.
* @return { Number } A fraction in [0, 1] where 0 = the left edge.
*/
Dygraph.prototype.toPercentXCoord = function(x) {
if (x === null) {
return null;
}
var xRange = this.xAxisRange();
return (x - xRange[0]) / (xRange[1] - xRange[0]);
};
/**
* Returns the number of columns (including the independent variable).
* @return { Integer } The number of columns.
*/
Dygraph.prototype.numColumns = function() {
return this.rawData_[0] ? this.rawData_[0].length : this.attr_("labels").length;
};
/**
* Returns the number of rows (excluding any header/label row).
* @return { Integer } The number of rows, less any header.
*/
Dygraph.prototype.numRows = function() {
return this.rawData_.length;
};
/**
* Returns the full range of the x-axis, as determined by the most extreme
* values in the data set. Not affected by zooming, visibility, etc.
* TODO(danvk): merge w/ xAxisExtremes
* @return { Array<Number> } A [low, high] pair
* @private
*/
Dygraph.prototype.fullXRange_ = function() {
if (this.numRows() > 0) {
return [this.rawData_[0][0], this.rawData_[this.numRows() - 1][0]];
} else {
return [0, 1];
}
};
/**
* Returns the value in the given row and column. If the row and column exceed
* the bounds on the data, returns null. Also returns null if the value is
* missing.
* @param { Number} row The row number of the data (0-based). Row 0 is the
* first row of data, not a header row.
* @param { Number} col The column number of the data (0-based)
* @return { Number } The value in the specified cell or null if the row/col
* were out of range.
*/
Dygraph.prototype.getValue = function(row, col) {
if (row < 0 || row > this.rawData_.length) return null;
if (col < 0 || col > this.rawData_[row].length) return null;
return this.rawData_[row][col];
};
/**
* Generates interface elements for the Dygraph: a containing div, a div to
* display the current point, and a textbox to adjust the rolling average
* period. Also creates the Renderer/Layout elements.
* @private
*/
Dygraph.prototype.createInterface_ = function() {
// Create the all-enclosing graph div
var enclosing = this.maindiv_;
this.graphDiv = document.createElement("div");
this.graphDiv.style.width = this.width_ + "px";
this.graphDiv.style.height = this.height_ + "px";
enclosing.appendChild(this.graphDiv);
// Create the canvas for interactive parts of the chart.
this.canvas_ = Dygraph.createCanvas();
this.canvas_.style.position = "absolute";
this.canvas_.width = this.width_;
this.canvas_.height = this.height_;
this.canvas_.style.width = this.width_ + "px"; // for IE
this.canvas_.style.height = this.height_ + "px"; // for IE
this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
// ... and for static parts of the chart.
this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
// The interactive parts of the graph are drawn on top of the chart.
this.graphDiv.appendChild(this.hidden_);
this.graphDiv.appendChild(this.canvas_);
this.mouseEventElement_ = this.createMouseEventElement_();
// Create the grapher
this.layout_ = new DygraphLayout(this);
var dygraph = this;
this.mouseMoveHandler_ = function(e) {
dygraph.mouseMove_(e);
};
this.mouseOutHandler_ = function(e) {
dygraph.mouseOut_(e);
};
this.addEvent(this.mouseEventElement_, 'mousemove', this.mouseMoveHandler_);
this.addEvent(this.mouseEventElement_, 'mouseout', this.mouseOutHandler_);
// Don't recreate and register the resize handler on subsequent calls.
// This happens when the graph is resized.
if (!this.resizeHandler_) {
this.resizeHandler_ = function(e) {
dygraph.resize();
};
// Update when the window is resized.
// TODO(danvk): drop frames depending on complexity of the chart.
this.addEvent(window, 'resize', this.resizeHandler_);
}
};
/**
* Detach DOM elements in the dygraph and null out all data references.
* Calling this when you're done with a dygraph can dramatically reduce memory
* usage. See, e.g., the tests/perf.html example.
*/
Dygraph.prototype.destroy = function() {
var removeRecursive = function(node) {
while (node.hasChildNodes()) {
removeRecursive(node.firstChild);
node.removeChild(node.firstChild);
}
};
if (this.registeredEvents_) {
for (var idx = 0; idx < this.registeredEvents_.length; idx++) {
var reg = this.registeredEvents_[idx];
Dygraph.removeEvent(reg.elem, reg.type, reg.fn);
}