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