squash a few remaining "use strict" errors
[dygraphs.git] / dygraph.js
1 /**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
9 * string. Dygraph can handle multiple series with or without error bars. The
10 * date/value ranges will be automatically set. Dygraph uses the
11 * <canvas> tag, so it only works in FF1.5+.
12 * @author danvdk@gmail.com (Dan Vanderkam)
13
14 Usage:
15 <div id="graphdiv" style="width:800px; height:500px;"></div>
16 <script type="text/javascript">
17 new Dygraph(document.getElementById("graphdiv"),
18 "datafile.csv", // CSV file with headers
19 { }); // options
20 </script>
21
22 The CSV file is of the form
23
24 Date,SeriesA,SeriesB,SeriesC
25 YYYYMMDD,A1,B1,C1
26 YYYYMMDD,A2,B2,C2
27
28 If the 'errorBars' option is set in the constructor, the input should be of
29 the form
30 Date,SeriesA,SeriesB,...
31 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
32 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
33
34 If the 'fractions' option is set, the input should be of the form:
35
36 Date,SeriesA,SeriesB,...
37 YYYYMMDD,A1/B1,A2/B2,...
38 YYYYMMDD,A1/B1,A2/B2,...
39
40 And error bars will be calculated automatically using a binomial distribution.
41
42 For further documentation and examples, see http://dygraphs.com/
43
44 */
45
46 "use strict";
47
48 /**
49 * Creates an interactive, zoomable chart.
50 *
51 * @constructor
52 * @param {div | String} div A div or the id of a div into which to construct
53 * the chart.
54 * @param {String | Function} file A file containing CSV data or a function
55 * that returns this data. The most basic expected format for each line is
56 * "YYYY/MM/DD,val1,val2,...". For more information, see
57 * http://dygraphs.com/data.html.
58 * @param {Object} attrs Various other attributes, e.g. errorBars determines
59 * whether the input data contains error ranges. For a complete list of
60 * options, see http://dygraphs.com/options.html.
61 */
62 var Dygraph = function(div, data, opts) {
63 if (arguments.length > 0) {
64 if (arguments.length == 4) {
65 // Old versions of dygraphs took in the series labels as a constructor
66 // parameter. This doesn't make sense anymore, but it's easy to continue
67 // to support this usage.
68 this.warn("Using deprecated four-argument dygraph constructor");
69 this.__old_init__(div, data, arguments[2], arguments[3]);
70 } else {
71 this.__init__(div, data, opts);
72 }
73 }
74 };
75
76 Dygraph.NAME = "Dygraph";
77 Dygraph.VERSION = "1.2";
78 Dygraph.__repr__ = function() {
79 return "[" + this.NAME + " " + this.VERSION + "]";
80 };
81
82 /**
83 * Returns information about the Dygraph class.
84 */
85 Dygraph.toString = function() {
86 return this.__repr__();
87 };
88
89 // Various default values
90 Dygraph.DEFAULT_ROLL_PERIOD = 1;
91 Dygraph.DEFAULT_WIDTH = 480;
92 Dygraph.DEFAULT_HEIGHT = 320;
93
94 Dygraph.ANIMATION_STEPS = 10;
95 Dygraph.ANIMATION_DURATION = 200;
96
97 // These are defined before DEFAULT_ATTRS so that it can refer to them.
98 /**
99 * @private
100 * Return a string version of a number. This respects the digitsAfterDecimal
101 * and maxNumberWidth options.
102 * @param {Number} x The number to be formatted
103 * @param {Dygraph} opts An options view
104 * @param {String} name The name of the point's data series
105 * @param {Dygraph} g The dygraph object
106 */
107 Dygraph.numberValueFormatter = function(x, opts, pt, g) {
108 var sigFigs = opts('sigFigs');
109
110 if (sigFigs !== null) {
111 // User has opted for a fixed number of significant figures.
112 return Dygraph.floatFormat(x, sigFigs);
113 }
114
115 var digits = opts('digitsAfterDecimal');
116 var maxNumberWidth = opts('maxNumberWidth');
117
118 // switch to scientific notation if we underflow or overflow fixed display.
119 if (x !== 0.0 &&
120 (Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
121 Math.abs(x) < Math.pow(10, -digits))) {
122 return x.toExponential(digits);
123 } else {
124 return '' + Dygraph.round_(x, digits);
125 }
126 };
127
128 /**
129 * variant for use as an axisLabelFormatter.
130 * @private
131 */
132 Dygraph.numberAxisLabelFormatter = function(x, granularity, opts, g) {
133 return Dygraph.numberValueFormatter(x, opts, g);
134 };
135
136 /**
137 * Convert a JS date (millis since epoch) to YYYY/MM/DD
138 * @param {Number} date The JavaScript date (ms since epoch)
139 * @return {String} A date of the form "YYYY/MM/DD"
140 * @private
141 */
142 Dygraph.dateString_ = function(date) {
143 var zeropad = Dygraph.zeropad;
144 var d = new Date(date);
145
146 // Get the year:
147 var year = "" + d.getFullYear();
148 // Get a 0 padded month string
149 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
150 // Get a 0 padded day string
151 var day = zeropad(d.getDate());
152
153 var ret = "";
154 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
155 if (frac) ret = " " + Dygraph.hmsString_(date);
156
157 return year + "/" + month + "/" + day + ret;
158 };
159
160 /**
161 * Convert a JS date to a string appropriate to display on an axis that
162 * is displaying values at the stated granularity.
163 * @param {Date} date The date to format
164 * @param {Number} granularity One of the Dygraph granularity constants
165 * @return {String} The formatted date
166 * @private
167 */
168 Dygraph.dateAxisFormatter = function(date, granularity) {
169 if (granularity >= Dygraph.DECADAL) {
170 return date.strftime('%Y');
171 } else if (granularity >= Dygraph.MONTHLY) {
172 return date.strftime('%b %y');
173 } else {
174 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
175 if (frac == 0 || granularity >= Dygraph.DAILY) {
176 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
177 } else {
178 return Dygraph.hmsString_(date.getTime());
179 }
180 }
181 };
182
183
184 // Default attribute values.
185 Dygraph.DEFAULT_ATTRS = {
186 highlightCircleSize: 3,
187
188 labelsDivWidth: 250,
189 labelsDivStyles: {
190 // TODO(danvk): move defaults from createStatusMessage_ here.
191 },
192 labelsSeparateLines: false,
193 labelsShowZeroValues: true,
194 labelsKMB: false,
195 labelsKMG2: false,
196 showLabelsOnHighlight: true,
197
198 digitsAfterDecimal: 2,
199 maxNumberWidth: 6,
200 sigFigs: null,
201
202 strokeWidth: 1.0,
203
204 axisTickSize: 3,
205 axisLabelFontSize: 14,
206 xAxisLabelWidth: 50,
207 yAxisLabelWidth: 50,
208 rightGap: 5,
209
210 showRoller: false,
211 xValueParser: Dygraph.dateParser,
212
213 delimiter: ',',
214
215 sigma: 2.0,
216 errorBars: false,
217 fractions: false,
218 wilsonInterval: true, // only relevant if fractions is true
219 customBars: false,
220 fillGraph: false,
221 fillAlpha: 0.15,
222 connectSeparatedPoints: false,
223
224 stackedGraph: false,
225 hideOverlayOnMouseOut: true,
226
227 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
228 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
229
230 stepPlot: false,
231 avoidMinZero: false,
232
233 // Sizes of the various chart labels.
234 titleHeight: 28,
235 xLabelHeight: 18,
236 yLabelWidth: 18,
237
238 drawXAxis: true,
239 drawYAxis: true,
240 axisLineColor: "black",
241 axisLineWidth: 0.3,
242 gridLineWidth: 0.3,
243 axisLabelColor: "black",
244 axisLabelFont: "Arial", // TODO(danvk): is this implemented?
245 axisLabelWidth: 50,
246 drawYGrid: true,
247 drawXGrid: true,
248 gridLineColor: "rgb(128,128,128)",
249
250 interactionModel: null, // will be set to Dygraph.Interaction.defaultModel
251 animatedZooms: false, // (for now)
252
253 // Range selector options
254 showRangeSelector: false,
255 rangeSelectorHeight: 40,
256 rangeSelectorPlotStrokeColor: "#808FAB",
257 rangeSelectorPlotFillColor: "#A7B1C4",
258
259 // per-axis options
260 axes: {
261 x: {
262 pixelsPerLabel: 60,
263 axisLabelFormatter: Dygraph.dateAxisFormatter,
264 valueFormatter: Dygraph.dateString_,
265 ticker: null // will be set in dygraph-tickers.js
266 },
267 y: {
268 pixelsPerLabel: 30,
269 valueFormatter: Dygraph.numberValueFormatter,
270 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
271 ticker: null // will be set in dygraph-tickers.js
272 },
273 y2: {
274 pixelsPerLabel: 30,
275 valueFormatter: Dygraph.numberValueFormatter,
276 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
277 ticker: null // will be set in dygraph-tickers.js
278 }
279 }
280 };
281
282 // Directions for panning and zooming. Use bit operations when combined
283 // values are possible.
284 Dygraph.HORIZONTAL = 1;
285 Dygraph.VERTICAL = 2;
286
287 // Used for initializing annotation CSS rules only once.
288 Dygraph.addedAnnotationCSS = false;
289
290 Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
291 // Labels is no longer a constructor parameter, since it's typically set
292 // directly from the data source. It also conains a name for the x-axis,
293 // which the previous constructor form did not.
294 if (labels != null) {
295 var new_labels = ["Date"];
296 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
297 Dygraph.update(attrs, { 'labels': new_labels });
298 }
299 this.__init__(div, file, attrs);
300 };
301
302 /**
303 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
304 * and context &lt;canvas&gt; inside of it. See the constructor for details.
305 * on the parameters.
306 * @param {Element} div the Element to render the graph into.
307 * @param {String | Function} file Source data
308 * @param {Object} attrs Miscellaneous other options
309 * @private
310 */
311 Dygraph.prototype.__init__ = function(div, file, attrs) {
312 // Hack for IE: if we're using excanvas and the document hasn't finished
313 // loading yet (and hence may not have initialized whatever it needs to
314 // initialize), then keep calling this routine periodically until it has.
315 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
316 typeof(G_vmlCanvasManager) != 'undefined' &&
317 document.readyState != 'complete') {
318 var self = this;
319 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
320 return;
321 }
322
323 // Support two-argument constructor
324 if (attrs == null) { attrs = {}; }
325
326 attrs = Dygraph.mapLegacyOptions_(attrs);
327
328 if (!div) {
329 Dygraph.error("Constructing dygraph with a non-existent div!");
330 return;
331 }
332
333 this.isUsingExcanvas_ = typeof(G_vmlCanvasManager) != 'undefined';
334
335 // Copy the important bits into the object
336 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
337 this.maindiv_ = div;
338 this.file_ = file;
339 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
340 this.previousVerticalX_ = -1;
341 this.fractions_ = attrs.fractions || false;
342 this.dateWindow_ = attrs.dateWindow || null;
343
344 this.wilsonInterval_ = attrs.wilsonInterval || true;
345 this.is_initial_draw_ = true;
346 this.annotations_ = [];
347
348 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
349 this.zoomed_x_ = false;
350 this.zoomed_y_ = false;
351
352 // Clear the div. This ensure that, if multiple dygraphs are passed the same
353 // div, then only one will be drawn.
354 div.innerHTML = "";
355
356 // For historical reasons, the 'width' and 'height' options trump all CSS
357 // rules _except_ for an explicit 'width' or 'height' on the div.
358 // As an added convenience, if the div has zero height (like <div></div> does
359 // without any styles), then we use a default height/width.
360 if (div.style.width == '' && attrs.width) {
361 div.style.width = attrs.width + "px";
362 }
363 if (div.style.height == '' && attrs.height) {
364 div.style.height = attrs.height + "px";
365 }
366 if (div.style.height == '' && div.clientHeight == 0) {
367 div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
368 if (div.style.width == '') {
369 div.style.width = Dygraph.DEFAULT_WIDTH + "px";
370 }
371 }
372 // these will be zero if the dygraph's div is hidden.
373 this.width_ = div.clientWidth;
374 this.height_ = div.clientHeight;
375
376 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
377 if (attrs['stackedGraph']) {
378 attrs['fillGraph'] = true;
379 // TODO(nikhilk): Add any other stackedGraph checks here.
380 }
381
382 // Dygraphs has many options, some of which interact with one another.
383 // To keep track of everything, we maintain two sets of options:
384 //
385 // this.user_attrs_ only options explicitly set by the user.
386 // this.attrs_ defaults, options derived from user_attrs_, data.
387 //
388 // Options are then accessed this.attr_('attr'), which first looks at
389 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
390 // defaults without overriding behavior that the user specifically asks for.
391 this.user_attrs_ = {};
392 Dygraph.update(this.user_attrs_, attrs);
393
394 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
395 this.attrs_ = {};
396 Dygraph.updateDeep(this.attrs_, Dygraph.DEFAULT_ATTRS);
397
398 this.boundaryIds_ = [];
399
400 // Create the containing DIV and other interactive elements
401 this.createInterface_();
402
403 this.start_();
404 };
405
406 /**
407 * Returns the zoomed status of the chart for one or both axes.
408 *
409 * Axis is an optional parameter. Can be set to 'x' or 'y'.
410 *
411 * The zoomed status for an axis is set whenever a user zooms using the mouse
412 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
413 * option is also specified).
414 */
415 Dygraph.prototype.isZoomed = function(axis) {
416 if (axis == null) return this.zoomed_x_ || this.zoomed_y_;
417 if (axis == 'x') return this.zoomed_x_;
418 if (axis == 'y') return this.zoomed_y_;
419 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
420 };
421
422 /**
423 * Returns information about the Dygraph object, including its containing ID.
424 */
425 Dygraph.prototype.toString = function() {
426 var maindiv = this.maindiv_;
427 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
428 return "[Dygraph " + id + "]";
429 }
430
431 /**
432 * @private
433 * Returns the value of an option. This may be set by the user (either in the
434 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
435 * per-series value.
436 * @param { String } name The name of the option, e.g. 'rollPeriod'.
437 * @param { String } [seriesName] The name of the series to which the option
438 * will be applied. If no per-series value of this option is available, then
439 * the global value is returned. This is optional.
440 * @return { ... } The value of the option.
441 */
442 Dygraph.prototype.attr_ = function(name, seriesName) {
443 // <REMOVE_FOR_COMBINED>
444 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
445 this.error('Must include options reference JS for testing');
446 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
447 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
448 'in the Dygraphs.OPTIONS_REFERENCE listing.');
449 // Only log this error once.
450 Dygraph.OPTIONS_REFERENCE[name] = true;
451 }
452 // </REMOVE_FOR_COMBINED>
453 if (seriesName &&
454 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
455 this.user_attrs_[seriesName] != null &&
456 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
457 return this.user_attrs_[seriesName][name];
458 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
459 return this.user_attrs_[name];
460 } else if (typeof(this.attrs_[name]) != 'undefined') {
461 return this.attrs_[name];
462 } else {
463 return null;
464 }
465 };
466
467 /**
468 * @private
469 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
470 * @return { ... } A function mapping string -> option value
471 */
472 Dygraph.prototype.optionsViewForAxis_ = function(axis) {
473 var self = this;
474 return function(opt) {
475 var axis_opts = self.user_attrs_['axes'];
476 if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
477 return axis_opts[axis][opt];
478 }
479 // user-specified attributes always trump defaults, even if they're less
480 // specific.
481 if (typeof(self.user_attrs_[opt]) != 'undefined') {
482 return self.user_attrs_[opt];
483 }
484
485 axis_opts = self.attrs_['axes'];
486 if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
487 return axis_opts[axis][opt];
488 }
489 // check old-style axis options
490 // TODO(danvk): add a deprecation warning if either of these match.
491 if (axis == 'y' && self.axes_[0].hasOwnProperty(opt)) {
492 return self.axes_[0][opt];
493 } else if (axis == 'y2' && self.axes_[1].hasOwnProperty(opt)) {
494 return self.axes_[1][opt];
495 }
496 return self.attr_(opt);
497 };
498 };
499
500 /**
501 * Returns the current rolling period, as set by the user or an option.
502 * @return {Number} The number of points in the rolling window
503 */
504 Dygraph.prototype.rollPeriod = function() {
505 return this.rollPeriod_;
506 };
507
508 /**
509 * Returns the currently-visible x-range. This can be affected by zooming,
510 * panning or a call to updateOptions.
511 * Returns a two-element array: [left, right].
512 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
513 */
514 Dygraph.prototype.xAxisRange = function() {
515 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
516 };
517
518 /**
519 * Returns the lower- and upper-bound x-axis values of the
520 * data set.
521 */
522 Dygraph.prototype.xAxisExtremes = function() {
523 var left = this.rawData_[0][0];
524 var right = this.rawData_[this.rawData_.length - 1][0];
525 return [left, right];
526 };
527
528 /**
529 * Returns the currently-visible y-range for an axis. This can be affected by
530 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
531 * called with no arguments, returns the range of the first axis.
532 * Returns a two-element array: [bottom, top].
533 */
534 Dygraph.prototype.yAxisRange = function(idx) {
535 if (typeof(idx) == "undefined") idx = 0;
536 if (idx < 0 || idx >= this.axes_.length) {
537 return null;
538 }
539 var axis = this.axes_[idx];
540 return [ axis.computedValueRange[0], axis.computedValueRange[1] ];
541 };
542
543 /**
544 * Returns the currently-visible y-ranges for each axis. This can be affected by
545 * zooming, panning, calls to updateOptions, etc.
546 * Returns an array of [bottom, top] pairs, one for each y-axis.
547 */
548 Dygraph.prototype.yAxisRanges = function() {
549 var ret = [];
550 for (var i = 0; i < this.axes_.length; i++) {
551 ret.push(this.yAxisRange(i));
552 }
553 return ret;
554 };
555
556 // TODO(danvk): use these functions throughout dygraphs.
557 /**
558 * Convert from data coordinates to canvas/div X/Y coordinates.
559 * If specified, do this conversion for the coordinate system of a particular
560 * axis. Uses the first axis by default.
561 * Returns a two-element array: [X, Y]
562 *
563 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
564 * instead of toDomCoords(null, y, axis).
565 */
566 Dygraph.prototype.toDomCoords = function(x, y, axis) {
567 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
568 };
569
570 /**
571 * Convert from data x coordinates to canvas/div X coordinate.
572 * If specified, do this conversion for the coordinate system of a particular
573 * axis.
574 * Returns a single value or null if x is null.
575 */
576 Dygraph.prototype.toDomXCoord = function(x) {
577 if (x == null) {
578 return null;
579 };
580
581 var area = this.plotter_.area;
582 var xRange = this.xAxisRange();
583 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
584 }
585
586 /**
587 * Convert from data x coordinates to canvas/div Y coordinate and optional
588 * axis. Uses the first axis by default.
589 *
590 * returns a single value or null if y is null.
591 */
592 Dygraph.prototype.toDomYCoord = function(y, axis) {
593 var pct = this.toPercentYCoord(y, axis);
594
595 if (pct == null) {
596 return null;
597 }
598 var area = this.plotter_.area;
599 return area.y + pct * area.h;
600 }
601
602 /**
603 * Convert from canvas/div coords to data coordinates.
604 * If specified, do this conversion for the coordinate system of a particular
605 * axis. Uses the first axis by default.
606 * Returns a two-element array: [X, Y].
607 *
608 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
609 * instead of toDataCoords(null, y, axis).
610 */
611 Dygraph.prototype.toDataCoords = function(x, y, axis) {
612 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
613 };
614
615 /**
616 * Convert from canvas/div x coordinate to data coordinate.
617 *
618 * If x is null, this returns null.
619 */
620 Dygraph.prototype.toDataXCoord = function(x) {
621 if (x == null) {
622 return null;
623 }
624
625 var area = this.plotter_.area;
626 var xRange = this.xAxisRange();
627 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
628 };
629
630 /**
631 * Convert from canvas/div y coord to value.
632 *
633 * If y is null, this returns null.
634 * if axis is null, this uses the first axis.
635 */
636 Dygraph.prototype.toDataYCoord = function(y, axis) {
637 if (y == null) {
638 return null;
639 }
640
641 var area = this.plotter_.area;
642 var yRange = this.yAxisRange(axis);
643
644 if (typeof(axis) == "undefined") axis = 0;
645 if (!this.axes_[axis].logscale) {
646 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
647 } else {
648 // Computing the inverse of toDomCoord.
649 var pct = (y - area.y) / area.h
650
651 // Computing the inverse of toPercentYCoord. The function was arrived at with
652 // the following steps:
653 //
654 // Original calcuation:
655 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
656 //
657 // Move denominator to both sides:
658 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
659 //
660 // subtract logr1, and take the negative value.
661 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
662 //
663 // Swap both sides of the equation, and we can compute the log of the
664 // return value. Which means we just need to use that as the exponent in
665 // e^exponent.
666 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
667
668 var logr1 = Dygraph.log10(yRange[1]);
669 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
670 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
671 return value;
672 }
673 };
674
675 /**
676 * Converts a y for an axis to a percentage from the top to the
677 * bottom of the drawing area.
678 *
679 * If the coordinate represents a value visible on the canvas, then
680 * the value will be between 0 and 1, where 0 is the top of the canvas.
681 * However, this method will return values outside the range, as
682 * values can fall outside the canvas.
683 *
684 * If y is null, this returns null.
685 * if axis is null, this uses the first axis.
686 *
687 * @param { Number } y The data y-coordinate.
688 * @param { Number } [axis] The axis number on which the data coordinate lives.
689 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
690 */
691 Dygraph.prototype.toPercentYCoord = function(y, axis) {
692 if (y == null) {
693 return null;
694 }
695 if (typeof(axis) == "undefined") axis = 0;
696
697 var area = this.plotter_.area;
698 var yRange = this.yAxisRange(axis);
699
700 var pct;
701 if (!this.axes_[axis].logscale) {
702 // yRange[1] - y is unit distance from the bottom.
703 // yRange[1] - yRange[0] is the scale of the range.
704 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
705 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
706 } else {
707 var logr1 = Dygraph.log10(yRange[1]);
708 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
709 }
710 return pct;
711 }
712
713 /**
714 * Converts an x value to a percentage from the left to the right of
715 * the drawing area.
716 *
717 * If the coordinate represents a value visible on the canvas, then
718 * the value will be between 0 and 1, where 0 is the left of the canvas.
719 * However, this method will return values outside the range, as
720 * values can fall outside the canvas.
721 *
722 * If x is null, this returns null.
723 * @param { Number } x The data x-coordinate.
724 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
725 */
726 Dygraph.prototype.toPercentXCoord = function(x) {
727 if (x == null) {
728 return null;
729 }
730
731 var xRange = this.xAxisRange();
732 return (x - xRange[0]) / (xRange[1] - xRange[0]);
733 };
734
735 /**
736 * Returns the number of columns (including the independent variable).
737 * @return { Integer } The number of columns.
738 */
739 Dygraph.prototype.numColumns = function() {
740 return this.rawData_[0].length;
741 };
742
743 /**
744 * Returns the number of rows (excluding any header/label row).
745 * @return { Integer } The number of rows, less any header.
746 */
747 Dygraph.prototype.numRows = function() {
748 return this.rawData_.length;
749 };
750
751 /**
752 * Returns the value in the given row and column. If the row and column exceed
753 * the bounds on the data, returns null. Also returns null if the value is
754 * missing.
755 * @param { Number} row The row number of the data (0-based). Row 0 is the
756 * first row of data, not a header row.
757 * @param { Number} col The column number of the data (0-based)
758 * @return { Number } The value in the specified cell or null if the row/col
759 * were out of range.
760 */
761 Dygraph.prototype.getValue = function(row, col) {
762 if (row < 0 || row > this.rawData_.length) return null;
763 if (col < 0 || col > this.rawData_[row].length) return null;
764
765 return this.rawData_[row][col];
766 };
767
768 /**
769 * Generates interface elements for the Dygraph: a containing div, a div to
770 * display the current point, and a textbox to adjust the rolling average
771 * period. Also creates the Renderer/Layout elements.
772 * @private
773 */
774 Dygraph.prototype.createInterface_ = function() {
775 // Create the all-enclosing graph div
776 var enclosing = this.maindiv_;
777
778 this.graphDiv = document.createElement("div");
779 this.graphDiv.style.width = this.width_ + "px";
780 this.graphDiv.style.height = this.height_ + "px";
781 enclosing.appendChild(this.graphDiv);
782
783 // Create the canvas for interactive parts of the chart.
784 this.canvas_ = Dygraph.createCanvas();
785 this.canvas_.style.position = "absolute";
786 this.canvas_.width = this.width_;
787 this.canvas_.height = this.height_;
788 this.canvas_.style.width = this.width_ + "px"; // for IE
789 this.canvas_.style.height = this.height_ + "px"; // for IE
790
791 this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
792
793 // ... and for static parts of the chart.
794 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
795 this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
796
797 if (this.attr_('showRangeSelector')) {
798 // The range selector must be created here so that its canvases and contexts get created here.
799 // For some reason, if the canvases and contexts don't get created here, things don't work in IE.
800 // The range selector also sets xAxisHeight in order to reserve space.
801 this.rangeSelector_ = new DygraphRangeSelector(this);
802 }
803
804 // The interactive parts of the graph are drawn on top of the chart.
805 this.graphDiv.appendChild(this.hidden_);
806 this.graphDiv.appendChild(this.canvas_);
807 this.mouseEventElement_ = this.createMouseEventElement_();
808
809 // Create the grapher
810 this.layout_ = new DygraphLayout(this);
811
812 if (this.rangeSelector_) {
813 // This needs to happen after the graph canvases are added to the div and the layout object is created.
814 this.rangeSelector_.addToGraph(this.graphDiv, this.layout_);
815 }
816
817 // Create the grapher
818 this.layout_ = new DygraphLayout(this);
819
820 if (this.rangeSelector_) {
821 // This needs to happen after the graph canvases are added to the div and the layout object is created.
822 this.rangeSelector_.addToGraph(this.graphDiv, this.layout_);
823 }
824
825 var dygraph = this;
826 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
827 dygraph.mouseMove_(e);
828 });
829 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
830 dygraph.mouseOut_(e);
831 });
832
833 this.createStatusMessage_();
834 this.createDragInterface_();
835
836 // Update when the window is resized.
837 // TODO(danvk): drop frames depending on complexity of the chart.
838 Dygraph.addEvent(window, 'resize', function(e) {
839 dygraph.resize();
840 });
841 };
842
843 /**
844 * Detach DOM elements in the dygraph and null out all data references.
845 * Calling this when you're done with a dygraph can dramatically reduce memory
846 * usage. See, e.g., the tests/perf.html example.
847 */
848 Dygraph.prototype.destroy = function() {
849 var removeRecursive = function(node) {
850 while (node.hasChildNodes()) {
851 removeRecursive(node.firstChild);
852 node.removeChild(node.firstChild);
853 }
854 };
855 removeRecursive(this.maindiv_);
856
857 var nullOut = function(obj) {
858 for (var n in obj) {
859 if (typeof(obj[n]) === 'object') {
860 obj[n] = null;
861 }
862 }
863 };
864
865 // These may not all be necessary, but it can't hurt...
866 nullOut(this.layout_);
867 nullOut(this.plotter_);
868 nullOut(this);
869 };
870
871 /**
872 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
873 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
874 * or the zoom rectangles) is done on this.canvas_.
875 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
876 * @return {Object} The newly-created canvas
877 * @private
878 */
879 Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
880 var h = Dygraph.createCanvas();
881 h.style.position = "absolute";
882 // TODO(danvk): h should be offset from canvas. canvas needs to include
883 // some extra area to make it easier to zoom in on the far left and far
884 // right. h needs to be precisely the plot area, so that clipping occurs.
885 h.style.top = canvas.style.top;
886 h.style.left = canvas.style.left;
887 h.width = this.width_;
888 h.height = this.height_;
889 h.style.width = this.width_ + "px"; // for IE
890 h.style.height = this.height_ + "px"; // for IE
891 return h;
892 };
893
894 /**
895 * Creates an overlay element used to handle mouse events.
896 * @return {Object} The mouse event element.
897 * @private
898 */
899 Dygraph.prototype.createMouseEventElement_ = function() {
900 if (this.isUsingExcanvas_) {
901 var elem = document.createElement("div");
902 elem.style.position = 'absolute';
903 elem.style.backgroundColor = 'white';
904 elem.style.filter = 'alpha(opacity=0)';
905 elem.style.width = this.width_ + "px";
906 elem.style.height = this.height_ + "px";
907 this.graphDiv.appendChild(elem);
908 return elem;
909 } else {
910 return this.canvas_;
911 }
912 };
913
914 /**
915 * Generate a set of distinct colors for the data series. This is done with a
916 * color wheel. Saturation/Value are customizable, and the hue is
917 * equally-spaced around the color wheel. If a custom set of colors is
918 * specified, that is used instead.
919 * @private
920 */
921 Dygraph.prototype.setColors_ = function() {
922 var num = this.attr_("labels").length - 1;
923 this.colors_ = [];
924 var colors = this.attr_('colors');
925 if (!colors) {
926 var sat = this.attr_('colorSaturation') || 1.0;
927 var val = this.attr_('colorValue') || 0.5;
928 var half = Math.ceil(num / 2);
929 for (var i = 1; i <= num; i++) {
930 if (!this.visibility()[i-1]) continue;
931 // alternate colors for high contrast.
932 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
933 var hue = (1.0 * idx/ (1 + num));
934 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
935 }
936 } else {
937 for (var i = 0; i < num; i++) {
938 if (!this.visibility()[i]) continue;
939 var colorStr = colors[i % colors.length];
940 this.colors_.push(colorStr);
941 }
942 }
943
944 this.plotter_.setColors(this.colors_);
945 };
946
947 /**
948 * Return the list of colors. This is either the list of colors passed in the
949 * attributes or the autogenerated list of rgb(r,g,b) strings.
950 * @return {Array<string>} The list of colors.
951 */
952 Dygraph.prototype.getColors = function() {
953 return this.colors_;
954 };
955
956 /**
957 * Create the div that contains information on the selected point(s)
958 * This goes in the top right of the canvas, unless an external div has already
959 * been specified.
960 * @private
961 */
962 Dygraph.prototype.createStatusMessage_ = function() {
963 var userLabelsDiv = this.user_attrs_["labelsDiv"];
964 if (userLabelsDiv && null != userLabelsDiv
965 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
966 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
967 }
968 if (!this.attr_("labelsDiv")) {
969 var divWidth = this.attr_('labelsDivWidth');
970 var messagestyle = {
971 "position": "absolute",
972 "fontSize": "14px",
973 "zIndex": 10,
974 "width": divWidth + "px",
975 "top": "0px",
976 "left": (this.width_ - divWidth - 2) + "px",
977 "background": "white",
978 "textAlign": "left",
979 "overflow": "hidden"};
980 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
981 var div = document.createElement("div");
982 div.className = "dygraph-legend";
983 for (var name in messagestyle) {
984 if (messagestyle.hasOwnProperty(name)) {
985 div.style[name] = messagestyle[name];
986 }
987 }
988 this.graphDiv.appendChild(div);
989 this.attrs_.labelsDiv = div;
990 }
991 };
992
993 /**
994 * Position the labels div so that:
995 * - its right edge is flush with the right edge of the charting area
996 * - its top edge is flush with the top edge of the charting area
997 * @private
998 */
999 Dygraph.prototype.positionLabelsDiv_ = function() {
1000 // Don't touch a user-specified labelsDiv.
1001 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
1002
1003 var area = this.plotter_.area;
1004 var div = this.attr_("labelsDiv");
1005 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
1006 div.style.top = area.y + "px";
1007 };
1008
1009 /**
1010 * Create the text box to adjust the averaging period
1011 * @private
1012 */
1013 Dygraph.prototype.createRollInterface_ = function() {
1014 // Create a roller if one doesn't exist already.
1015 if (!this.roller_) {
1016 this.roller_ = document.createElement("input");
1017 this.roller_.type = "text";
1018 this.roller_.style.display = "none";
1019 this.graphDiv.appendChild(this.roller_);
1020 }
1021
1022 var display = this.attr_('showRoller') ? 'block' : 'none';
1023
1024 var area = this.plotter_.area;
1025 var textAttr = { "position": "absolute",
1026 "zIndex": 10,
1027 "top": (area.y + area.h - 25) + "px",
1028 "left": (area.x + 1) + "px",
1029 "display": display
1030 };
1031 this.roller_.size = "2";
1032 this.roller_.value = this.rollPeriod_;
1033 for (var name in textAttr) {
1034 if (textAttr.hasOwnProperty(name)) {
1035 this.roller_.style[name] = textAttr[name];
1036 }
1037 }
1038
1039 var dygraph = this;
1040 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
1041 };
1042
1043 /**
1044 * @private
1045 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1046 * canvas (i.e. DOM Coords).
1047 */
1048 Dygraph.prototype.dragGetX_ = function(e, context) {
1049 return Dygraph.pageX(e) - context.px
1050 };
1051
1052 /**
1053 * @private
1054 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1055 * canvas (i.e. DOM Coords).
1056 */
1057 Dygraph.prototype.dragGetY_ = function(e, context) {
1058 return Dygraph.pageY(e) - context.py
1059 };
1060
1061 /**
1062 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1063 * events.
1064 * @private
1065 */
1066 Dygraph.prototype.createDragInterface_ = function() {
1067 var context = {
1068 // Tracks whether the mouse is down right now
1069 isZooming: false,
1070 isPanning: false, // is this drag part of a pan?
1071 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
1072 dragStartX: null, // pixel coordinates
1073 dragStartY: null, // pixel coordinates
1074 dragEndX: null, // pixel coordinates
1075 dragEndY: null, // pixel coordinates
1076 dragDirection: null,
1077 prevEndX: null, // pixel coordinates
1078 prevEndY: null, // pixel coordinates
1079 prevDragDirection: null,
1080
1081 // The value on the left side of the graph when a pan operation starts.
1082 initialLeftmostDate: null,
1083
1084 // The number of units each pixel spans. (This won't be valid for log
1085 // scales)
1086 xUnitsPerPixel: null,
1087
1088 // TODO(danvk): update this comment
1089 // The range in second/value units that the viewport encompasses during a
1090 // panning operation.
1091 dateRange: null,
1092
1093 // Top-left corner of the canvas, in DOM coords
1094 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1095 px: 0,
1096 py: 0,
1097
1098 // Values for use with panEdgeFraction, which limit how far outside the
1099 // graph's data boundaries it can be panned.
1100 boundedDates: null, // [minDate, maxDate]
1101 boundedValues: null, // [[minValue, maxValue] ...]
1102
1103 initializeMouseDown: function(event, g, context) {
1104 // prevents mouse drags from selecting page text.
1105 if (event.preventDefault) {
1106 event.preventDefault(); // Firefox, Chrome, etc.
1107 } else {
1108 event.returnValue = false; // IE
1109 event.cancelBubble = true;
1110 }
1111
1112 context.px = Dygraph.findPosX(g.canvas_);
1113 context.py = Dygraph.findPosY(g.canvas_);
1114 context.dragStartX = g.dragGetX_(event, context);
1115 context.dragStartY = g.dragGetY_(event, context);
1116 }
1117 };
1118
1119 var interactionModel = this.attr_("interactionModel");
1120
1121 // Self is the graph.
1122 var self = this;
1123
1124 // Function that binds the graph and context to the handler.
1125 var bindHandler = function(handler) {
1126 return function(event) {
1127 handler(event, self, context);
1128 };
1129 };
1130
1131 for (var eventName in interactionModel) {
1132 if (!interactionModel.hasOwnProperty(eventName)) continue;
1133 Dygraph.addEvent(this.mouseEventElement_, eventName,
1134 bindHandler(interactionModel[eventName]));
1135 }
1136
1137 // If the user releases the mouse button during a drag, but not over the
1138 // canvas, then it doesn't count as a zooming action.
1139 Dygraph.addEvent(document, 'mouseup', function(event) {
1140 if (context.isZooming || context.isPanning) {
1141 context.isZooming = false;
1142 context.dragStartX = null;
1143 context.dragStartY = null;
1144 }
1145
1146 if (context.isPanning) {
1147 context.isPanning = false;
1148 context.draggingDate = null;
1149 context.dateRange = null;
1150 for (var i = 0; i < self.axes_.length; i++) {
1151 delete self.axes_[i].draggingValue;
1152 delete self.axes_[i].dragValueRange;
1153 }
1154 }
1155 });
1156 };
1157
1158 /**
1159 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1160 * up any previous zoom rectangles that were drawn. This could be optimized to
1161 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1162 * dots.
1163 *
1164 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1165 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1166 * @param {Number} startX The X position where the drag started, in canvas
1167 * coordinates.
1168 * @param {Number} endX The current X position of the drag, in canvas coords.
1169 * @param {Number} startY The Y position where the drag started, in canvas
1170 * coordinates.
1171 * @param {Number} endY The current Y position of the drag, in canvas coords.
1172 * @param {Number} prevDirection the value of direction on the previous call to
1173 * this function. Used to avoid excess redrawing
1174 * @param {Number} prevEndX The value of endX on the previous call to this
1175 * function. Used to avoid excess redrawing
1176 * @param {Number} prevEndY The value of endY on the previous call to this
1177 * function. Used to avoid excess redrawing
1178 * @private
1179 */
1180 Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1181 endY, prevDirection, prevEndX,
1182 prevEndY) {
1183 var ctx = this.canvas_ctx_;
1184
1185 // Clean up from the previous rect if necessary
1186 if (prevDirection == Dygraph.HORIZONTAL) {
1187 ctx.clearRect(Math.min(startX, prevEndX), this.layout_.getPlotArea().y,
1188 Math.abs(startX - prevEndX), this.layout_.getPlotArea().h);
1189 } else if (prevDirection == Dygraph.VERTICAL){
1190 ctx.clearRect(this.layout_.getPlotArea().x, Math.min(startY, prevEndY),
1191 this.layout_.getPlotArea().w, Math.abs(startY - prevEndY));
1192 }
1193
1194 // Draw a light-grey rectangle to show the new viewing area
1195 if (direction == Dygraph.HORIZONTAL) {
1196 if (endX && startX) {
1197 ctx.fillStyle = "rgba(128,128,128,0.33)";
1198 ctx.fillRect(Math.min(startX, endX), this.layout_.getPlotArea().y,
1199 Math.abs(endX - startX), this.layout_.getPlotArea().h);
1200 }
1201 } else if (direction == Dygraph.VERTICAL) {
1202 if (endY && startY) {
1203 ctx.fillStyle = "rgba(128,128,128,0.33)";
1204 ctx.fillRect(this.layout_.getPlotArea().x, Math.min(startY, endY),
1205 this.layout_.getPlotArea().w, Math.abs(endY - startY));
1206 }
1207 }
1208
1209 if (this.isUsingExcanvas_) {
1210 this.currentZoomRectArgs_ = [direction, startX, endX, startY, endY, 0, 0, 0];
1211 }
1212 };
1213
1214 /**
1215 * Clear the zoom rectangle (and perform no zoom).
1216 * @private
1217 */
1218 Dygraph.prototype.clearZoomRect_ = function() {
1219 this.currentZoomRectArgs_ = null;
1220 this.canvas_ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
1221 };
1222
1223 /**
1224 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1225 * the canvas. The exact zoom window may be slightly larger if there are no data
1226 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1227 * which accepts dates that match the raw data. This function redraws the graph.
1228 *
1229 * @param {Number} lowX The leftmost pixel value that should be visible.
1230 * @param {Number} highX The rightmost pixel value that should be visible.
1231 * @private
1232 */
1233 Dygraph.prototype.doZoomX_ = function(lowX, highX) {
1234 this.currentZoomRectArgs_ = null;
1235 // Find the earliest and latest dates contained in this canvasx range.
1236 // Convert the call to date ranges of the raw data.
1237 var minDate = this.toDataXCoord(lowX);
1238 var maxDate = this.toDataXCoord(highX);
1239 this.doZoomXDates_(minDate, maxDate);
1240 };
1241
1242 /**
1243 * Transition function to use in animations. Returns values between 0.0
1244 * (totally old values) and 1.0 (totally new values) for each frame.
1245 * @private
1246 */
1247 Dygraph.zoomAnimationFunction = function(frame, numFrames) {
1248 var k = 1.5;
1249 return (1.0 - Math.pow(k, -frame)) / (1.0 - Math.pow(k, -numFrames));
1250 };
1251
1252 /**
1253 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1254 * method with doZoomX which accepts pixel coordinates. This function redraws
1255 * the graph.
1256 *
1257 * @param {Number} minDate The minimum date that should be visible.
1258 * @param {Number} maxDate The maximum date that should be visible.
1259 * @private
1260 */
1261 Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
1262 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1263 // can produce strange effects. Rather than the y-axis transitioning slowly
1264 // between values, it can jerk around.)
1265 var old_window = this.xAxisRange();
1266 var new_window = [minDate, maxDate];
1267 this.zoomed_x_ = true;
1268 var that = this;
1269 this.doAnimatedZoom(old_window, new_window, null, null, function() {
1270 if (that.attr_("zoomCallback")) {
1271 that.attr_("zoomCallback")(minDate, maxDate, that.yAxisRanges());
1272 }
1273 });
1274 };
1275
1276 /**
1277 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1278 * the canvas. This function redraws the graph.
1279 *
1280 * @param {Number} lowY The topmost pixel value that should be visible.
1281 * @param {Number} highY The lowest pixel value that should be visible.
1282 * @private
1283 */
1284 Dygraph.prototype.doZoomY_ = function(lowY, highY) {
1285 this.currentZoomRectArgs_ = null;
1286 // Find the highest and lowest values in pixel range for each axis.
1287 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1288 // This is because pixels increase as you go down on the screen, whereas data
1289 // coordinates increase as you go up the screen.
1290 var oldValueRanges = this.yAxisRanges();
1291 var newValueRanges = [];
1292 for (var i = 0; i < this.axes_.length; i++) {
1293 var hi = this.toDataYCoord(lowY, i);
1294 var low = this.toDataYCoord(highY, i);
1295 newValueRanges.push([low, hi]);
1296 }
1297
1298 this.zoomed_y_ = true;
1299 var that = this;
1300 this.doAnimatedZoom(null, null, oldValueRanges, newValueRanges, function() {
1301 if (that.attr_("zoomCallback")) {
1302 var xRange = that.xAxisRange();
1303 var yRange = that.yAxisRange();
1304 that.attr_("zoomCallback")(xRange[0], xRange[1], that.yAxisRanges());
1305 }
1306 });
1307 };
1308
1309 /**
1310 * Reset the zoom to the original view coordinates. This is the same as
1311 * double-clicking on the graph.
1312 *
1313 * @private
1314 */
1315 Dygraph.prototype.doUnzoom_ = function() {
1316 var dirty = false, dirtyX = false, dirtyY = false;
1317 if (this.dateWindow_ != null) {
1318 dirty = true;
1319 dirtyX = true;
1320 }
1321
1322 for (var i = 0; i < this.axes_.length; i++) {
1323 if (this.axes_[i].valueWindow != null) {
1324 dirty = true;
1325 dirtyY = true;
1326 }
1327 }
1328
1329 // Clear any selection, since it's likely to be drawn in the wrong place.
1330 this.clearSelection();
1331
1332 if (dirty) {
1333 this.zoomed_x_ = false;
1334 this.zoomed_y_ = false;
1335
1336 var minDate = this.rawData_[0][0];
1337 var maxDate = this.rawData_[this.rawData_.length - 1][0];
1338
1339 // With only one frame, don't bother calculating extreme ranges.
1340 // TODO(danvk): merge this block w/ the code below.
1341 if (!this.attr_("animatedZooms")) {
1342 this.dateWindow_ = null;
1343 for (var i = 0; i < this.axes_.length; i++) {
1344 if (this.axes_[i].valueWindow != null) {
1345 delete this.axes_[i].valueWindow;
1346 }
1347 }
1348 this.drawGraph_();
1349 if (this.attr_("zoomCallback")) {
1350 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
1351 }
1352 return;
1353 }
1354
1355 var oldWindow=null, newWindow=null, oldValueRanges=null, newValueRanges=null;
1356 if (dirtyX) {
1357 oldWindow = this.xAxisRange();
1358 newWindow = [minDate, maxDate];
1359 }
1360
1361 if (dirtyY) {
1362 oldValueRanges = this.yAxisRanges();
1363 // TODO(danvk): this is pretty inefficient
1364 var packed = this.gatherDatasets_(this.rolledSeries_, null);
1365 var extremes = packed[1];
1366
1367 // this has the side-effect of modifying this.axes_.
1368 // this doesn't make much sense in this context, but it's convenient (we
1369 // need this.axes_[*].extremeValues) and not harmful since we'll be
1370 // calling drawGraph_ shortly, which clobbers these values.
1371 this.computeYAxisRanges_(extremes);
1372
1373 newValueRanges = [];
1374 for (var i = 0; i < this.axes_.length; i++) {
1375 newValueRanges.push(this.axes_[i].extremeRange);
1376 }
1377 }
1378
1379 var that = this;
1380 this.doAnimatedZoom(oldWindow, newWindow, oldValueRanges, newValueRanges,
1381 function() {
1382 that.dateWindow_ = null;
1383 for (var i = 0; i < that.axes_.length; i++) {
1384 if (that.axes_[i].valueWindow != null) {
1385 delete that.axes_[i].valueWindow;
1386 }
1387 }
1388 if (that.attr_("zoomCallback")) {
1389 that.attr_("zoomCallback")(minDate, maxDate, that.yAxisRanges());
1390 }
1391 });
1392 }
1393 };
1394
1395 /**
1396 * Combined animation logic for all zoom functions.
1397 * either the x parameters or y parameters may be null.
1398 * @private
1399 */
1400 Dygraph.prototype.doAnimatedZoom = function(oldXRange, newXRange, oldYRanges, newYRanges, callback) {
1401 var steps = this.attr_("animatedZooms") ? Dygraph.ANIMATION_STEPS : 1;
1402
1403 var windows = [];
1404 var valueRanges = [];
1405
1406 if (oldXRange != null && newXRange != null) {
1407 for (var step = 1; step <= steps; step++) {
1408 var frac = Dygraph.zoomAnimationFunction(step, steps);
1409 windows[step-1] = [oldXRange[0]*(1-frac) + frac*newXRange[0],
1410 oldXRange[1]*(1-frac) + frac*newXRange[1]];
1411 }
1412 }
1413
1414 if (oldYRanges != null && newYRanges != null) {
1415 for (var step = 1; step <= steps; step++) {
1416 var frac = Dygraph.zoomAnimationFunction(step, steps);
1417 var thisRange = [];
1418 for (var j = 0; j < this.axes_.length; j++) {
1419 thisRange.push([oldYRanges[j][0]*(1-frac) + frac*newYRanges[j][0],
1420 oldYRanges[j][1]*(1-frac) + frac*newYRanges[j][1]]);
1421 }
1422 valueRanges[step-1] = thisRange;
1423 }
1424 }
1425
1426 var that = this;
1427 Dygraph.repeatAndCleanup(function(step) {
1428 if (valueRanges.length) {
1429 for (var i = 0; i < that.axes_.length; i++) {
1430 var w = valueRanges[step][i];
1431 that.axes_[i].valueWindow = [w[0], w[1]];
1432 }
1433 }
1434 if (windows.length) {
1435 that.dateWindow_ = windows[step];
1436 }
1437 that.drawGraph_();
1438 }, steps, Dygraph.ANIMATION_DURATION / steps, callback);
1439 };
1440
1441 /**
1442 * When the mouse moves in the canvas, display information about a nearby data
1443 * point and draw dots over those points in the data series. This function
1444 * takes care of cleanup of previously-drawn dots.
1445 * @param {Object} event The mousemove event from the browser.
1446 * @private
1447 */
1448 Dygraph.prototype.mouseMove_ = function(event) {
1449 // This prevents JS errors when mousing over the canvas before data loads.
1450 var points = this.layout_.points;
1451 if (points === undefined) return;
1452
1453 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
1454
1455 var lastx = -1;
1456 var lasty = -1;
1457
1458 // Loop through all the points and find the date nearest to our current
1459 // location.
1460 var minDist = 1e+100;
1461 var idx = -1;
1462 for (var i = 0; i < points.length; i++) {
1463 var point = points[i];
1464 if (point == null) continue;
1465 var dist = Math.abs(point.canvasx - canvasx);
1466 if (dist > minDist) continue;
1467 minDist = dist;
1468 idx = i;
1469 }
1470 if (idx >= 0) lastx = points[idx].xval;
1471
1472 // Extract the points we've selected
1473 this.selPoints_ = [];
1474 var l = points.length;
1475 if (!this.attr_("stackedGraph")) {
1476 for (var i = 0; i < l; i++) {
1477 if (points[i].xval == lastx) {
1478 this.selPoints_.push(points[i]);
1479 }
1480 }
1481 } else {
1482 // Need to 'unstack' points starting from the bottom
1483 var cumulative_sum = 0;
1484 for (var i = l - 1; i >= 0; i--) {
1485 if (points[i].xval == lastx) {
1486 var p = {}; // Clone the point since we modify it
1487 for (var k in points[i]) {
1488 p[k] = points[i][k];
1489 }
1490 p.yval -= cumulative_sum;
1491 cumulative_sum += p.yval;
1492 this.selPoints_.push(p);
1493 }
1494 }
1495 this.selPoints_.reverse();
1496 }
1497
1498 if (this.attr_("highlightCallback")) {
1499 var px = this.lastx_;
1500 if (px !== null && lastx != px) {
1501 // only fire if the selected point has changed.
1502 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
1503 }
1504 }
1505
1506 // Save last x position for callbacks.
1507 this.lastx_ = lastx;
1508
1509 this.updateSelection_();
1510 };
1511
1512 /**
1513 * Transforms layout_.points index into data row number.
1514 * @param int layout_.points index
1515 * @return int row number, or -1 if none could be found.
1516 * @private
1517 */
1518 Dygraph.prototype.idxToRow_ = function(idx) {
1519 if (idx < 0) return -1;
1520
1521 for (var i in this.layout_.datasets) {
1522 if (idx < this.layout_.datasets[i].length) {
1523 return this.boundaryIds_[0][0]+idx;
1524 }
1525 idx -= this.layout_.datasets[i].length;
1526 }
1527 return -1;
1528 };
1529
1530 /**
1531 * @private
1532 * Generates HTML for the legend which is displayed when hovering over the
1533 * chart. If no selected points are specified, a default legend is returned
1534 * (this may just be the empty string).
1535 * @param { Number } [x] The x-value of the selected points.
1536 * @param { [Object] } [sel_points] List of selected points for the given
1537 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1538 */
1539 Dygraph.prototype.generateLegendHTML_ = function(x, sel_points) {
1540 // If no points are selected, we display a default legend. Traditionally,
1541 // this has been blank. But a better default would be a conventional legend,
1542 // which provides essential information for a non-interactive chart.
1543 if (typeof(x) === 'undefined') {
1544 if (this.attr_('legend') != 'always') return '';
1545
1546 var sepLines = this.attr_('labelsSeparateLines');
1547 var labels = this.attr_('labels');
1548 var html = '';
1549 for (var i = 1; i < labels.length; i++) {
1550 if (!this.visibility()[i - 1]) continue;
1551 var c = this.plotter_.colors[labels[i]];
1552 if (html != '') html += (sepLines ? '<br/>' : ' ');
1553 html += "<b><span style='color: " + c + ";'>&mdash;" + labels[i] +
1554 "</span></b>";
1555 }
1556 return html;
1557 }
1558
1559 var xOptView = this.optionsViewForAxis_('x');
1560 var xvf = xOptView('valueFormatter');
1561 var html = xvf(x, xOptView, this.attr_('labels')[0], this) + ":";
1562
1563 var yOptViews = [];
1564 var num_axes = this.numAxes();
1565 for (var i = 0; i < num_axes; i++) {
1566 yOptViews[i] = this.optionsViewForAxis_('y' + (i ? 1 + i : ''));
1567 }
1568 var showZeros = this.attr_("labelsShowZeroValues");
1569 var sepLines = this.attr_("labelsSeparateLines");
1570 for (var i = 0; i < this.selPoints_.length; i++) {
1571 var pt = this.selPoints_[i];
1572 if (pt.yval == 0 && !showZeros) continue;
1573 if (!Dygraph.isOK(pt.canvasy)) continue;
1574 if (sepLines) html += "<br/>";
1575
1576 var yOptView = yOptViews[this.seriesToAxisMap_[pt.name]];
1577 var fmtFunc = yOptView('valueFormatter');
1578 var c = this.plotter_.colors[pt.name];
1579 var yval = fmtFunc(pt.yval, yOptView, pt.name, this);
1580
1581 // TODO(danvk): use a template string here and make it an attribute.
1582 html += " <b><span style='color: " + c + ";'>"
1583 + pt.name + "</span></b>:"
1584 + yval;
1585 }
1586 return html;
1587 };
1588
1589 /**
1590 * @private
1591 * Displays information about the selected points in the legend. If there is no
1592 * selection, the legend will be cleared.
1593 * @param { Number } [x] The x-value of the selected points.
1594 * @param { [Object] } [sel_points] List of selected points for the given
1595 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1596 */
1597 Dygraph.prototype.setLegendHTML_ = function(x, sel_points) {
1598 var html = this.generateLegendHTML_(x, sel_points);
1599 var labelsDiv = this.attr_("labelsDiv");
1600 if (labelsDiv !== null) {
1601 labelsDiv.innerHTML = html;
1602 } else {
1603 if (typeof(this.shown_legend_error_) == 'undefined') {
1604 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1605 this.shown_legend_error_ = true;
1606 }
1607 }
1608 };
1609
1610 /**
1611 * Draw dots over the selectied points in the data series. This function
1612 * takes care of cleanup of previously-drawn dots.
1613 * @private
1614 */
1615 Dygraph.prototype.updateSelection_ = function() {
1616 // Clear the previously drawn vertical, if there is one
1617 var ctx = this.canvas_ctx_;
1618 if (this.previousVerticalX_ >= 0) {
1619 // Determine the maximum highlight circle size.
1620 var maxCircleSize = 0;
1621 var labels = this.attr_('labels');
1622 for (var i = 1; i < labels.length; i++) {
1623 var r = this.attr_('highlightCircleSize', labels[i]);
1624 if (r > maxCircleSize) maxCircleSize = r;
1625 }
1626 var px = this.previousVerticalX_;
1627 ctx.clearRect(px - maxCircleSize - 1, 0,
1628 2 * maxCircleSize + 2, this.height_);
1629 }
1630
1631 if (this.isUsingExcanvas_ && this.currentZoomRectArgs_) {
1632 Dygraph.prototype.drawZoomRect_.apply(this, this.currentZoomRectArgs_);
1633 }
1634
1635 if (this.selPoints_.length > 0) {
1636 // Set the status message to indicate the selected point(s)
1637 if (this.attr_('showLabelsOnHighlight')) {
1638 this.setLegendHTML_(this.lastx_, this.selPoints_);
1639 }
1640
1641 // Draw colored circles over the center of each selected point
1642 var canvasx = this.selPoints_[0].canvasx;
1643 ctx.save();
1644 for (var i = 0; i < this.selPoints_.length; i++) {
1645 var pt = this.selPoints_[i];
1646 if (!Dygraph.isOK(pt.canvasy)) continue;
1647
1648 var circleSize = this.attr_('highlightCircleSize', pt.name);
1649 ctx.beginPath();
1650 ctx.fillStyle = this.plotter_.colors[pt.name];
1651 ctx.arc(canvasx, pt.canvasy, circleSize, 0, 2 * Math.PI, false);
1652 ctx.fill();
1653 }
1654 ctx.restore();
1655
1656 this.previousVerticalX_ = canvasx;
1657 }
1658 };
1659
1660 /**
1661 * Manually set the selected points and display information about them in the
1662 * legend. The selection can be cleared using clearSelection() and queried
1663 * using getSelection().
1664 * @param { Integer } row number that should be highlighted (i.e. appear with
1665 * hover dots on the chart). Set to false to clear any selection.
1666 */
1667 Dygraph.prototype.setSelection = function(row) {
1668 // Extract the points we've selected
1669 this.selPoints_ = [];
1670 var pos = 0;
1671
1672 if (row !== false) {
1673 row = row - this.boundaryIds_[0][0];
1674 }
1675
1676 if (row !== false && row >= 0) {
1677 for (var i in this.layout_.datasets) {
1678 if (row < this.layout_.datasets[i].length) {
1679 var point = this.layout_.points[pos+row];
1680
1681 if (this.attr_("stackedGraph")) {
1682 point = this.layout_.unstackPointAtIndex(pos+row);
1683 }
1684
1685 this.selPoints_.push(point);
1686 }
1687 pos += this.layout_.datasets[i].length;
1688 }
1689 }
1690
1691 if (this.selPoints_.length) {
1692 this.lastx_ = this.selPoints_[0].xval;
1693 this.updateSelection_();
1694 } else {
1695 this.clearSelection();
1696 }
1697
1698 };
1699
1700 /**
1701 * The mouse has left the canvas. Clear out whatever artifacts remain
1702 * @param {Object} event the mouseout event from the browser.
1703 * @private
1704 */
1705 Dygraph.prototype.mouseOut_ = function(event) {
1706 if (this.attr_("unhighlightCallback")) {
1707 this.attr_("unhighlightCallback")(event);
1708 }
1709
1710 if (this.attr_("hideOverlayOnMouseOut")) {
1711 this.clearSelection();
1712 }
1713 };
1714
1715 /**
1716 * Clears the current selection (i.e. points that were highlighted by moving
1717 * the mouse over the chart).
1718 */
1719 Dygraph.prototype.clearSelection = function() {
1720 // Get rid of the overlay data
1721 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
1722 this.setLegendHTML_();
1723 this.selPoints_ = [];
1724 this.lastx_ = -1;
1725 }
1726
1727 /**
1728 * Returns the number of the currently selected row. To get data for this row,
1729 * you can use the getValue method.
1730 * @return { Integer } row number, or -1 if nothing is selected
1731 */
1732 Dygraph.prototype.getSelection = function() {
1733 if (!this.selPoints_ || this.selPoints_.length < 1) {
1734 return -1;
1735 }
1736
1737 for (var row=0; row<this.layout_.points.length; row++ ) {
1738 if (this.layout_.points[row].x == this.selPoints_[0].x) {
1739 return row + this.boundaryIds_[0][0];
1740 }
1741 }
1742 return -1;
1743 };
1744
1745 /**
1746 * Fires when there's data available to be graphed.
1747 * @param {String} data Raw CSV data to be plotted
1748 * @private
1749 */
1750 Dygraph.prototype.loadedEvent_ = function(data) {
1751 this.rawData_ = this.parseCSV_(data);
1752 this.predraw_();
1753 };
1754
1755 /**
1756 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1757 * @private
1758 */
1759 Dygraph.prototype.addXTicks_ = function() {
1760 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1761 var range;
1762 if (this.dateWindow_) {
1763 range = [this.dateWindow_[0], this.dateWindow_[1]];
1764 } else {
1765 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
1766 }
1767
1768 var xAxisOptionsView = this.optionsViewForAxis_('x');
1769 var xTicks = xAxisOptionsView('ticker')(
1770 range[0],
1771 range[1],
1772 this.width_, // TODO(danvk): should be area.width
1773 xAxisOptionsView,
1774 this);
1775 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
1776 // console.log(msg);
1777 this.layout_.setXTicks(xTicks);
1778 };
1779
1780 /**
1781 * @private
1782 * Computes the range of the data series (including confidence intervals).
1783 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
1784 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
1785 * @return [low, high]
1786 */
1787 Dygraph.prototype.extremeValues_ = function(series) {
1788 var minY = null, maxY = null;
1789
1790 var bars = this.attr_("errorBars") || this.attr_("customBars");
1791 if (bars) {
1792 // With custom bars, maxY is the max of the high values.
1793 for (var j = 0; j < series.length; j++) {
1794 var y = series[j][1][0];
1795 if (!y) continue;
1796 var low = y - series[j][1][1];
1797 var high = y + series[j][1][2];
1798 if (low > y) low = y; // this can happen with custom bars,
1799 if (high < y) high = y; // e.g. in tests/custom-bars.html
1800 if (maxY == null || high > maxY) {
1801 maxY = high;
1802 }
1803 if (minY == null || low < minY) {
1804 minY = low;
1805 }
1806 }
1807 } else {
1808 for (var j = 0; j < series.length; j++) {
1809 var y = series[j][1];
1810 if (y === null || isNaN(y)) continue;
1811 if (maxY == null || y > maxY) {
1812 maxY = y;
1813 }
1814 if (minY == null || y < minY) {
1815 minY = y;
1816 }
1817 }
1818 }
1819
1820 return [minY, maxY];
1821 };
1822
1823 /**
1824 * @private
1825 * This function is called once when the chart's data is changed or the options
1826 * dictionary is updated. It is _not_ called when the user pans or zooms. The
1827 * idea is that values derived from the chart's data can be computed here,
1828 * rather than every time the chart is drawn. This includes things like the
1829 * number of axes, rolling averages, etc.
1830 */
1831 Dygraph.prototype.predraw_ = function() {
1832 var start = new Date();
1833
1834 // TODO(danvk): move more computations out of drawGraph_ and into here.
1835 this.computeYAxes_();
1836
1837 // Create a new plotter.
1838 if (this.plotter_) this.plotter_.clear();
1839 this.plotter_ = new DygraphCanvasRenderer(this,
1840 this.hidden_,
1841 this.hidden_ctx_,
1842 this.layout_);
1843
1844 // The roller sits in the bottom left corner of the chart. We don't know where
1845 // this will be until the options are available, so it's positioned here.
1846 this.createRollInterface_();
1847
1848 // Same thing applies for the labelsDiv. It's right edge should be flush with
1849 // the right edge of the charting area (which may not be the same as the right
1850 // edge of the div, if we have two y-axes.
1851 this.positionLabelsDiv_();
1852
1853 if (this.rangeSelector_) {
1854 this.rangeSelector_.renderStaticLayer();
1855 }
1856
1857 // Convert the raw data (a 2D array) into the internal format and compute
1858 // rolling averages.
1859 this.rolledSeries_ = [null]; // x-axis is the first series and it's special
1860 for (var i = 1; i < this.rawData_[0].length; i++) {
1861 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
1862 var logScale = this.attr_('logscale', i);
1863 var series = this.extractSeries_(this.rawData_, i, logScale, connectSeparatedPoints);
1864 series = this.rollingAverage(series, this.rollPeriod_);
1865 this.rolledSeries_.push(series);
1866 }
1867
1868 // If the data or options have changed, then we'd better redraw.
1869 this.drawGraph_();
1870
1871 // This is used to determine whether to do various animations.
1872 var end = new Date();
1873 this.drawingTimeMs_ = (end - start);
1874 };
1875
1876 /**
1877 * Loop over all fields and create datasets, calculating extreme y-values for
1878 * each series and extreme x-indices as we go.
1879 *
1880 * dateWindow is passed in as an explicit parameter so that we can compute
1881 * extreme values "speculatively", i.e. without actually setting state on the
1882 * dygraph.
1883 *
1884 * TODO(danvk): make this more of a true function
1885 * @return [ datasets, seriesExtremes, boundaryIds ]
1886 * @private
1887 */
1888 Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
1889 var boundaryIds = [];
1890 var cumulative_y = []; // For stacked series.
1891 var datasets = [];
1892 var extremes = {}; // series name -> [low, high]
1893
1894 // Loop over the fields (series). Go from the last to the first,
1895 // because if they're stacked that's how we accumulate the values.
1896 var num_series = rolledSeries.length - 1;
1897 for (var i = num_series; i >= 1; i--) {
1898 if (!this.visibility()[i - 1]) continue;
1899
1900 // TODO(danvk): is this copy really necessary?
1901 var series = [];
1902 for (var j = 0; j < rolledSeries[i].length; j++) {
1903 series.push(rolledSeries[i][j]);
1904 }
1905
1906 // Prune down to the desired range, if necessary (for zooming)
1907 // Because there can be lines going to points outside of the visible area,
1908 // we actually prune to visible points, plus one on either side.
1909 var bars = this.attr_("errorBars") || this.attr_("customBars");
1910 if (dateWindow) {
1911 var low = dateWindow[0];
1912 var high = dateWindow[1];
1913 var pruned = [];
1914 // TODO(danvk): do binary search instead of linear search.
1915 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
1916 var firstIdx = null, lastIdx = null;
1917 for (var k = 0; k < series.length; k++) {
1918 if (series[k][0] >= low && firstIdx === null) {
1919 firstIdx = k;
1920 }
1921 if (series[k][0] <= high) {
1922 lastIdx = k;
1923 }
1924 }
1925 if (firstIdx === null) firstIdx = 0;
1926 if (firstIdx > 0) firstIdx--;
1927 if (lastIdx === null) lastIdx = series.length - 1;
1928 if (lastIdx < series.length - 1) lastIdx++;
1929 boundaryIds[i-1] = [firstIdx, lastIdx];
1930 for (var k = firstIdx; k <= lastIdx; k++) {
1931 pruned.push(series[k]);
1932 }
1933 series = pruned;
1934 } else {
1935 boundaryIds[i-1] = [0, series.length-1];
1936 }
1937
1938 var seriesExtremes = this.extremeValues_(series);
1939
1940 if (bars) {
1941 for (var j=0; j<series.length; j++) {
1942 series[j] = [series[j][0],
1943 series[j][1][0],
1944 series[j][1][1],
1945 series[j][1][2]];
1946 }
1947 } else if (this.attr_("stackedGraph")) {
1948 var l = series.length;
1949 var actual_y;
1950 for (var j = 0; j < l; j++) {
1951 // If one data set has a NaN, let all subsequent stacked
1952 // sets inherit the NaN -- only start at 0 for the first set.
1953 var x = series[j][0];
1954 if (cumulative_y[x] === undefined) {
1955 cumulative_y[x] = 0;
1956 }
1957
1958 actual_y = series[j][1];
1959 cumulative_y[x] += actual_y;
1960
1961 series[j] = [x, cumulative_y[x]]
1962
1963 if (cumulative_y[x] > seriesExtremes[1]) {
1964 seriesExtremes[1] = cumulative_y[x];
1965 }
1966 if (cumulative_y[x] < seriesExtremes[0]) {
1967 seriesExtremes[0] = cumulative_y[x];
1968 }
1969 }
1970 }
1971
1972 var seriesName = this.attr_("labels")[i];
1973 extremes[seriesName] = seriesExtremes;
1974 datasets[i] = series;
1975 }
1976
1977 return [ datasets, extremes, boundaryIds ];
1978 };
1979
1980 /**
1981 * Update the graph with new data. This method is called when the viewing area
1982 * has changed. If the underlying data or options have changed, predraw_ will
1983 * be called before drawGraph_ is called.
1984 *
1985 * clearSelection, when undefined or true, causes this.clearSelection to be
1986 * called at the end of the draw operation. This should rarely be defined,
1987 * and never true (that is it should be undefined most of the time, and
1988 * rarely false.)
1989 *
1990 * @private
1991 */
1992 Dygraph.prototype.drawGraph_ = function(clearSelection) {
1993 var start = new Date();
1994
1995 if (typeof(clearSelection) === 'undefined') {
1996 clearSelection = true;
1997 }
1998
1999 // This is used to set the second parameter to drawCallback, below.
2000 var is_initial_draw = this.is_initial_draw_;
2001 this.is_initial_draw_ = false;
2002
2003 var minY = null, maxY = null;
2004 this.layout_.removeAllDatasets();
2005 this.setColors_();
2006 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
2007
2008 var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_);
2009 var datasets = packed[0];
2010 var extremes = packed[1];
2011 this.boundaryIds_ = packed[2];
2012
2013 for (var i = 1; i < datasets.length; i++) {
2014 if (!this.visibility()[i - 1]) continue;
2015 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
2016 }
2017
2018 this.computeYAxisRanges_(extremes);
2019 this.layout_.setYAxes(this.axes_);
2020
2021 this.addXTicks_();
2022
2023 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2024 var tmp_zoomed_x = this.zoomed_x_;
2025 // Tell PlotKit to use this new data and render itself
2026 this.layout_.setDateWindow(this.dateWindow_);
2027 this.zoomed_x_ = tmp_zoomed_x;
2028 this.layout_.evaluateWithError();
2029 this.renderGraph_(is_initial_draw, false);
2030
2031 if (this.attr_("timingName")) {
2032 var end = new Date();
2033 if (console) {
2034 console.log(this.attr_("timingName") + " - drawGraph: " + (end - start) + "ms")
2035 }
2036 }
2037 };
2038
2039 Dygraph.prototype.renderGraph_ = function(is_initial_draw, clearSelection) {
2040 this.plotter_.clear();
2041 this.plotter_.render();
2042 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2043 this.canvas_.height);
2044
2045 if (is_initial_draw) {
2046 // Generate a static legend before any particular point is selected.
2047 this.setLegendHTML_();
2048 } else {
2049 if (clearSelection) {
2050 if (typeof(this.selPoints_) !== 'undefined' && this.selPoints_.length) {
2051 // We should select the point nearest the page x/y here, but it's easier
2052 // to just clear the selection. This prevents erroneous hover dots from
2053 // being displayed.
2054 this.clearSelection();
2055 } else {
2056 this.clearSelection();
2057 }
2058 }
2059 }
2060
2061 if (this.rangeSelector_) {
2062 this.rangeSelector_.renderInteractiveLayer();
2063 }
2064
2065 if (this.attr_("drawCallback") !== null) {
2066 this.attr_("drawCallback")(this, is_initial_draw);
2067 }
2068 };
2069
2070 /**
2071 * @private
2072 * Determine properties of the y-axes which are independent of the data
2073 * currently being displayed. This includes things like the number of axes and
2074 * the style of the axes. It does not include the range of each axis and its
2075 * tick marks.
2076 * This fills in this.axes_ and this.seriesToAxisMap_.
2077 * axes_ = [ { options } ]
2078 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2079 * indices are into the axes_ array.
2080 */
2081 Dygraph.prototype.computeYAxes_ = function() {
2082 // Preserve valueWindow settings if they exist, and if the user hasn't
2083 // specified a new valueRange.
2084 var valueWindows;
2085 if (this.axes_ != undefined && this.user_attrs_.hasOwnProperty("valueRange") == false) {
2086 valueWindows = [];
2087 for (var index = 0; index < this.axes_.length; index++) {
2088 valueWindows.push(this.axes_[index].valueWindow);
2089 }
2090 }
2091
2092 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
2093 this.seriesToAxisMap_ = {};
2094
2095 // Get a list of series names.
2096 var labels = this.attr_("labels");
2097 var series = {};
2098 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
2099
2100 // all options which could be applied per-axis:
2101 var axisOptions = [
2102 'includeZero',
2103 'valueRange',
2104 'labelsKMB',
2105 'labelsKMG2',
2106 'pixelsPerYLabel',
2107 'yAxisLabelWidth',
2108 'axisLabelFontSize',
2109 'axisTickSize',
2110 'logscale'
2111 ];
2112
2113 // Copy global axis options over to the first axis.
2114 for (var i = 0; i < axisOptions.length; i++) {
2115 var k = axisOptions[i];
2116 var v = this.attr_(k);
2117 if (v) this.axes_[0][k] = v;
2118 }
2119
2120 // Go through once and add all the axes.
2121 for (var seriesName in series) {
2122 if (!series.hasOwnProperty(seriesName)) continue;
2123 var axis = this.attr_("axis", seriesName);
2124 if (axis == null) {
2125 this.seriesToAxisMap_[seriesName] = 0;
2126 continue;
2127 }
2128 if (typeof(axis) == 'object') {
2129 // Add a new axis, making a copy of its per-axis options.
2130 var opts = {};
2131 Dygraph.update(opts, this.axes_[0]);
2132 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
2133 var yAxisId = this.axes_.length;
2134 opts.yAxisId = yAxisId;
2135 opts.g = this;
2136 Dygraph.update(opts, axis);
2137 this.axes_.push(opts);
2138 this.seriesToAxisMap_[seriesName] = yAxisId;
2139 }
2140 }
2141
2142 // Go through one more time and assign series to an axis defined by another
2143 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2144 for (var seriesName in series) {
2145 if (!series.hasOwnProperty(seriesName)) continue;
2146 var axis = this.attr_("axis", seriesName);
2147 if (typeof(axis) == 'string') {
2148 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
2149 this.error("Series " + seriesName + " wants to share a y-axis with " +
2150 "series " + axis + ", which does not define its own axis.");
2151 return null;
2152 }
2153 var idx = this.seriesToAxisMap_[axis];
2154 this.seriesToAxisMap_[seriesName] = idx;
2155 }
2156 }
2157
2158 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2159 // this last so that hiding the first series doesn't destroy the axis
2160 // properties of the primary axis.
2161 var seriesToAxisFiltered = {};
2162 var vis = this.visibility();
2163 for (var i = 1; i < labels.length; i++) {
2164 var s = labels[i];
2165 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2166 }
2167 this.seriesToAxisMap_ = seriesToAxisFiltered;
2168
2169 if (valueWindows != undefined) {
2170 // Restore valueWindow settings.
2171 for (var index = 0; index < valueWindows.length; index++) {
2172 this.axes_[index].valueWindow = valueWindows[index];
2173 }
2174 }
2175 };
2176
2177 /**
2178 * Returns the number of y-axes on the chart.
2179 * @return {Number} the number of axes.
2180 */
2181 Dygraph.prototype.numAxes = function() {
2182 var last_axis = 0;
2183 for (var series in this.seriesToAxisMap_) {
2184 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2185 var idx = this.seriesToAxisMap_[series];
2186 if (idx > last_axis) last_axis = idx;
2187 }
2188 return 1 + last_axis;
2189 };
2190
2191 /**
2192 * @private
2193 * Returns axis properties for the given series.
2194 * @param { String } setName The name of the series for which to get axis
2195 * properties, e.g. 'Y1'.
2196 * @return { Object } The axis properties.
2197 */
2198 Dygraph.prototype.axisPropertiesForSeries = function(series) {
2199 // TODO(danvk): handle errors.
2200 return this.axes_[this.seriesToAxisMap_[series]];
2201 };
2202
2203 /**
2204 * @private
2205 * Determine the value range and tick marks for each axis.
2206 * @param {Object} extremes A mapping from seriesName -> [low, high]
2207 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2208 */
2209 Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2210 // Build a map from axis number -> [list of series names]
2211 var seriesForAxis = [];
2212 for (var series in this.seriesToAxisMap_) {
2213 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2214 var idx = this.seriesToAxisMap_[series];
2215 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2216 seriesForAxis[idx].push(series);
2217 }
2218
2219 // Compute extreme values, a span and tick marks for each axis.
2220 for (var i = 0; i < this.axes_.length; i++) {
2221 var axis = this.axes_[i];
2222
2223 if (!seriesForAxis[i]) {
2224 // If no series are defined or visible then use a reasonable default
2225 axis.extremeRange = [0, 1];
2226 } else {
2227 // Calculate the extremes of extremes.
2228 var series = seriesForAxis[i];
2229 var minY = Infinity; // extremes[series[0]][0];
2230 var maxY = -Infinity; // extremes[series[0]][1];
2231 var extremeMinY, extremeMaxY;
2232 for (var j = 0; j < series.length; j++) {
2233 // Only use valid extremes to stop null data series' from corrupting the scale.
2234 extremeMinY = extremes[series[j]][0];
2235 if (extremeMinY != null) {
2236 minY = Math.min(extremeMinY, minY);
2237 }
2238 extremeMaxY = extremes[series[j]][1];
2239 if (extremeMaxY != null) {
2240 maxY = Math.max(extremeMaxY, maxY);
2241 }
2242 }
2243 if (axis.includeZero && minY > 0) minY = 0;
2244
2245 // Ensure we have a valid scale, otherwise defualt to zero for safety.
2246 if (minY == Infinity) minY = 0;
2247 if (maxY == -Infinity) maxY = 0;
2248
2249 // Add some padding and round up to an integer to be human-friendly.
2250 var span = maxY - minY;
2251 // special case: if we have no sense of scale, use +/-10% of the sole value.
2252 if (span == 0) { span = maxY; }
2253
2254 var maxAxisY;
2255 var minAxisY;
2256 if (axis.logscale) {
2257 var maxAxisY = maxY + 0.1 * span;
2258 var minAxisY = minY;
2259 } else {
2260 var maxAxisY = maxY + 0.1 * span;
2261 var minAxisY = minY - 0.1 * span;
2262
2263 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2264 if (!this.attr_("avoidMinZero")) {
2265 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2266 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2267 }
2268
2269 if (this.attr_("includeZero")) {
2270 if (maxY < 0) maxAxisY = 0;
2271 if (minY > 0) minAxisY = 0;
2272 }
2273 }
2274 axis.extremeRange = [minAxisY, maxAxisY];
2275 }
2276 if (axis.valueWindow) {
2277 // This is only set if the user has zoomed on the y-axis. It is never set
2278 // by a user. It takes precedence over axis.valueRange because, if you set
2279 // valueRange, you'd still expect to be able to pan.
2280 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2281 } else if (axis.valueRange) {
2282 // This is a user-set value range for this axis.
2283 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
2284 } else {
2285 axis.computedValueRange = axis.extremeRange;
2286 }
2287
2288 // Add ticks. By default, all axes inherit the tick positions of the
2289 // primary axis. However, if an axis is specifically marked as having
2290 // independent ticks, then that is permissible as well.
2291 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2292 var ticker = opts('ticker');
2293 if (i == 0 || axis.independentTicks) {
2294 axis.ticks = ticker(axis.computedValueRange[0],
2295 axis.computedValueRange[1],
2296 this.height_, // TODO(danvk): should be area.height
2297 opts,
2298 this);
2299 } else {
2300 var p_axis = this.axes_[0];
2301 var p_ticks = p_axis.ticks;
2302 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2303 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2304 var tick_values = [];
2305 for (var k = 0; k < p_ticks.length; k++) {
2306 var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
2307 var y_val = axis.computedValueRange[0] + y_frac * scale;
2308 tick_values.push(y_val);
2309 }
2310
2311 axis.ticks = ticker(axis.computedValueRange[0],
2312 axis.computedValueRange[1],
2313 this.height_, // TODO(danvk): should be area.height
2314 opts,
2315 this,
2316 tick_values);
2317 }
2318 }
2319 };
2320
2321 /**
2322 * Extracts one series from the raw data (a 2D array) into an array of (date,
2323 * value) tuples.
2324 *
2325 * This is where undesirable points (i.e. negative values on log scales and
2326 * missing values through which we wish to connect lines) are dropped.
2327 *
2328 * @private
2329 */
2330 Dygraph.prototype.extractSeries_ = function(rawData, i, logScale, connectSeparatedPoints) {
2331 var series = [];
2332 for (var j = 0; j < rawData.length; j++) {
2333 var x = rawData[j][0];
2334 var point = rawData[j][i];
2335 if (logScale) {
2336 // On the log scale, points less than zero do not exist.
2337 // This will create a gap in the chart. Note that this ignores
2338 // connectSeparatedPoints.
2339 if (point <= 0) {
2340 point = null;
2341 }
2342 series.push([x, point]);
2343 } else {
2344 if (point != null || !connectSeparatedPoints) {
2345 series.push([x, point]);
2346 }
2347 }
2348 }
2349 return series;
2350 };
2351
2352 /**
2353 * @private
2354 * Calculates the rolling average of a data set.
2355 * If originalData is [label, val], rolls the average of those.
2356 * If originalData is [label, [, it's interpreted as [value, stddev]
2357 * and the roll is returned in the same form, with appropriately reduced
2358 * stddev for each value.
2359 * Note that this is where fractional input (i.e. '5/10') is converted into
2360 * decimal values.
2361 * @param {Array} originalData The data in the appropriate format (see above)
2362 * @param {Number} rollPeriod The number of points over which to average the
2363 * data
2364 */
2365 Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
2366 if (originalData.length < 2)
2367 return originalData;
2368 var rollPeriod = Math.min(rollPeriod, originalData.length);
2369 var rollingData = [];
2370 var sigma = this.attr_("sigma");
2371
2372 if (this.fractions_) {
2373 var num = 0;
2374 var den = 0; // numerator/denominator
2375 var mult = 100.0;
2376 for (var i = 0; i < originalData.length; i++) {
2377 num += originalData[i][1][0];
2378 den += originalData[i][1][1];
2379 if (i - rollPeriod >= 0) {
2380 num -= originalData[i - rollPeriod][1][0];
2381 den -= originalData[i - rollPeriod][1][1];
2382 }
2383
2384 var date = originalData[i][0];
2385 var value = den ? num / den : 0.0;
2386 if (this.attr_("errorBars")) {
2387 if (this.wilsonInterval_) {
2388 // For more details on this confidence interval, see:
2389 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
2390 if (den) {
2391 var p = value < 0 ? 0 : value, n = den;
2392 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
2393 var denom = 1 + sigma * sigma / den;
2394 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
2395 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
2396 rollingData[i] = [date,
2397 [p * mult, (p - low) * mult, (high - p) * mult]];
2398 } else {
2399 rollingData[i] = [date, [0, 0, 0]];
2400 }
2401 } else {
2402 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
2403 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
2404 }
2405 } else {
2406 rollingData[i] = [date, mult * value];
2407 }
2408 }
2409 } else if (this.attr_("customBars")) {
2410 var low = 0;
2411 var mid = 0;
2412 var high = 0;
2413 var count = 0;
2414 for (var i = 0; i < originalData.length; i++) {
2415 var data = originalData[i][1];
2416 var y = data[1];
2417 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
2418
2419 if (y != null && !isNaN(y)) {
2420 low += data[0];
2421 mid += y;
2422 high += data[2];
2423 count += 1;
2424 }
2425 if (i - rollPeriod >= 0) {
2426 var prev = originalData[i - rollPeriod];
2427 if (prev[1][1] != null && !isNaN(prev[1][1])) {
2428 low -= prev[1][0];
2429 mid -= prev[1][1];
2430 high -= prev[1][2];
2431 count -= 1;
2432 }
2433 }
2434 if (count) {
2435 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
2436 1.0 * (mid - low) / count,
2437 1.0 * (high - mid) / count ]];
2438 } else {
2439 rollingData[i] = [originalData[i][0], [null, null, null]];
2440 }
2441 }
2442 } else {
2443 // Calculate the rolling average for the first rollPeriod - 1 points where
2444 // there is not enough data to roll over the full number of points
2445 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
2446 if (!this.attr_("errorBars")){
2447 if (rollPeriod == 1) {
2448 return originalData;
2449 }
2450
2451 for (var i = 0; i < originalData.length; i++) {
2452 var sum = 0;
2453 var num_ok = 0;
2454 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2455 var y = originalData[j][1];
2456 if (y == null || isNaN(y)) continue;
2457 num_ok++;
2458 sum += originalData[j][1];
2459 }
2460 if (num_ok) {
2461 rollingData[i] = [originalData[i][0], sum / num_ok];
2462 } else {
2463 rollingData[i] = [originalData[i][0], null];
2464 }
2465 }
2466
2467 } else {
2468 for (var i = 0; i < originalData.length; i++) {
2469 var sum = 0;
2470 var variance = 0;
2471 var num_ok = 0;
2472 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2473 var y = originalData[j][1][0];
2474 if (y == null || isNaN(y)) continue;
2475 num_ok++;
2476 sum += originalData[j][1][0];
2477 variance += Math.pow(originalData[j][1][1], 2);
2478 }
2479 if (num_ok) {
2480 var stddev = Math.sqrt(variance) / num_ok;
2481 rollingData[i] = [originalData[i][0],
2482 [sum / num_ok, sigma * stddev, sigma * stddev]];
2483 } else {
2484 rollingData[i] = [originalData[i][0], [null, null, null]];
2485 }
2486 }
2487 }
2488 }
2489
2490 return rollingData;
2491 };
2492
2493 /**
2494 * Detects the type of the str (date or numeric) and sets the various
2495 * formatting attributes in this.attrs_ based on this type.
2496 * @param {String} str An x value.
2497 * @private
2498 */
2499 Dygraph.prototype.detectTypeFromString_ = function(str) {
2500 var isDate = false;
2501 var dashPos = str.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2502 if ((dashPos > 0 && (str[dashPos-1] != 'e' && str[dashPos-1] != 'E')) ||
2503 str.indexOf('/') >= 0 ||
2504 isNaN(parseFloat(str))) {
2505 isDate = true;
2506 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2507 // TODO(danvk): remove support for this format.
2508 isDate = true;
2509 }
2510
2511 if (isDate) {
2512 this.attrs_.xValueParser = Dygraph.dateParser;
2513 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2514 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2515 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
2516 } else {
2517 /** @private (shut up, jsdoc!) */
2518 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2519 // TODO(danvk): use Dygraph.numberValueFormatter here?
2520 /** @private (shut up, jsdoc!) */
2521 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
2522 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
2523 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
2524 }
2525 };
2526
2527 /**
2528 * Parses the value as a floating point number. This is like the parseFloat()
2529 * built-in, but with a few differences:
2530 * - the empty string is parsed as null, rather than NaN.
2531 * - if the string cannot be parsed at all, an error is logged.
2532 * If the string can't be parsed, this method returns null.
2533 * @param {String} x The string to be parsed
2534 * @param {Number} opt_line_no The line number from which the string comes.
2535 * @param {String} opt_line The text of the line from which the string comes.
2536 * @private
2537 */
2538
2539 // Parse the x as a float or return null if it's not a number.
2540 Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
2541 var val = parseFloat(x);
2542 if (!isNaN(val)) return val;
2543
2544 // Try to figure out what happeend.
2545 // If the value is the empty string, parse it as null.
2546 if (/^ *$/.test(x)) return null;
2547
2548 // If it was actually "NaN", return it as NaN.
2549 if (/^ *nan *$/i.test(x)) return NaN;
2550
2551 // Looks like a parsing error.
2552 var msg = "Unable to parse '" + x + "' as a number";
2553 if (opt_line !== null && opt_line_no !== null) {
2554 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
2555 }
2556 this.error(msg);
2557
2558 return null;
2559 };
2560
2561 /**
2562 * @private
2563 * Parses a string in a special csv format. We expect a csv file where each
2564 * line is a date point, and the first field in each line is the date string.
2565 * We also expect that all remaining fields represent series.
2566 * if the errorBars attribute is set, then interpret the fields as:
2567 * date, series1, stddev1, series2, stddev2, ...
2568 * @param {[Object]} data See above.
2569 *
2570 * @return [Object] An array with one entry for each row. These entries
2571 * are an array of cells in that row. The first entry is the parsed x-value for
2572 * the row. The second, third, etc. are the y-values. These can take on one of
2573 * three forms, depending on the CSV and constructor parameters:
2574 * 1. numeric value
2575 * 2. [ value, stddev ]
2576 * 3. [ low value, center value, high value ]
2577 */
2578 Dygraph.prototype.parseCSV_ = function(data) {
2579 var ret = [];
2580 var lines = data.split("\n");
2581
2582 // Use the default delimiter or fall back to a tab if that makes sense.
2583 var delim = this.attr_('delimiter');
2584 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
2585 delim = '\t';
2586 }
2587
2588 var start = 0;
2589 if (!('labels' in this.user_attrs_)) {
2590 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
2591 start = 1;
2592 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
2593 }
2594 var line_no = 0;
2595
2596 var xParser;
2597 var defaultParserSet = false; // attempt to auto-detect x value type
2598 var expectedCols = this.attr_("labels").length;
2599 var outOfOrder = false;
2600 for (var i = start; i < lines.length; i++) {
2601 var line = lines[i];
2602 line_no = i;
2603 if (line.length == 0) continue; // skip blank lines
2604 if (line[0] == '#') continue; // skip comment lines
2605 var inFields = line.split(delim);
2606 if (inFields.length < 2) continue;
2607
2608 var fields = [];
2609 if (!defaultParserSet) {
2610 this.detectTypeFromString_(inFields[0]);
2611 xParser = this.attr_("xValueParser");
2612 defaultParserSet = true;
2613 }
2614 fields[0] = xParser(inFields[0], this);
2615
2616 // If fractions are expected, parse the numbers as "A/B"
2617 if (this.fractions_) {
2618 for (var j = 1; j < inFields.length; j++) {
2619 // TODO(danvk): figure out an appropriate way to flag parse errors.
2620 var vals = inFields[j].split("/");
2621 if (vals.length != 2) {
2622 this.error('Expected fractional "num/den" values in CSV data ' +
2623 "but found a value '" + inFields[j] + "' on line " +
2624 (1 + i) + " ('" + line + "') which is not of this form.");
2625 fields[j] = [0, 0];
2626 } else {
2627 fields[j] = [this.parseFloat_(vals[0], i, line),
2628 this.parseFloat_(vals[1], i, line)];
2629 }
2630 }
2631 } else if (this.attr_("errorBars")) {
2632 // If there are error bars, values are (value, stddev) pairs
2633 if (inFields.length % 2 != 1) {
2634 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2635 'but line ' + (1 + i) + ' has an odd number of values (' +
2636 (inFields.length - 1) + "): '" + line + "'");
2637 }
2638 for (var j = 1; j < inFields.length; j += 2) {
2639 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2640 this.parseFloat_(inFields[j + 1], i, line)];
2641 }
2642 } else if (this.attr_("customBars")) {
2643 // Bars are a low;center;high tuple
2644 for (var j = 1; j < inFields.length; j++) {
2645 var val = inFields[j];
2646 if (/^ *$/.test(val)) {
2647 fields[j] = [null, null, null];
2648 } else {
2649 var vals = val.split(";");
2650 if (vals.length == 3) {
2651 fields[j] = [ this.parseFloat_(vals[0], i, line),
2652 this.parseFloat_(vals[1], i, line),
2653 this.parseFloat_(vals[2], i, line) ];
2654 } else {
2655 this.warning('When using customBars, values must be either blank ' +
2656 'or "low;center;high" tuples (got "' + val +
2657 '" on line ' + (1+i));
2658 }
2659 }
2660 }
2661 } else {
2662 // Values are just numbers
2663 for (var j = 1; j < inFields.length; j++) {
2664 fields[j] = this.parseFloat_(inFields[j], i, line);
2665 }
2666 }
2667 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2668 outOfOrder = true;
2669 }
2670
2671 if (fields.length != expectedCols) {
2672 this.error("Number of columns in line " + i + " (" + fields.length +
2673 ") does not agree with number of labels (" + expectedCols +
2674 ") " + line);
2675 }
2676
2677 // If the user specified the 'labels' option and none of the cells of the
2678 // first row parsed correctly, then they probably double-specified the
2679 // labels. We go with the values set in the option, discard this row and
2680 // log a warning to the JS console.
2681 if (i == 0 && this.attr_('labels')) {
2682 var all_null = true;
2683 for (var j = 0; all_null && j < fields.length; j++) {
2684 if (fields[j]) all_null = false;
2685 }
2686 if (all_null) {
2687 this.warn("The dygraphs 'labels' option is set, but the first row of " +
2688 "CSV data ('" + line + "') appears to also contain labels. " +
2689 "Will drop the CSV labels and use the option labels.");
2690 continue;
2691 }
2692 }
2693 ret.push(fields);
2694 }
2695
2696 if (outOfOrder) {
2697 this.warn("CSV is out of order; order it correctly to speed loading.");
2698 ret.sort(function(a,b) { return a[0] - b[0] });
2699 }
2700
2701 return ret;
2702 };
2703
2704 /**
2705 * @private
2706 * The user has provided their data as a pre-packaged JS array. If the x values
2707 * are numeric, this is the same as dygraphs' internal format. If the x values
2708 * are dates, we need to convert them from Date objects to ms since epoch.
2709 * @param {[Object]} data
2710 * @return {[Object]} data with numeric x values.
2711 */
2712 Dygraph.prototype.parseArray_ = function(data) {
2713 // Peek at the first x value to see if it's numeric.
2714 if (data.length == 0) {
2715 this.error("Can't plot empty data set");
2716 return null;
2717 }
2718 if (data[0].length == 0) {
2719 this.error("Data set cannot contain an empty row");
2720 return null;
2721 }
2722
2723 if (this.attr_("labels") == null) {
2724 this.warn("Using default labels. Set labels explicitly via 'labels' " +
2725 "in the options parameter");
2726 this.attrs_.labels = [ "X" ];
2727 for (var i = 1; i < data[0].length; i++) {
2728 this.attrs_.labels.push("Y" + i);
2729 }
2730 }
2731
2732 if (Dygraph.isDateLike(data[0][0])) {
2733 // Some intelligent defaults for a date x-axis.
2734 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2735 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
2736 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2737
2738 // Assume they're all dates.
2739 var parsedData = Dygraph.clone(data);
2740 for (var i = 0; i < data.length; i++) {
2741 if (parsedData[i].length == 0) {
2742 this.error("Row " + (1 + i) + " of data is empty");
2743 return null;
2744 }
2745 if (parsedData[i][0] == null
2746 || typeof(parsedData[i][0].getTime) != 'function'
2747 || isNaN(parsedData[i][0].getTime())) {
2748 this.error("x value in row " + (1 + i) + " is not a Date");
2749 return null;
2750 }
2751 parsedData[i][0] = parsedData[i][0].getTime();
2752 }
2753 return parsedData;
2754 } else {
2755 // Some intelligent defaults for a numeric x-axis.
2756 /** @private (shut up, jsdoc!) */
2757 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
2758 this.attrs_.axes.x.axisLabelFormatter = Dygraph.numberAxisLabelFormatter;
2759 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
2760 return data;
2761 }
2762 };
2763
2764 /**
2765 * Parses a DataTable object from gviz.
2766 * The data is expected to have a first column that is either a date or a
2767 * number. All subsequent columns must be numbers. If there is a clear mismatch
2768 * between this.xValueParser_ and the type of the first column, it will be
2769 * fixed. Fills out rawData_.
2770 * @param {[Object]} data See above.
2771 * @private
2772 */
2773 Dygraph.prototype.parseDataTable_ = function(data) {
2774 var cols = data.getNumberOfColumns();
2775 var rows = data.getNumberOfRows();
2776
2777 var indepType = data.getColumnType(0);
2778 if (indepType == 'date' || indepType == 'datetime') {
2779 this.attrs_.xValueParser = Dygraph.dateParser;
2780 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2781 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2782 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
2783 } else if (indepType == 'number') {
2784 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2785 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
2786 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
2787 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
2788 } else {
2789 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2790 "column 1 of DataTable input (Got '" + indepType + "')");
2791 return null;
2792 }
2793
2794 // Array of the column indices which contain data (and not annotations).
2795 var colIdx = [];
2796 var annotationCols = {}; // data index -> [annotation cols]
2797 var hasAnnotations = false;
2798 for (var i = 1; i < cols; i++) {
2799 var type = data.getColumnType(i);
2800 if (type == 'number') {
2801 colIdx.push(i);
2802 } else if (type == 'string' && this.attr_('displayAnnotations')) {
2803 // This is OK -- it's an annotation column.
2804 var dataIdx = colIdx[colIdx.length - 1];
2805 if (!annotationCols.hasOwnProperty(dataIdx)) {
2806 annotationCols[dataIdx] = [i];
2807 } else {
2808 annotationCols[dataIdx].push(i);
2809 }
2810 hasAnnotations = true;
2811 } else {
2812 this.error("Only 'number' is supported as a dependent type with Gviz." +
2813 " 'string' is only supported if displayAnnotations is true");
2814 }
2815 }
2816
2817 // Read column labels
2818 // TODO(danvk): add support back for errorBars
2819 var labels = [data.getColumnLabel(0)];
2820 for (var i = 0; i < colIdx.length; i++) {
2821 labels.push(data.getColumnLabel(colIdx[i]));
2822 if (this.attr_("errorBars")) i += 1;
2823 }
2824 this.attrs_.labels = labels;
2825 cols = labels.length;
2826
2827 var ret = [];
2828 var outOfOrder = false;
2829 var annotations = [];
2830 for (var i = 0; i < rows; i++) {
2831 var row = [];
2832 if (typeof(data.getValue(i, 0)) === 'undefined' ||
2833 data.getValue(i, 0) === null) {
2834 this.warn("Ignoring row " + i +
2835 " of DataTable because of undefined or null first column.");
2836 continue;
2837 }
2838
2839 if (indepType == 'date' || indepType == 'datetime') {
2840 row.push(data.getValue(i, 0).getTime());
2841 } else {
2842 row.push(data.getValue(i, 0));
2843 }
2844 if (!this.attr_("errorBars")) {
2845 for (var j = 0; j < colIdx.length; j++) {
2846 var col = colIdx[j];
2847 row.push(data.getValue(i, col));
2848 if (hasAnnotations &&
2849 annotationCols.hasOwnProperty(col) &&
2850 data.getValue(i, annotationCols[col][0]) != null) {
2851 var ann = {};
2852 ann.series = data.getColumnLabel(col);
2853 ann.xval = row[0];
2854 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
2855 ann.text = '';
2856 for (var k = 0; k < annotationCols[col].length; k++) {
2857 if (k) ann.text += "\n";
2858 ann.text += data.getValue(i, annotationCols[col][k]);
2859 }
2860 annotations.push(ann);
2861 }
2862 }
2863
2864 // Strip out infinities, which give dygraphs problems later on.
2865 for (var j = 0; j < row.length; j++) {
2866 if (!isFinite(row[j])) row[j] = null;
2867 }
2868 } else {
2869 for (var j = 0; j < cols - 1; j++) {
2870 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
2871 }
2872 }
2873 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
2874 outOfOrder = true;
2875 }
2876 ret.push(row);
2877 }
2878
2879 if (outOfOrder) {
2880 this.warn("DataTable is out of order; order it correctly to speed loading.");
2881 ret.sort(function(a,b) { return a[0] - b[0] });
2882 }
2883 this.rawData_ = ret;
2884
2885 if (annotations.length > 0) {
2886 this.setAnnotations(annotations, true);
2887 }
2888 }
2889
2890 /**
2891 * Get the CSV data. If it's in a function, call that function. If it's in a
2892 * file, do an XMLHttpRequest to get it.
2893 * @private
2894 */
2895 Dygraph.prototype.start_ = function() {
2896 if (typeof this.file_ == 'function') {
2897 // CSV string. Pretend we got it via XHR.
2898 this.loadedEvent_(this.file_());
2899 } else if (Dygraph.isArrayLike(this.file_)) {
2900 this.rawData_ = this.parseArray_(this.file_);
2901 this.predraw_();
2902 } else if (typeof this.file_ == 'object' &&
2903 typeof this.file_.getColumnRange == 'function') {
2904 // must be a DataTable from gviz.
2905 this.parseDataTable_(this.file_);
2906 this.predraw_();
2907 } else if (typeof this.file_ == 'string') {
2908 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2909 if (this.file_.indexOf('\n') >= 0) {
2910 this.loadedEvent_(this.file_);
2911 } else {
2912 var req = new XMLHttpRequest();
2913 var caller = this;
2914 req.onreadystatechange = function () {
2915 if (req.readyState == 4) {
2916 if (req.status == 200 || // Normal http
2917 req.status == 0) { // Chrome w/ --allow-file-access-from-files
2918 caller.loadedEvent_(req.responseText);
2919 }
2920 }
2921 };
2922
2923 req.open("GET", this.file_, true);
2924 req.send(null);
2925 }
2926 } else {
2927 this.error("Unknown data format: " + (typeof this.file_));
2928 }
2929 };
2930
2931 /**
2932 * Changes various properties of the graph. These can include:
2933 * <ul>
2934 * <li>file: changes the source data for the graph</li>
2935 * <li>errorBars: changes whether the data contains stddev</li>
2936 * </ul>
2937 *
2938 * There's a huge variety of options that can be passed to this method. For a
2939 * full list, see http://dygraphs.com/options.html.
2940 *
2941 * @param {Object} attrs The new properties and values
2942 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
2943 * call to updateOptions(). If you know better, you can pass true to explicitly
2944 * block the redraw. This can be useful for chaining updateOptions() calls,
2945 * avoiding the occasional infinite loop and preventing redraws when it's not
2946 * necessary (e.g. when updating a callback).
2947 */
2948 Dygraph.prototype.updateOptions = function(input_attrs, block_redraw) {
2949 if (typeof(block_redraw) == 'undefined') block_redraw = false;
2950
2951 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
2952 var file = input_attrs['file'];
2953 var attrs = Dygraph.mapLegacyOptions_(input_attrs);
2954
2955 // TODO(danvk): this is a mess. Move these options into attr_.
2956 if ('rollPeriod' in attrs) {
2957 this.rollPeriod_ = attrs.rollPeriod;
2958 }
2959 if ('dateWindow' in attrs) {
2960 this.dateWindow_ = attrs.dateWindow;
2961 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
2962 this.zoomed_x_ = attrs.dateWindow != null;
2963 }
2964 }
2965 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
2966 this.zoomed_y_ = attrs.valueRange != null;
2967 }
2968
2969 // TODO(danvk): validate per-series options.
2970 // Supported:
2971 // strokeWidth
2972 // pointSize
2973 // drawPoints
2974 // highlightCircleSize
2975
2976 // Check if this set options will require new points.
2977 var requiresNewPoints = Dygraph.isPixelChangingOptionList(this.attr_("labels"), attrs);
2978
2979 Dygraph.updateDeep(this.user_attrs_, attrs);
2980
2981 if (file) {
2982 this.file_ = file;
2983 if (!block_redraw) this.start_();
2984 } else {
2985 if (!block_redraw) {
2986 if (requiresNewPoints) {
2987 this.predraw_();
2988 } else {
2989 this.renderGraph_(false, false);
2990 }
2991 }
2992 }
2993 };
2994
2995 /**
2996 * Returns a copy of the options with deprecated names converted into current
2997 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
2998 * interested in that, they should save a copy before calling this.
2999 * @private
3000 */
3001 Dygraph.mapLegacyOptions_ = function(attrs) {
3002 var my_attrs = {};
3003 for (var k in attrs) {
3004 if (k == 'file') continue;
3005 if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k];
3006 }
3007
3008 var set = function(axis, opt, value) {
3009 if (!my_attrs.axes) my_attrs.axes = {};
3010 if (!my_attrs.axes[axis]) my_attrs.axes[axis] = {};
3011 my_attrs.axes[axis][opt] = value;
3012 };
3013 var map = function(opt, axis, new_opt) {
3014 if (typeof(attrs[opt]) != 'undefined') {
3015 set(axis, new_opt, attrs[opt]);
3016 delete my_attrs[opt];
3017 }
3018 };
3019
3020 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3021 map('xValueFormatter', 'x', 'valueFormatter');
3022 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3023 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3024 map('xTicker', 'x', 'ticker');
3025 map('yValueFormatter', 'y', 'valueFormatter');
3026 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3027 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3028 map('yTicker', 'y', 'ticker');
3029 return my_attrs;
3030 };
3031
3032 /**
3033 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3034 * containing div (which has presumably changed size since the dygraph was
3035 * instantiated. If the width/height are specified, the div will be resized.
3036 *
3037 * This is far more efficient than destroying and re-instantiating a
3038 * Dygraph, since it doesn't have to reparse the underlying data.
3039 *
3040 * @param {Number} [width] Width (in pixels)
3041 * @param {Number} [height] Height (in pixels)
3042 */
3043 Dygraph.prototype.resize = function(width, height) {
3044 if (this.resize_lock) {
3045 return;
3046 }
3047 this.resize_lock = true;
3048
3049 if ((width === null) != (height === null)) {
3050 this.warn("Dygraph.resize() should be called with zero parameters or " +
3051 "two non-NULL parameters. Pretending it was zero.");
3052 width = height = null;
3053 }
3054
3055 var old_width = this.width_;
3056 var old_height = this.height_;
3057
3058 if (width) {
3059 this.maindiv_.style.width = width + "px";
3060 this.maindiv_.style.height = height + "px";
3061 this.width_ = width;
3062 this.height_ = height;
3063 } else {
3064 this.width_ = this.maindiv_.clientWidth;
3065 this.height_ = this.maindiv_.clientHeight;
3066 }
3067
3068 if (old_width != this.width_ || old_height != this.height_) {
3069 // TODO(danvk): there should be a clear() method.
3070 this.maindiv_.innerHTML = "";
3071 this.roller_ = null;
3072 this.attrs_.labelsDiv = null;
3073 this.createInterface_();
3074 if (this.annotations_.length) {
3075 // createInterface_ reset the layout, so we need to do this.
3076 this.layout_.setAnnotations(this.annotations_);
3077 }
3078 this.predraw_();
3079 }
3080
3081 this.resize_lock = false;
3082 };
3083
3084 /**
3085 * Adjusts the number of points in the rolling average. Updates the graph to
3086 * reflect the new averaging period.
3087 * @param {Number} length Number of points over which to average the data.
3088 */
3089 Dygraph.prototype.adjustRoll = function(length) {
3090 this.rollPeriod_ = length;
3091 this.predraw_();
3092 };
3093
3094 /**
3095 * Returns a boolean array of visibility statuses.
3096 */
3097 Dygraph.prototype.visibility = function() {
3098 // Do lazy-initialization, so that this happens after we know the number of
3099 // data series.
3100 if (!this.attr_("visibility")) {
3101 this.attrs_["visibility"] = [];
3102 }
3103 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
3104 this.attr_("visibility").push(true);
3105 }
3106 return this.attr_("visibility");
3107 };
3108
3109 /**
3110 * Changes the visiblity of a series.
3111 */
3112 Dygraph.prototype.setVisibility = function(num, value) {
3113 var x = this.visibility();
3114 if (num < 0 || num >= x.length) {
3115 this.warn("invalid series number in setVisibility: " + num);
3116 } else {
3117 x[num] = value;
3118 this.predraw_();
3119 }
3120 };
3121
3122 /**
3123 * How large of an area will the dygraph render itself in?
3124 * This is used for testing.
3125 * @return A {width: w, height: h} object.
3126 * @private
3127 */
3128 Dygraph.prototype.size = function() {
3129 return { width: this.width_, height: this.height_ };
3130 };
3131
3132 /**
3133 * Update the list of annotations and redraw the chart.
3134 * See dygraphs.com/annotations.html for more info on how to use annotations.
3135 * @param ann {Array} An array of annotation objects.
3136 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3137 */
3138 Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3139 // Only add the annotation CSS rule once we know it will be used.
3140 Dygraph.addAnnotationRule();
3141 this.annotations_ = ann;
3142 this.layout_.setAnnotations(this.annotations_);
3143 if (!suppressDraw) {
3144 this.predraw_();
3145 }
3146 };
3147
3148 /**
3149 * Return the list of annotations.
3150 */
3151 Dygraph.prototype.annotations = function() {
3152 return this.annotations_;
3153 };
3154
3155 /**
3156 * Get the index of a series (column) given its name. The first column is the
3157 * x-axis, so the data series start with index 1.
3158 */
3159 Dygraph.prototype.indexFromSetName = function(name) {
3160 var labels = this.attr_("labels");
3161 for (var i = 0; i < labels.length; i++) {
3162 if (labels[i] == name) return i;
3163 }
3164 return null;
3165 };
3166
3167 /**
3168 * @private
3169 * Adds a default style for the annotation CSS classes to the document. This is
3170 * only executed when annotations are actually used. It is designed to only be
3171 * called once -- all calls after the first will return immediately.
3172 */
3173 Dygraph.addAnnotationRule = function() {
3174 if (Dygraph.addedAnnotationCSS) return;
3175
3176 var rule = "border: 1px solid black; " +
3177 "background-color: white; " +
3178 "text-align: center;";
3179
3180 var styleSheetElement = document.createElement("style");
3181 styleSheetElement.type = "text/css";
3182 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3183
3184 // Find the first style sheet that we can access.
3185 // We may not add a rule to a style sheet from another domain for security
3186 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3187 // adds its own style sheets from google.com.
3188 for (var i = 0; i < document.styleSheets.length; i++) {
3189 if (document.styleSheets[i].disabled) continue;
3190 var mysheet = document.styleSheets[i];
3191 try {
3192 if (mysheet.insertRule) { // Firefox
3193 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3194 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3195 } else if (mysheet.addRule) { // IE
3196 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3197 }
3198 Dygraph.addedAnnotationCSS = true;
3199 return;
3200 } catch(err) {
3201 // Was likely a security exception.
3202 }
3203 }
3204
3205 this.warn("Unable to add default annotation CSS rule; display may be off.");
3206 }
3207
3208 // Older pages may still use this name.
3209 var DateGraph = Dygraph;