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