c9ec7658a4cbdc3e1fc2b4db2866779cdb5dd306
[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 Dygraph.LOG_SCALE = 10;
90 Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
91 /** @private */
92 Dygraph.log10 = function(x) {
93 return Math.log(x) / Dygraph.LN_TEN;
94 }
95
96 // Default attribute values.
97 Dygraph.DEFAULT_ATTRS = {
98 highlightCircleSize: 3,
99 pixelsPerXLabel: 60,
100 pixelsPerYLabel: 30,
101
102 labelsDivWidth: 250,
103 labelsDivStyles: {
104 // TODO(danvk): move defaults from createStatusMessage_ here.
105 },
106 labelsSeparateLines: false,
107 labelsShowZeroValues: true,
108 labelsKMB: false,
109 labelsKMG2: false,
110 showLabelsOnHighlight: true,
111
112 yValueFormatter: function(a,b) { return Dygraph.numberFormatter(a,b); },
113 digitsAfterDecimal: 2,
114 maxNumberWidth: 6,
115 sigFigs: null,
116
117 strokeWidth: 1.0,
118
119 axisTickSize: 3,
120 axisLabelFontSize: 14,
121 xAxisLabelWidth: 50,
122 yAxisLabelWidth: 50,
123 xAxisLabelFormatter: Dygraph.dateAxisFormatter,
124 rightGap: 5,
125
126 showRoller: false,
127 xValueFormatter: Dygraph.dateString_,
128 xValueParser: Dygraph.dateParser,
129 xTicker: Dygraph.dateTicker,
130
131 delimiter: ',',
132
133 sigma: 2.0,
134 errorBars: false,
135 fractions: false,
136 wilsonInterval: true, // only relevant if fractions is true
137 customBars: false,
138 fillGraph: false,
139 fillAlpha: 0.15,
140 connectSeparatedPoints: false,
141
142 stackedGraph: false,
143 hideOverlayOnMouseOut: true,
144
145 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
146 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
147
148 stepPlot: false,
149 avoidMinZero: false,
150
151 // Sizes of the various chart labels.
152 titleHeight: 28,
153 xLabelHeight: 18,
154 yLabelWidth: 18,
155
156 drawXAxis: true,
157 drawYAxis: true,
158 axisLineColor: "black",
159 axisLineWidth: 0.3,
160 gridLineWidth: 0.3,
161 axisLabelColor: "black",
162 axisLabelFont: "Arial", // TODO(danvk): is this implemented?
163 axisLabelWidth: 50,
164 drawYGrid: true,
165 drawXGrid: true,
166 gridLineColor: "rgb(128,128,128)",
167
168 interactionModel: null // will be set to Dygraph.defaultInteractionModel.
169 };
170
171 // Various logging levels.
172 Dygraph.DEBUG = 1;
173 Dygraph.INFO = 2;
174 Dygraph.WARNING = 3;
175 Dygraph.ERROR = 3;
176
177 // Directions for panning and zooming. Use bit operations when combined
178 // values are possible.
179 Dygraph.HORIZONTAL = 1;
180 Dygraph.VERTICAL = 2;
181
182 // Used for initializing annotation CSS rules only once.
183 Dygraph.addedAnnotationCSS = false;
184
185 /**
186 * @private
187 * Return the 2d context for a dygraph canvas.
188 *
189 * This method is only exposed for the sake of replacing the function in
190 * automated tests, e.g.
191 *
192 * var oldFunc = Dygraph.getContext();
193 * Dygraph.getContext = function(canvas) {
194 * var realContext = oldFunc(canvas);
195 * return new Proxy(realContext);
196 * };
197 */
198 Dygraph.getContext = function(canvas) {
199 return canvas.getContext("2d");
200 };
201
202 Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
203 // Labels is no longer a constructor parameter, since it's typically set
204 // directly from the data source. It also conains a name for the x-axis,
205 // which the previous constructor form did not.
206 if (labels != null) {
207 var new_labels = ["Date"];
208 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
209 Dygraph.update(attrs, { 'labels': new_labels });
210 }
211 this.__init__(div, file, attrs);
212 };
213
214 /**
215 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
216 * and context &lt;canvas&gt; inside of it. See the constructor for details.
217 * on the parameters.
218 * @param {Element} div the Element to render the graph into.
219 * @param {String | Function} file Source data
220 * @param {Object} attrs Miscellaneous other options
221 * @private
222 */
223 Dygraph.prototype.__init__ = function(div, file, attrs) {
224 // Hack for IE: if we're using excanvas and the document hasn't finished
225 // loading yet (and hence may not have initialized whatever it needs to
226 // initialize), then keep calling this routine periodically until it has.
227 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
228 typeof(G_vmlCanvasManager) != 'undefined' &&
229 document.readyState != 'complete') {
230 var self = this;
231 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
232 }
233
234 // Support two-argument constructor
235 if (attrs == null) { attrs = {}; }
236
237 // Copy the important bits into the object
238 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
239 this.maindiv_ = div;
240 this.file_ = file;
241 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
242 this.previousVerticalX_ = -1;
243 this.fractions_ = attrs.fractions || false;
244 this.dateWindow_ = attrs.dateWindow || null;
245
246 this.wilsonInterval_ = attrs.wilsonInterval || true;
247 this.is_initial_draw_ = true;
248 this.annotations_ = [];
249
250 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
251 this.zoomed_x_ = false;
252 this.zoomed_y_ = false;
253
254 // Clear the div. This ensure that, if multiple dygraphs are passed the same
255 // div, then only one will be drawn.
256 div.innerHTML = "";
257
258 // If the div isn't already sized then inherit from our attrs or
259 // give it a default size.
260 if (div.style.width == '') {
261 div.style.width = (attrs.width || Dygraph.DEFAULT_WIDTH) + "px";
262 }
263 if (div.style.height == '') {
264 div.style.height = (attrs.height || Dygraph.DEFAULT_HEIGHT) + "px";
265 }
266 this.width_ = parseInt(div.style.width, 10);
267 this.height_ = parseInt(div.style.height, 10);
268 // The div might have been specified as percent of the current window size,
269 // convert that to an appropriate number of pixels.
270 if (div.style.width.indexOf("%") == div.style.width.length - 1) {
271 this.width_ = div.offsetWidth;
272 }
273 if (div.style.height.indexOf("%") == div.style.height.length - 1) {
274 this.height_ = div.offsetHeight;
275 }
276
277 if (this.width_ == 0) {
278 this.error("dygraph has zero width. Please specify a width in pixels.");
279 }
280 if (this.height_ == 0) {
281 this.error("dygraph has zero height. Please specify a height in pixels.");
282 }
283
284 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
285 if (attrs['stackedGraph']) {
286 attrs['fillGraph'] = true;
287 // TODO(nikhilk): Add any other stackedGraph checks here.
288 }
289
290 // Dygraphs has many options, some of which interact with one another.
291 // To keep track of everything, we maintain two sets of options:
292 //
293 // this.user_attrs_ only options explicitly set by the user.
294 // this.attrs_ defaults, options derived from user_attrs_, data.
295 //
296 // Options are then accessed this.attr_('attr'), which first looks at
297 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
298 // defaults without overriding behavior that the user specifically asks for.
299 this.user_attrs_ = {};
300 Dygraph.update(this.user_attrs_, attrs);
301
302 this.attrs_ = {};
303 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
304
305 this.boundaryIds_ = [];
306
307 // Create the containing DIV and other interactive elements
308 this.createInterface_();
309
310 this.start_();
311 };
312
313 /**
314 * Returns the zoomed status of the chart for one or both axes.
315 *
316 * Axis is an optional parameter. Can be set to 'x' or 'y'.
317 *
318 * The zoomed status for an axis is set whenever a user zooms using the mouse
319 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
320 * option is also specified).
321 */
322 Dygraph.prototype.isZoomed = function(axis) {
323 if (axis == null) return this.zoomed_x_ || this.zoomed_y_;
324 if (axis == 'x') return this.zoomed_x_;
325 if (axis == 'y') return this.zoomed_y_;
326 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
327 };
328
329 /**
330 * Returns information about the Dygraph object, including its containing ID.
331 */
332 Dygraph.prototype.toString = function() {
333 var maindiv = this.maindiv_;
334 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
335 return "[Dygraph " + id + "]";
336 }
337
338 /**
339 * @private
340 * Returns the value of an option. This may be set by the user (either in the
341 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
342 * per-series value.
343 * @param { String } name The name of the option, e.g. 'rollPeriod'.
344 * @param { String } [seriesName] The name of the series to which the option
345 * will be applied. If no per-series value of this option is available, then
346 * the global value is returned. This is optional.
347 * @return { ... } The value of the option.
348 */
349 Dygraph.prototype.attr_ = function(name, seriesName) {
350 // <REMOVE_FOR_COMBINED>
351 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
352 this.error('Must include options reference JS for testing');
353 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
354 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
355 'in the Dygraphs.OPTIONS_REFERENCE listing.');
356 // Only log this error once.
357 Dygraph.OPTIONS_REFERENCE[name] = true;
358 }
359 // </REMOVE_FOR_COMBINED>
360 if (seriesName &&
361 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
362 this.user_attrs_[seriesName] != null &&
363 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
364 return this.user_attrs_[seriesName][name];
365 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
366 return this.user_attrs_[name];
367 } else if (typeof(this.attrs_[name]) != 'undefined') {
368 return this.attrs_[name];
369 } else {
370 return null;
371 }
372 };
373
374 // TODO(danvk): any way I can get the line numbers to be this.warn call?
375 /**
376 * @private
377 * Log an error on the JS console at the given severity.
378 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
379 * @param { String } The message to log.
380 */
381 Dygraph.prototype.log = function(severity, message) {
382 if (typeof(console) != 'undefined') {
383 switch (severity) {
384 case Dygraph.DEBUG:
385 console.debug('dygraphs: ' + message);
386 break;
387 case Dygraph.INFO:
388 console.info('dygraphs: ' + message);
389 break;
390 case Dygraph.WARNING:
391 console.warn('dygraphs: ' + message);
392 break;
393 case Dygraph.ERROR:
394 console.error('dygraphs: ' + message);
395 break;
396 }
397 }
398 };
399
400 /** @private */
401 Dygraph.prototype.info = function(message) {
402 this.log(Dygraph.INFO, message);
403 };
404
405 /** @private */
406 Dygraph.prototype.warn = function(message) {
407 this.log(Dygraph.WARNING, message);
408 };
409
410 /** @private */
411 Dygraph.prototype.error = function(message) {
412 this.log(Dygraph.ERROR, message);
413 };
414
415 /**
416 * Returns the current rolling period, as set by the user or an option.
417 * @return {Number} The number of points in the rolling window
418 */
419 Dygraph.prototype.rollPeriod = function() {
420 return this.rollPeriod_;
421 };
422
423 /**
424 * Returns the currently-visible x-range. This can be affected by zooming,
425 * panning or a call to updateOptions.
426 * Returns a two-element array: [left, right].
427 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
428 */
429 Dygraph.prototype.xAxisRange = function() {
430 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
431 };
432
433 /**
434 * Returns the lower- and upper-bound x-axis values of the
435 * data set.
436 */
437 Dygraph.prototype.xAxisExtremes = function() {
438 var left = this.rawData_[0][0];
439 var right = this.rawData_[this.rawData_.length - 1][0];
440 return [left, right];
441 };
442
443 /**
444 * Returns the currently-visible y-range for an axis. This can be affected by
445 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
446 * called with no arguments, returns the range of the first axis.
447 * Returns a two-element array: [bottom, top].
448 */
449 Dygraph.prototype.yAxisRange = function(idx) {
450 if (typeof(idx) == "undefined") idx = 0;
451 if (idx < 0 || idx >= this.axes_.length) return null;
452 return [ this.axes_[idx].computedValueRange[0],
453 this.axes_[idx].computedValueRange[1] ];
454 };
455
456 /**
457 * Returns the currently-visible y-ranges for each axis. This can be affected by
458 * zooming, panning, calls to updateOptions, etc.
459 * Returns an array of [bottom, top] pairs, one for each y-axis.
460 */
461 Dygraph.prototype.yAxisRanges = function() {
462 var ret = [];
463 for (var i = 0; i < this.axes_.length; i++) {
464 ret.push(this.yAxisRange(i));
465 }
466 return ret;
467 };
468
469 // TODO(danvk): use these functions throughout dygraphs.
470 /**
471 * Convert from data coordinates to canvas/div X/Y coordinates.
472 * If specified, do this conversion for the coordinate system of a particular
473 * axis. Uses the first axis by default.
474 * Returns a two-element array: [X, Y]
475 *
476 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
477 * instead of toDomCoords(null, y, axis).
478 */
479 Dygraph.prototype.toDomCoords = function(x, y, axis) {
480 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
481 };
482
483 /**
484 * Convert from data x coordinates to canvas/div X coordinate.
485 * If specified, do this conversion for the coordinate system of a particular
486 * axis.
487 * Returns a single value or null if x is null.
488 */
489 Dygraph.prototype.toDomXCoord = function(x) {
490 if (x == null) {
491 return null;
492 };
493
494 var area = this.plotter_.area;
495 var xRange = this.xAxisRange();
496 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
497 }
498
499 /**
500 * Convert from data x coordinates to canvas/div Y coordinate and optional
501 * axis. Uses the first axis by default.
502 *
503 * returns a single value or null if y is null.
504 */
505 Dygraph.prototype.toDomYCoord = function(y, axis) {
506 var pct = this.toPercentYCoord(y, axis);
507
508 if (pct == null) {
509 return null;
510 }
511 var area = this.plotter_.area;
512 return area.y + pct * area.h;
513 }
514
515 /**
516 * Convert from canvas/div coords to data coordinates.
517 * If specified, do this conversion for the coordinate system of a particular
518 * axis. Uses the first axis by default.
519 * Returns a two-element array: [X, Y].
520 *
521 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
522 * instead of toDataCoords(null, y, axis).
523 */
524 Dygraph.prototype.toDataCoords = function(x, y, axis) {
525 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
526 };
527
528 /**
529 * Convert from canvas/div x coordinate to data coordinate.
530 *
531 * If x is null, this returns null.
532 */
533 Dygraph.prototype.toDataXCoord = function(x) {
534 if (x == null) {
535 return null;
536 }
537
538 var area = this.plotter_.area;
539 var xRange = this.xAxisRange();
540 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
541 };
542
543 /**
544 * Convert from canvas/div y coord to value.
545 *
546 * If y is null, this returns null.
547 * if axis is null, this uses the first axis.
548 */
549 Dygraph.prototype.toDataYCoord = function(y, axis) {
550 if (y == null) {
551 return null;
552 }
553
554 var area = this.plotter_.area;
555 var yRange = this.yAxisRange(axis);
556
557 if (typeof(axis) == "undefined") axis = 0;
558 if (!this.axes_[axis].logscale) {
559 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
560 } else {
561 // Computing the inverse of toDomCoord.
562 var pct = (y - area.y) / area.h
563
564 // Computing the inverse of toPercentYCoord. The function was arrived at with
565 // the following steps:
566 //
567 // Original calcuation:
568 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
569 //
570 // Move denominator to both sides:
571 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
572 //
573 // subtract logr1, and take the negative value.
574 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
575 //
576 // Swap both sides of the equation, and we can compute the log of the
577 // return value. Which means we just need to use that as the exponent in
578 // e^exponent.
579 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
580
581 var logr1 = Dygraph.log10(yRange[1]);
582 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
583 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
584 return value;
585 }
586 };
587
588 /**
589 * Converts a y for an axis to a percentage from the top to the
590 * bottom of the drawing area.
591 *
592 * If the coordinate represents a value visible on the canvas, then
593 * the value will be between 0 and 1, where 0 is the top of the canvas.
594 * However, this method will return values outside the range, as
595 * values can fall outside the canvas.
596 *
597 * If y is null, this returns null.
598 * if axis is null, this uses the first axis.
599 *
600 * @param { Number } y The data y-coordinate.
601 * @param { Number } [axis] The axis number on which the data coordinate lives.
602 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
603 */
604 Dygraph.prototype.toPercentYCoord = function(y, axis) {
605 if (y == null) {
606 return null;
607 }
608 if (typeof(axis) == "undefined") axis = 0;
609
610 var area = this.plotter_.area;
611 var yRange = this.yAxisRange(axis);
612
613 var pct;
614 if (!this.axes_[axis].logscale) {
615 // yRange[1] - y is unit distance from the bottom.
616 // yRange[1] - yRange[0] is the scale of the range.
617 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
618 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
619 } else {
620 var logr1 = Dygraph.log10(yRange[1]);
621 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
622 }
623 return pct;
624 }
625
626 /**
627 * Converts an x value to a percentage from the left to the right of
628 * the drawing area.
629 *
630 * If the coordinate represents a value visible on the canvas, then
631 * the value will be between 0 and 1, where 0 is the left of the canvas.
632 * However, this method will return values outside the range, as
633 * values can fall outside the canvas.
634 *
635 * If x is null, this returns null.
636 * @param { Number } x The data x-coordinate.
637 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
638 */
639 Dygraph.prototype.toPercentXCoord = function(x) {
640 if (x == null) {
641 return null;
642 }
643
644 var xRange = this.xAxisRange();
645 return (x - xRange[0]) / (xRange[1] - xRange[0]);
646 };
647
648 /**
649 * Returns the number of columns (including the independent variable).
650 * @return { Integer } The number of columns.
651 */
652 Dygraph.prototype.numColumns = function() {
653 return this.rawData_[0].length;
654 };
655
656 /**
657 * Returns the number of rows (excluding any header/label row).
658 * @return { Integer } The number of rows, less any header.
659 */
660 Dygraph.prototype.numRows = function() {
661 return this.rawData_.length;
662 };
663
664 /**
665 * Returns the value in the given row and column. If the row and column exceed
666 * the bounds on the data, returns null. Also returns null if the value is
667 * missing.
668 * @param { Number} row The row number of the data (0-based). Row 0 is the
669 * first row of data, not a header row.
670 * @param { Number} col The column number of the data (0-based)
671 * @return { Number } The value in the specified cell or null if the row/col
672 * were out of range.
673 */
674 Dygraph.prototype.getValue = function(row, col) {
675 if (row < 0 || row > this.rawData_.length) return null;
676 if (col < 0 || col > this.rawData_[row].length) return null;
677
678 return this.rawData_[row][col];
679 };
680
681 /**
682 * @private
683 * Add an event handler. This smooths a difference between IE and the rest of
684 * the world.
685 * @param { DOM element } el The element to add the event to.
686 * @param { String } evt The name of the event, e.g. 'click' or 'mousemove'.
687 * @param { Function } fn The function to call on the event. The function takes
688 * one parameter: the event object.
689 */
690 Dygraph.addEvent = function(el, evt, fn) {
691 var normed_fn = function(e) {
692 if (!e) var e = window.event;
693 fn(e);
694 };
695 if (window.addEventListener) { // Mozilla, Netscape, Firefox
696 el.addEventListener(evt, normed_fn, false);
697 } else { // IE
698 el.attachEvent('on' + evt, normed_fn);
699 }
700 };
701
702
703 /**
704 * @private
705 * Cancels further processing of an event. This is useful to prevent default
706 * browser actions, e.g. highlighting text on a double-click.
707 * Based on the article at
708 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
709 * @param { Event } e The event whose normal behavior should be canceled.
710 */
711 Dygraph.cancelEvent = function(e) {
712 e = e ? e : window.event;
713 if (e.stopPropagation) {
714 e.stopPropagation();
715 }
716 if (e.preventDefault) {
717 e.preventDefault();
718 }
719 e.cancelBubble = true;
720 e.cancel = true;
721 e.returnValue = false;
722 return false;
723 };
724
725
726 /**
727 * Generates interface elements for the Dygraph: a containing div, a div to
728 * display the current point, and a textbox to adjust the rolling average
729 * period. Also creates the Renderer/Layout elements.
730 * @private
731 */
732 Dygraph.prototype.createInterface_ = function() {
733 // Create the all-enclosing graph div
734 var enclosing = this.maindiv_;
735
736 this.graphDiv = document.createElement("div");
737 this.graphDiv.style.width = this.width_ + "px";
738 this.graphDiv.style.height = this.height_ + "px";
739 enclosing.appendChild(this.graphDiv);
740
741 // Create the canvas for interactive parts of the chart.
742 this.canvas_ = Dygraph.createCanvas();
743 this.canvas_.style.position = "absolute";
744 this.canvas_.width = this.width_;
745 this.canvas_.height = this.height_;
746 this.canvas_.style.width = this.width_ + "px"; // for IE
747 this.canvas_.style.height = this.height_ + "px"; // for IE
748
749 this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
750
751 // ... and for static parts of the chart.
752 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
753 this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
754
755 // The interactive parts of the graph are drawn on top of the chart.
756 this.graphDiv.appendChild(this.hidden_);
757 this.graphDiv.appendChild(this.canvas_);
758 this.mouseEventElement_ = this.canvas_;
759
760 var dygraph = this;
761 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
762 dygraph.mouseMove_(e);
763 });
764 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
765 dygraph.mouseOut_(e);
766 });
767
768 // Create the grapher
769 this.layout_ = new DygraphLayout(this);
770
771 this.createStatusMessage_();
772 this.createDragInterface_();
773 };
774
775 /**
776 * Detach DOM elements in the dygraph and null out all data references.
777 * Calling this when you're done with a dygraph can dramatically reduce memory
778 * usage. See, e.g., the tests/perf.html example.
779 */
780 Dygraph.prototype.destroy = function() {
781 var removeRecursive = function(node) {
782 while (node.hasChildNodes()) {
783 removeRecursive(node.firstChild);
784 node.removeChild(node.firstChild);
785 }
786 };
787 removeRecursive(this.maindiv_);
788
789 var nullOut = function(obj) {
790 for (var n in obj) {
791 if (typeof(obj[n]) === 'object') {
792 obj[n] = null;
793 }
794 }
795 };
796
797 // These may not all be necessary, but it can't hurt...
798 nullOut(this.layout_);
799 nullOut(this.plotter_);
800 nullOut(this);
801 };
802
803 /**
804 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
805 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
806 * or the zoom rectangles) is done on this.canvas_.
807 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
808 * @return {Object} The newly-created canvas
809 * @private
810 */
811 Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
812 var h = Dygraph.createCanvas();
813 h.style.position = "absolute";
814 // TODO(danvk): h should be offset from canvas. canvas needs to include
815 // some extra area to make it easier to zoom in on the far left and far
816 // right. h needs to be precisely the plot area, so that clipping occurs.
817 h.style.top = canvas.style.top;
818 h.style.left = canvas.style.left;
819 h.width = this.width_;
820 h.height = this.height_;
821 h.style.width = this.width_ + "px"; // for IE
822 h.style.height = this.height_ + "px"; // for IE
823 return h;
824 };
825
826 /**
827 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
828 * is used to generate default series colors which are evenly spaced on the
829 * color wheel.
830 * @param { Number } hue Range is 0.0-1.0.
831 * @param { Number } saturation Range is 0.0-1.0.
832 * @param { Number } value Range is 0.0-1.0.
833 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
834 * @private
835 */
836 Dygraph.hsvToRGB = function (hue, saturation, value) {
837 var red;
838 var green;
839 var blue;
840 if (saturation === 0) {
841 red = value;
842 green = value;
843 blue = value;
844 } else {
845 var i = Math.floor(hue * 6);
846 var f = (hue * 6) - i;
847 var p = value * (1 - saturation);
848 var q = value * (1 - (saturation * f));
849 var t = value * (1 - (saturation * (1 - f)));
850 switch (i) {
851 case 1: red = q; green = value; blue = p; break;
852 case 2: red = p; green = value; blue = t; break;
853 case 3: red = p; green = q; blue = value; break;
854 case 4: red = t; green = p; blue = value; break;
855 case 5: red = value; green = p; blue = q; break;
856 case 6: // fall through
857 case 0: red = value; green = t; blue = p; break;
858 }
859 }
860 red = Math.floor(255 * red + 0.5);
861 green = Math.floor(255 * green + 0.5);
862 blue = Math.floor(255 * blue + 0.5);
863 return 'rgb(' + red + ',' + green + ',' + blue + ')';
864 };
865
866
867 /**
868 * Generate a set of distinct colors for the data series. This is done with a
869 * color wheel. Saturation/Value are customizable, and the hue is
870 * equally-spaced around the color wheel. If a custom set of colors is
871 * specified, that is used instead.
872 * @private
873 */
874 Dygraph.prototype.setColors_ = function() {
875 var num = this.attr_("labels").length - 1;
876 this.colors_ = [];
877 var colors = this.attr_('colors');
878 if (!colors) {
879 var sat = this.attr_('colorSaturation') || 1.0;
880 var val = this.attr_('colorValue') || 0.5;
881 var half = Math.ceil(num / 2);
882 for (var i = 1; i <= num; i++) {
883 if (!this.visibility()[i-1]) continue;
884 // alternate colors for high contrast.
885 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
886 var hue = (1.0 * idx/ (1 + num));
887 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
888 }
889 } else {
890 for (var i = 0; i < num; i++) {
891 if (!this.visibility()[i]) continue;
892 var colorStr = colors[i % colors.length];
893 this.colors_.push(colorStr);
894 }
895 }
896
897 this.plotter_.setColors(this.colors_);
898 };
899
900 /**
901 * Return the list of colors. This is either the list of colors passed in the
902 * attributes or the autogenerated list of rgb(r,g,b) strings.
903 * @return {Array<string>} The list of colors.
904 */
905 Dygraph.prototype.getColors = function() {
906 return this.colors_;
907 };
908
909 // The following functions are from quirksmode.org with a modification for Safari from
910 // http://blog.firetree.net/2005/07/04/javascript-find-position/
911 // http://www.quirksmode.org/js/findpos.html
912
913 /** @private */
914 Dygraph.findPosX = function(obj) {
915 var curleft = 0;
916 if(obj.offsetParent)
917 while(1)
918 {
919 curleft += obj.offsetLeft;
920 if(!obj.offsetParent)
921 break;
922 obj = obj.offsetParent;
923 }
924 else if(obj.x)
925 curleft += obj.x;
926 return curleft;
927 };
928
929
930 /** @private */
931 Dygraph.findPosY = function(obj) {
932 var curtop = 0;
933 if(obj.offsetParent)
934 while(1)
935 {
936 curtop += obj.offsetTop;
937 if(!obj.offsetParent)
938 break;
939 obj = obj.offsetParent;
940 }
941 else if(obj.y)
942 curtop += obj.y;
943 return curtop;
944 };
945
946
947 /**
948 * Create the div that contains information on the selected point(s)
949 * This goes in the top right of the canvas, unless an external div has already
950 * been specified.
951 * @private
952 */
953 Dygraph.prototype.createStatusMessage_ = function() {
954 var userLabelsDiv = this.user_attrs_["labelsDiv"];
955 if (userLabelsDiv && null != userLabelsDiv
956 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
957 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
958 }
959 if (!this.attr_("labelsDiv")) {
960 var divWidth = this.attr_('labelsDivWidth');
961 var messagestyle = {
962 "position": "absolute",
963 "fontSize": "14px",
964 "zIndex": 10,
965 "width": divWidth + "px",
966 "top": "0px",
967 "left": (this.width_ - divWidth - 2) + "px",
968 "background": "white",
969 "textAlign": "left",
970 "overflow": "hidden"};
971 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
972 var div = document.createElement("div");
973 for (var name in messagestyle) {
974 if (messagestyle.hasOwnProperty(name)) {
975 div.style[name] = messagestyle[name];
976 }
977 }
978 this.graphDiv.appendChild(div);
979 this.attrs_.labelsDiv = div;
980 }
981 };
982
983 /**
984 * Position the labels div so that:
985 * - its right edge is flush with the right edge of the charting area
986 * - its top edge is flush with the top edge of the charting area
987 * @private
988 */
989 Dygraph.prototype.positionLabelsDiv_ = function() {
990 // Don't touch a user-specified labelsDiv.
991 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
992
993 var area = this.plotter_.area;
994 var div = this.attr_("labelsDiv");
995 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
996 div.style.top = area.y + "px";
997 };
998
999 /**
1000 * Create the text box to adjust the averaging period
1001 * @private
1002 */
1003 Dygraph.prototype.createRollInterface_ = function() {
1004 // Create a roller if one doesn't exist already.
1005 if (!this.roller_) {
1006 this.roller_ = document.createElement("input");
1007 this.roller_.type = "text";
1008 this.roller_.style.display = "none";
1009 this.graphDiv.appendChild(this.roller_);
1010 }
1011
1012 var display = this.attr_('showRoller') ? 'block' : 'none';
1013
1014 var area = this.plotter_.area;
1015 var textAttr = { "position": "absolute",
1016 "zIndex": 10,
1017 "top": (area.y + area.h - 25) + "px",
1018 "left": (area.x + 1) + "px",
1019 "display": display
1020 };
1021 this.roller_.size = "2";
1022 this.roller_.value = this.rollPeriod_;
1023 for (var name in textAttr) {
1024 if (textAttr.hasOwnProperty(name)) {
1025 this.roller_.style[name] = textAttr[name];
1026 }
1027 }
1028
1029 var dygraph = this;
1030 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
1031 };
1032
1033 /**
1034 * @private
1035 * Returns the x-coordinate of the event in a coordinate system where the
1036 * top-left corner of the page (not the window) is (0,0).
1037 * Taken from MochiKit.Signal
1038 */
1039 Dygraph.pageX = function(e) {
1040 if (e.pageX) {
1041 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
1042 } else {
1043 var de = document;
1044 var b = document.body;
1045 return e.clientX +
1046 (de.scrollLeft || b.scrollLeft) -
1047 (de.clientLeft || 0);
1048 }
1049 };
1050
1051 /**
1052 * @private
1053 * Returns the y-coordinate of the event in a coordinate system where the
1054 * top-left corner of the page (not the window) is (0,0).
1055 * Taken from MochiKit.Signal
1056 */
1057 Dygraph.pageY = function(e) {
1058 if (e.pageY) {
1059 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
1060 } else {
1061 var de = document;
1062 var b = document.body;
1063 return e.clientY +
1064 (de.scrollTop || b.scrollTop) -
1065 (de.clientTop || 0);
1066 }
1067 };
1068
1069 /**
1070 * @private
1071 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1072 * canvas (i.e. DOM Coords).
1073 */
1074 Dygraph.prototype.dragGetX_ = function(e, context) {
1075 return Dygraph.pageX(e) - context.px
1076 };
1077
1078 /**
1079 * @private
1080 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1081 * canvas (i.e. DOM Coords).
1082 */
1083 Dygraph.prototype.dragGetY_ = function(e, context) {
1084 return Dygraph.pageY(e) - context.py
1085 };
1086
1087 /**
1088 * A collection of functions to facilitate build custom interaction models.
1089 * @class
1090 */
1091 Dygraph.Interaction = {};
1092
1093 /**
1094 * Called in response to an interaction model operation that
1095 * should start the default panning behavior.
1096 *
1097 * It's used in the default callback for "mousedown" operations.
1098 * Custom interaction model builders can use it to provide the default
1099 * panning behavior.
1100 *
1101 * @param { Event } event the event object which led to the startPan call.
1102 * @param { Dygraph} g The dygraph on which to act.
1103 * @param { Object} context The dragging context object (with
1104 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1105 */
1106 Dygraph.Interaction.startPan = function(event, g, context) {
1107 context.isPanning = true;
1108 var xRange = g.xAxisRange();
1109 context.dateRange = xRange[1] - xRange[0];
1110 context.initialLeftmostDate = xRange[0];
1111 context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
1112
1113 if (g.attr_("panEdgeFraction")) {
1114 var maxXPixelsToDraw = g.width_ * g.attr_("panEdgeFraction");
1115 var xExtremes = g.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes!
1116
1117 var boundedLeftX = g.toDomXCoord(xExtremes[0]) - maxXPixelsToDraw;
1118 var boundedRightX = g.toDomXCoord(xExtremes[1]) + maxXPixelsToDraw;
1119
1120 var boundedLeftDate = g.toDataXCoord(boundedLeftX);
1121 var boundedRightDate = g.toDataXCoord(boundedRightX);
1122 context.boundedDates = [boundedLeftDate, boundedRightDate];
1123
1124 var boundedValues = [];
1125 var maxYPixelsToDraw = g.height_ * g.attr_("panEdgeFraction");
1126
1127 for (var i = 0; i < g.axes_.length; i++) {
1128 var axis = g.axes_[i];
1129 var yExtremes = axis.extremeRange;
1130
1131 var boundedTopY = g.toDomYCoord(yExtremes[0], i) + maxYPixelsToDraw;
1132 var boundedBottomY = g.toDomYCoord(yExtremes[1], i) - maxYPixelsToDraw;
1133
1134 var boundedTopValue = g.toDataYCoord(boundedTopY);
1135 var boundedBottomValue = g.toDataYCoord(boundedBottomY);
1136
1137 boundedValues[i] = [boundedTopValue, boundedBottomValue];
1138 }
1139 context.boundedValues = boundedValues;
1140 }
1141
1142 // Record the range of each y-axis at the start of the drag.
1143 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
1144 context.is2DPan = false;
1145 for (var i = 0; i < g.axes_.length; i++) {
1146 var axis = g.axes_[i];
1147 var yRange = g.yAxisRange(i);
1148 // TODO(konigsberg): These values should be in |context|.
1149 // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
1150 if (axis.logscale) {
1151 axis.initialTopValue = Dygraph.log10(yRange[1]);
1152 axis.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]);
1153 } else {
1154 axis.initialTopValue = yRange[1];
1155 axis.dragValueRange = yRange[1] - yRange[0];
1156 }
1157 axis.unitsPerPixel = axis.dragValueRange / (g.plotter_.area.h - 1);
1158
1159 // While calculating axes, set 2dpan.
1160 if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
1161 }
1162 };
1163
1164 /**
1165 * Called in response to an interaction model operation that
1166 * responds to an event that pans the view.
1167 *
1168 * It's used in the default callback for "mousemove" operations.
1169 * Custom interaction model builders can use it to provide the default
1170 * panning behavior.
1171 *
1172 * @param { Event } event the event object which led to the movePan call.
1173 * @param { Dygraph} g The dygraph on which to act.
1174 * @param { Object} context The dragging context object (with
1175 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1176 */
1177 Dygraph.Interaction.movePan = function(event, g, context) {
1178 context.dragEndX = g.dragGetX_(event, context);
1179 context.dragEndY = g.dragGetY_(event, context);
1180
1181 var minDate = context.initialLeftmostDate -
1182 (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
1183 if (context.boundedDates) {
1184 minDate = Math.max(minDate, context.boundedDates[0]);
1185 }
1186 var maxDate = minDate + context.dateRange;
1187 if (context.boundedDates) {
1188 if (maxDate > context.boundedDates[1]) {
1189 // Adjust minDate, and recompute maxDate.
1190 minDate = minDate - (maxDate - context.boundedDates[1]);
1191 maxDate = minDate + context.dateRange;
1192 }
1193 }
1194
1195 g.dateWindow_ = [minDate, maxDate];
1196
1197 // y-axis scaling is automatic unless this is a full 2D pan.
1198 if (context.is2DPan) {
1199 // Adjust each axis appropriately.
1200 for (var i = 0; i < g.axes_.length; i++) {
1201 var axis = g.axes_[i];
1202
1203 var pixelsDragged = context.dragEndY - context.dragStartY;
1204 var unitsDragged = pixelsDragged * axis.unitsPerPixel;
1205
1206 var boundedValue = context.boundedValues ? context.boundedValues[i] : null;
1207
1208 // In log scale, maxValue and minValue are the logs of those values.
1209 var maxValue = axis.initialTopValue + unitsDragged;
1210 if (boundedValue) {
1211 maxValue = Math.min(maxValue, boundedValue[1]);
1212 }
1213 var minValue = maxValue - axis.dragValueRange;
1214 if (boundedValue) {
1215 if (minValue < boundedValue[0]) {
1216 // Adjust maxValue, and recompute minValue.
1217 maxValue = maxValue - (minValue - boundedValue[0]);
1218 minValue = maxValue - axis.dragValueRange;
1219 }
1220 }
1221 if (axis.logscale) {
1222 axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue),
1223 Math.pow(Dygraph.LOG_SCALE, maxValue) ];
1224 } else {
1225 axis.valueWindow = [ minValue, maxValue ];
1226 }
1227 }
1228 }
1229
1230 g.drawGraph_();
1231 };
1232
1233 /**
1234 * Called in response to an interaction model operation that
1235 * responds to an event that ends panning.
1236 *
1237 * It's used in the default callback for "mouseup" operations.
1238 * Custom interaction model builders can use it to provide the default
1239 * panning behavior.
1240 *
1241 * @param { Event } event the event object which led to the startZoom call.
1242 * @param { Dygraph} g The dygraph on which to act.
1243 * @param { Object} context The dragging context object (with
1244 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1245 */
1246 Dygraph.Interaction.endPan = function(event, g, context) {
1247 // TODO(konigsberg): Clear the context data from the axis.
1248 // TODO(konigsberg): mouseup should just delete the
1249 // context object, and mousedown should create a new one.
1250 context.isPanning = false;
1251 context.is2DPan = false;
1252 context.initialLeftmostDate = null;
1253 context.dateRange = null;
1254 context.valueRange = null;
1255 context.boundedDates = null;
1256 context.boundedValues = null;
1257 };
1258
1259 /**
1260 * Called in response to an interaction model operation that
1261 * responds to an event that starts zooming.
1262 *
1263 * It's used in the default callback for "mousedown" operations.
1264 * Custom interaction model builders can use it to provide the default
1265 * zooming behavior.
1266 *
1267 * @param { Event } event the event object which led to the startZoom call.
1268 * @param { Dygraph} g The dygraph on which to act.
1269 * @param { Object} context The dragging context object (with
1270 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1271 */
1272 Dygraph.Interaction.startZoom = function(event, g, context) {
1273 context.isZooming = true;
1274 };
1275
1276 /**
1277 * Called in response to an interaction model operation that
1278 * responds to an event that defines zoom boundaries.
1279 *
1280 * It's used in the default callback for "mousemove" operations.
1281 * Custom interaction model builders can use it to provide the default
1282 * zooming behavior.
1283 *
1284 * @param { Event } event the event object which led to the moveZoom call.
1285 * @param { Dygraph} g The dygraph on which to act.
1286 * @param { Object} context The dragging context object (with
1287 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1288 */
1289 Dygraph.Interaction.moveZoom = function(event, g, context) {
1290 context.dragEndX = g.dragGetX_(event, context);
1291 context.dragEndY = g.dragGetY_(event, context);
1292
1293 var xDelta = Math.abs(context.dragStartX - context.dragEndX);
1294 var yDelta = Math.abs(context.dragStartY - context.dragEndY);
1295
1296 // drag direction threshold for y axis is twice as large as x axis
1297 context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL;
1298
1299 g.drawZoomRect_(
1300 context.dragDirection,
1301 context.dragStartX,
1302 context.dragEndX,
1303 context.dragStartY,
1304 context.dragEndY,
1305 context.prevDragDirection,
1306 context.prevEndX,
1307 context.prevEndY);
1308
1309 context.prevEndX = context.dragEndX;
1310 context.prevEndY = context.dragEndY;
1311 context.prevDragDirection = context.dragDirection;
1312 };
1313
1314 /**
1315 * Called in response to an interaction model operation that
1316 * responds to an event that performs a zoom based on previously defined
1317 * bounds..
1318 *
1319 * It's used in the default callback for "mouseup" operations.
1320 * Custom interaction model builders can use it to provide the default
1321 * zooming behavior.
1322 *
1323 * @param { Event } event the event object which led to the endZoom call.
1324 * @param { Dygraph} g The dygraph on which to end the zoom.
1325 * @param { Object} context The dragging context object (with
1326 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1327 */
1328 Dygraph.Interaction.endZoom = function(event, g, context) {
1329 // TODO(konigsberg): Refactor or rename this fn -- it deals with clicks, too.
1330 context.isZooming = false;
1331 context.dragEndX = g.dragGetX_(event, context);
1332 context.dragEndY = g.dragGetY_(event, context);
1333 var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
1334 var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
1335
1336 if (regionWidth < 2 && regionHeight < 2 &&
1337 g.lastx_ != undefined && g.lastx_ != -1) {
1338 // TODO(danvk): pass along more info about the points, e.g. 'x'
1339 if (g.attr_('clickCallback') != null) {
1340 g.attr_('clickCallback')(event, g.lastx_, g.selPoints_);
1341 }
1342 if (g.attr_('pointClickCallback')) {
1343 // check if the click was on a particular point.
1344 var closestIdx = -1;
1345 var closestDistance = 0;
1346 for (var i = 0; i < g.selPoints_.length; i++) {
1347 var p = g.selPoints_[i];
1348 var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
1349 Math.pow(p.canvasy - context.dragEndY, 2);
1350 if (closestIdx == -1 || distance < closestDistance) {
1351 closestDistance = distance;
1352 closestIdx = i;
1353 }
1354 }
1355
1356 // Allow any click within two pixels of the dot.
1357 var radius = g.attr_('highlightCircleSize') + 2;
1358 if (closestDistance <= 5 * 5) {
1359 g.attr_('pointClickCallback')(event, g.selPoints_[closestIdx]);
1360 }
1361 }
1362 }
1363
1364 if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) {
1365 g.doZoomX_(Math.min(context.dragStartX, context.dragEndX),
1366 Math.max(context.dragStartX, context.dragEndX));
1367 } else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) {
1368 g.doZoomY_(Math.min(context.dragStartY, context.dragEndY),
1369 Math.max(context.dragStartY, context.dragEndY));
1370 } else {
1371 g.canvas_ctx_.clearRect(0, 0, g.canvas_.width, g.canvas_.height);
1372 }
1373 context.dragStartX = null;
1374 context.dragStartY = null;
1375 };
1376
1377 /**
1378 * Default interation model for dygraphs. You can refer to specific elements of
1379 * this when constructing your own interaction model, e.g.:
1380 * g.updateOptions( {
1381 * interactionModel: {
1382 * mousedown: Dygraph.defaultInteractionModel.mousedown
1383 * }
1384 * } );
1385 */
1386 Dygraph.Interaction.defaultModel = {
1387 // Track the beginning of drag events
1388 mousedown: function(event, g, context) {
1389 context.initializeMouseDown(event, g, context);
1390
1391 if (event.altKey || event.shiftKey) {
1392 Dygraph.startPan(event, g, context);
1393 } else {
1394 Dygraph.startZoom(event, g, context);
1395 }
1396 },
1397
1398 // Draw zoom rectangles when the mouse is down and the user moves around
1399 mousemove: function(event, g, context) {
1400 if (context.isZooming) {
1401 Dygraph.moveZoom(event, g, context);
1402 } else if (context.isPanning) {
1403 Dygraph.movePan(event, g, context);
1404 }
1405 },
1406
1407 mouseup: function(event, g, context) {
1408 if (context.isZooming) {
1409 Dygraph.endZoom(event, g, context);
1410 } else if (context.isPanning) {
1411 Dygraph.endPan(event, g, context);
1412 }
1413 },
1414
1415 // Temporarily cancel the dragging event when the mouse leaves the graph
1416 mouseout: function(event, g, context) {
1417 if (context.isZooming) {
1418 context.dragEndX = null;
1419 context.dragEndY = null;
1420 }
1421 },
1422
1423 // Disable zooming out if panning.
1424 dblclick: function(event, g, context) {
1425 if (event.altKey || event.shiftKey) {
1426 return;
1427 }
1428 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1429 // friendlier to public use.
1430 g.doUnzoom_();
1431 }
1432 };
1433
1434 Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.Interaction.defaultModel;
1435
1436 // old ways of accessing these methods/properties
1437 Dygraph.defaultInteractionModel = Dygraph.Interaction.defaultModel;
1438 Dygraph.endZoom = Dygraph.Interaction.endZoom;
1439 Dygraph.moveZoom = Dygraph.Interaction.moveZoom;
1440 Dygraph.startZoom = Dygraph.Interaction.startZoom;
1441 Dygraph.endPan = Dygraph.Interaction.endPan;
1442 Dygraph.movePan = Dygraph.Interaction.movePan;
1443 Dygraph.startPan = Dygraph.Interaction.startPan;
1444
1445 /**
1446 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1447 * events.
1448 * @private
1449 */
1450 Dygraph.prototype.createDragInterface_ = function() {
1451 var context = {
1452 // Tracks whether the mouse is down right now
1453 isZooming: false,
1454 isPanning: false, // is this drag part of a pan?
1455 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
1456 dragStartX: null,
1457 dragStartY: null,
1458 dragEndX: null,
1459 dragEndY: null,
1460 dragDirection: null,
1461 prevEndX: null,
1462 prevEndY: null,
1463 prevDragDirection: null,
1464
1465 // The value on the left side of the graph when a pan operation starts.
1466 initialLeftmostDate: null,
1467
1468 // The number of units each pixel spans. (This won't be valid for log
1469 // scales)
1470 xUnitsPerPixel: null,
1471
1472 // TODO(danvk): update this comment
1473 // The range in second/value units that the viewport encompasses during a
1474 // panning operation.
1475 dateRange: null,
1476
1477 // Utility function to convert page-wide coordinates to canvas coords
1478 px: 0,
1479 py: 0,
1480
1481 // Values for use with panEdgeFraction, which limit how far outside the
1482 // graph's data boundaries it can be panned.
1483 boundedDates: null, // [minDate, maxDate]
1484 boundedValues: null, // [[minValue, maxValue] ...]
1485
1486 initializeMouseDown: function(event, g, context) {
1487 // prevents mouse drags from selecting page text.
1488 if (event.preventDefault) {
1489 event.preventDefault(); // Firefox, Chrome, etc.
1490 } else {
1491 event.returnValue = false; // IE
1492 event.cancelBubble = true;
1493 }
1494
1495 context.px = Dygraph.findPosX(g.canvas_);
1496 context.py = Dygraph.findPosY(g.canvas_);
1497 context.dragStartX = g.dragGetX_(event, context);
1498 context.dragStartY = g.dragGetY_(event, context);
1499 }
1500 };
1501
1502 var interactionModel = this.attr_("interactionModel");
1503
1504 // Self is the graph.
1505 var self = this;
1506
1507 // Function that binds the graph and context to the handler.
1508 var bindHandler = function(handler) {
1509 return function(event) {
1510 handler(event, self, context);
1511 };
1512 };
1513
1514 for (var eventName in interactionModel) {
1515 if (!interactionModel.hasOwnProperty(eventName)) continue;
1516 Dygraph.addEvent(this.mouseEventElement_, eventName,
1517 bindHandler(interactionModel[eventName]));
1518 }
1519
1520 // If the user releases the mouse button during a drag, but not over the
1521 // canvas, then it doesn't count as a zooming action.
1522 Dygraph.addEvent(document, 'mouseup', function(event) {
1523 if (context.isZooming || context.isPanning) {
1524 context.isZooming = false;
1525 context.dragStartX = null;
1526 context.dragStartY = null;
1527 }
1528
1529 if (context.isPanning) {
1530 context.isPanning = false;
1531 context.draggingDate = null;
1532 context.dateRange = null;
1533 for (var i = 0; i < self.axes_.length; i++) {
1534 delete self.axes_[i].draggingValue;
1535 delete self.axes_[i].dragValueRange;
1536 }
1537 }
1538 });
1539 };
1540
1541
1542 /**
1543 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1544 * up any previous zoom rectangles that were drawn. This could be optimized to
1545 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1546 * dots.
1547 *
1548 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1549 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1550 * @param {Number} startX The X position where the drag started, in canvas
1551 * coordinates.
1552 * @param {Number} endX The current X position of the drag, in canvas coords.
1553 * @param {Number} startY The Y position where the drag started, in canvas
1554 * coordinates.
1555 * @param {Number} endY The current Y position of the drag, in canvas coords.
1556 * @param {Number} prevDirection the value of direction on the previous call to
1557 * this function. Used to avoid excess redrawing
1558 * @param {Number} prevEndX The value of endX on the previous call to this
1559 * function. Used to avoid excess redrawing
1560 * @param {Number} prevEndY The value of endY on the previous call to this
1561 * function. Used to avoid excess redrawing
1562 * @private
1563 */
1564 Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1565 endY, prevDirection, prevEndX,
1566 prevEndY) {
1567 var ctx = this.canvas_ctx_;
1568
1569 // Clean up from the previous rect if necessary
1570 if (prevDirection == Dygraph.HORIZONTAL) {
1571 ctx.clearRect(Math.min(startX, prevEndX), 0,
1572 Math.abs(startX - prevEndX), this.height_);
1573 } else if (prevDirection == Dygraph.VERTICAL){
1574 ctx.clearRect(0, Math.min(startY, prevEndY),
1575 this.width_, Math.abs(startY - prevEndY));
1576 }
1577
1578 // Draw a light-grey rectangle to show the new viewing area
1579 if (direction == Dygraph.HORIZONTAL) {
1580 if (endX && startX) {
1581 ctx.fillStyle = "rgba(128,128,128,0.33)";
1582 ctx.fillRect(Math.min(startX, endX), 0,
1583 Math.abs(endX - startX), this.height_);
1584 }
1585 }
1586 if (direction == Dygraph.VERTICAL) {
1587 if (endY && startY) {
1588 ctx.fillStyle = "rgba(128,128,128,0.33)";
1589 ctx.fillRect(0, Math.min(startY, endY),
1590 this.width_, Math.abs(endY - startY));
1591 }
1592 }
1593 };
1594
1595 /**
1596 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1597 * the canvas. The exact zoom window may be slightly larger if there are no data
1598 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1599 * which accepts dates that match the raw data. This function redraws the graph.
1600 *
1601 * @param {Number} lowX The leftmost pixel value that should be visible.
1602 * @param {Number} highX The rightmost pixel value that should be visible.
1603 * @private
1604 */
1605 Dygraph.prototype.doZoomX_ = function(lowX, highX) {
1606 // Find the earliest and latest dates contained in this canvasx range.
1607 // Convert the call to date ranges of the raw data.
1608 var minDate = this.toDataXCoord(lowX);
1609 var maxDate = this.toDataXCoord(highX);
1610 this.doZoomXDates_(minDate, maxDate);
1611 };
1612
1613 /**
1614 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1615 * method with doZoomX which accepts pixel coordinates. This function redraws
1616 * the graph.
1617 *
1618 * @param {Number} minDate The minimum date that should be visible.
1619 * @param {Number} maxDate The maximum date that should be visible.
1620 * @private
1621 */
1622 Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
1623 this.dateWindow_ = [minDate, maxDate];
1624 this.zoomed_x_ = true;
1625 this.drawGraph_();
1626 if (this.attr_("zoomCallback")) {
1627 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
1628 }
1629 };
1630
1631 /**
1632 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1633 * the canvas. This function redraws the graph.
1634 *
1635 * @param {Number} lowY The topmost pixel value that should be visible.
1636 * @param {Number} highY The lowest pixel value that should be visible.
1637 * @private
1638 */
1639 Dygraph.prototype.doZoomY_ = function(lowY, highY) {
1640 // Find the highest and lowest values in pixel range for each axis.
1641 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1642 // This is because pixels increase as you go down on the screen, whereas data
1643 // coordinates increase as you go up the screen.
1644 var valueRanges = [];
1645 for (var i = 0; i < this.axes_.length; i++) {
1646 var hi = this.toDataYCoord(lowY, i);
1647 var low = this.toDataYCoord(highY, i);
1648 this.axes_[i].valueWindow = [low, hi];
1649 valueRanges.push([low, hi]);
1650 }
1651
1652 this.zoomed_y_ = true;
1653 this.drawGraph_();
1654 if (this.attr_("zoomCallback")) {
1655 var xRange = this.xAxisRange();
1656 var yRange = this.yAxisRange();
1657 this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges());
1658 }
1659 };
1660
1661 /**
1662 * Reset the zoom to the original view coordinates. This is the same as
1663 * double-clicking on the graph.
1664 *
1665 * @private
1666 */
1667 Dygraph.prototype.doUnzoom_ = function() {
1668 var dirty = false;
1669 if (this.dateWindow_ != null) {
1670 dirty = true;
1671 this.dateWindow_ = null;
1672 }
1673
1674 for (var i = 0; i < this.axes_.length; i++) {
1675 if (this.axes_[i].valueWindow != null) {
1676 dirty = true;
1677 delete this.axes_[i].valueWindow;
1678 }
1679 }
1680
1681 // Clear any selection, since it's likely to be drawn in the wrong place.
1682 this.clearSelection();
1683
1684 if (dirty) {
1685 // Putting the drawing operation before the callback because it resets
1686 // yAxisRange.
1687 this.zoomed_x_ = false;
1688 this.zoomed_y_ = false;
1689 this.drawGraph_();
1690 if (this.attr_("zoomCallback")) {
1691 var minDate = this.rawData_[0][0];
1692 var maxDate = this.rawData_[this.rawData_.length - 1][0];
1693 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
1694 }
1695 }
1696 };
1697
1698 /**
1699 * When the mouse moves in the canvas, display information about a nearby data
1700 * point and draw dots over those points in the data series. This function
1701 * takes care of cleanup of previously-drawn dots.
1702 * @param {Object} event The mousemove event from the browser.
1703 * @private
1704 */
1705 Dygraph.prototype.mouseMove_ = function(event) {
1706 // This prevents JS errors when mousing over the canvas before data loads.
1707 var points = this.layout_.points;
1708 if (points === undefined) return;
1709
1710 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
1711
1712 var lastx = -1;
1713 var lasty = -1;
1714
1715 // Loop through all the points and find the date nearest to our current
1716 // location.
1717 var minDist = 1e+100;
1718 var idx = -1;
1719 for (var i = 0; i < points.length; i++) {
1720 var point = points[i];
1721 if (point == null) continue;
1722 var dist = Math.abs(point.canvasx - canvasx);
1723 if (dist > minDist) continue;
1724 minDist = dist;
1725 idx = i;
1726 }
1727 if (idx >= 0) lastx = points[idx].xval;
1728
1729 // Extract the points we've selected
1730 this.selPoints_ = [];
1731 var l = points.length;
1732 if (!this.attr_("stackedGraph")) {
1733 for (var i = 0; i < l; i++) {
1734 if (points[i].xval == lastx) {
1735 this.selPoints_.push(points[i]);
1736 }
1737 }
1738 } else {
1739 // Need to 'unstack' points starting from the bottom
1740 var cumulative_sum = 0;
1741 for (var i = l - 1; i >= 0; i--) {
1742 if (points[i].xval == lastx) {
1743 var p = {}; // Clone the point since we modify it
1744 for (var k in points[i]) {
1745 p[k] = points[i][k];
1746 }
1747 p.yval -= cumulative_sum;
1748 cumulative_sum += p.yval;
1749 this.selPoints_.push(p);
1750 }
1751 }
1752 this.selPoints_.reverse();
1753 }
1754
1755 if (this.attr_("highlightCallback")) {
1756 var px = this.lastx_;
1757 if (px !== null && lastx != px) {
1758 // only fire if the selected point has changed.
1759 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
1760 }
1761 }
1762
1763 // Save last x position for callbacks.
1764 this.lastx_ = lastx;
1765
1766 this.updateSelection_();
1767 };
1768
1769 /**
1770 * Transforms layout_.points index into data row number.
1771 * @param int layout_.points index
1772 * @return int row number, or -1 if none could be found.
1773 * @private
1774 */
1775 Dygraph.prototype.idxToRow_ = function(idx) {
1776 if (idx < 0) return -1;
1777
1778 for (var i in this.layout_.datasets) {
1779 if (idx < this.layout_.datasets[i].length) {
1780 return this.boundaryIds_[0][0]+idx;
1781 }
1782 idx -= this.layout_.datasets[i].length;
1783 }
1784 return -1;
1785 };
1786
1787 /**
1788 * @private
1789 * @param { Number } x The number to consider.
1790 * @return { Boolean } Whether the number is zero or NaN.
1791 */
1792 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
1793 Dygraph.isOK = function(x) {
1794 return x && !isNaN(x);
1795 };
1796
1797 /**
1798 * @private
1799 * Generates HTML for the legend which is displayed when hovering over the
1800 * chart. If no selected points are specified, a default legend is returned
1801 * (this may just be the empty string).
1802 * @param { Number } [x] The x-value of the selected points.
1803 * @param { [Object] } [sel_points] List of selected points for the given
1804 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1805 */
1806 Dygraph.prototype.generateLegendHTML_ = function(x, sel_points) {
1807 // If no points are selected, we display a default legend. Traditionally,
1808 // this has been blank. But a better default would be a conventional legend,
1809 // which provides essential information for a non-interactive chart.
1810 if (typeof(x) === 'undefined') {
1811 if (this.attr_('legend') != 'always') return '';
1812
1813 var sepLines = this.attr_('labelsSeparateLines');
1814 var labels = this.attr_('labels');
1815 var html = '';
1816 for (var i = 1; i < labels.length; i++) {
1817 if (!this.visibility()[i - 1]) continue;
1818 var c = this.plotter_.colors[labels[i]];
1819 if (html != '') html += (sepLines ? '<br/>' : ' ');
1820 html += "<b><span style='color: " + c + ";'>&mdash;" + labels[i] +
1821 "</span></b>";
1822 }
1823 return html;
1824 }
1825
1826 var html = this.attr_('xValueFormatter')(x) + ":";
1827
1828 var fmtFunc = this.attr_('yValueFormatter');
1829 var showZeros = this.attr_("labelsShowZeroValues");
1830 var sepLines = this.attr_("labelsSeparateLines");
1831 for (var i = 0; i < this.selPoints_.length; i++) {
1832 var pt = this.selPoints_[i];
1833 if (pt.yval == 0 && !showZeros) continue;
1834 if (!Dygraph.isOK(pt.canvasy)) continue;
1835 if (sepLines) html += "<br/>";
1836
1837 var c = this.plotter_.colors[pt.name];
1838 var yval = fmtFunc(pt.yval, this);
1839 // TODO(danvk): use a template string here and make it an attribute.
1840 html += " <b><span style='color: " + c + ";'>"
1841 + pt.name + "</span></b>:"
1842 + yval;
1843 }
1844 return html;
1845 };
1846
1847 /**
1848 * @private
1849 * Displays information about the selected points in the legend. If there is no
1850 * selection, the legend will be cleared.
1851 * @param { Number } [x] The x-value of the selected points.
1852 * @param { [Object] } [sel_points] List of selected points for the given
1853 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1854 */
1855 Dygraph.prototype.setLegendHTML_ = function(x, sel_points) {
1856 var html = this.generateLegendHTML_(x, sel_points);
1857 var labelsDiv = this.attr_("labelsDiv");
1858 if (labelsDiv !== null) {
1859 labelsDiv.innerHTML = html;
1860 } else {
1861 if (typeof(this.shown_legend_error_) == 'undefined') {
1862 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1863 this.shown_legend_error_ = true;
1864 }
1865 }
1866 };
1867
1868 /**
1869 * Draw dots over the selectied points in the data series. This function
1870 * takes care of cleanup of previously-drawn dots.
1871 * @private
1872 */
1873 Dygraph.prototype.updateSelection_ = function() {
1874 // Clear the previously drawn vertical, if there is one
1875 var ctx = this.canvas_ctx_;
1876 if (this.previousVerticalX_ >= 0) {
1877 // Determine the maximum highlight circle size.
1878 var maxCircleSize = 0;
1879 var labels = this.attr_('labels');
1880 for (var i = 1; i < labels.length; i++) {
1881 var r = this.attr_('highlightCircleSize', labels[i]);
1882 if (r > maxCircleSize) maxCircleSize = r;
1883 }
1884 var px = this.previousVerticalX_;
1885 ctx.clearRect(px - maxCircleSize - 1, 0,
1886 2 * maxCircleSize + 2, this.height_);
1887 }
1888
1889 if (this.selPoints_.length > 0) {
1890 // Set the status message to indicate the selected point(s)
1891 if (this.attr_('showLabelsOnHighlight')) {
1892 this.setLegendHTML_(this.lastx_, this.selPoints_);
1893 }
1894
1895 // Draw colored circles over the center of each selected point
1896 var canvasx = this.selPoints_[0].canvasx;
1897 ctx.save();
1898 for (var i = 0; i < this.selPoints_.length; i++) {
1899 var pt = this.selPoints_[i];
1900 if (!Dygraph.isOK(pt.canvasy)) continue;
1901
1902 var circleSize = this.attr_('highlightCircleSize', pt.name);
1903 ctx.beginPath();
1904 ctx.fillStyle = this.plotter_.colors[pt.name];
1905 ctx.arc(canvasx, pt.canvasy, circleSize, 0, 2 * Math.PI, false);
1906 ctx.fill();
1907 }
1908 ctx.restore();
1909
1910 this.previousVerticalX_ = canvasx;
1911 }
1912 };
1913
1914 /**
1915 * Manually set the selected points and display information about them in the
1916 * legend. The selection can be cleared using clearSelection() and queried
1917 * using getSelection().
1918 * @param { Integer } row number that should be highlighted (i.e. appear with
1919 * hover dots on the chart). Set to false to clear any selection.
1920 */
1921 Dygraph.prototype.setSelection = function(row) {
1922 // Extract the points we've selected
1923 this.selPoints_ = [];
1924 var pos = 0;
1925
1926 if (row !== false) {
1927 row = row-this.boundaryIds_[0][0];
1928 }
1929
1930 if (row !== false && row >= 0) {
1931 for (var i in this.layout_.datasets) {
1932 if (row < this.layout_.datasets[i].length) {
1933 var point = this.layout_.points[pos+row];
1934
1935 if (this.attr_("stackedGraph")) {
1936 point = this.layout_.unstackPointAtIndex(pos+row);
1937 }
1938
1939 this.selPoints_.push(point);
1940 }
1941 pos += this.layout_.datasets[i].length;
1942 }
1943 }
1944
1945 if (this.selPoints_.length) {
1946 this.lastx_ = this.selPoints_[0].xval;
1947 this.updateSelection_();
1948 } else {
1949 this.clearSelection();
1950 }
1951
1952 };
1953
1954 /**
1955 * The mouse has left the canvas. Clear out whatever artifacts remain
1956 * @param {Object} event the mouseout event from the browser.
1957 * @private
1958 */
1959 Dygraph.prototype.mouseOut_ = function(event) {
1960 if (this.attr_("unhighlightCallback")) {
1961 this.attr_("unhighlightCallback")(event);
1962 }
1963
1964 if (this.attr_("hideOverlayOnMouseOut")) {
1965 this.clearSelection();
1966 }
1967 };
1968
1969 /**
1970 * Clears the current selection (i.e. points that were highlighted by moving
1971 * the mouse over the chart).
1972 */
1973 Dygraph.prototype.clearSelection = function() {
1974 // Get rid of the overlay data
1975 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
1976 this.setLegendHTML_();
1977 this.selPoints_ = [];
1978 this.lastx_ = -1;
1979 }
1980
1981 /**
1982 * Returns the number of the currently selected row. To get data for this row,
1983 * you can use the getValue method.
1984 * @return { Integer } row number, or -1 if nothing is selected
1985 */
1986 Dygraph.prototype.getSelection = function() {
1987 if (!this.selPoints_ || this.selPoints_.length < 1) {
1988 return -1;
1989 }
1990
1991 for (var row=0; row<this.layout_.points.length; row++ ) {
1992 if (this.layout_.points[row].x == this.selPoints_[0].x) {
1993 return row + this.boundaryIds_[0][0];
1994 }
1995 }
1996 return -1;
1997 };
1998
1999 /**
2000 * Number formatting function which mimicks the behavior of %g in printf, i.e.
2001 * either exponential or fixed format (without trailing 0s) is used depending on
2002 * the length of the generated string. The advantage of this format is that
2003 * there is a predictable upper bound on the resulting string length,
2004 * significant figures are not dropped, and normal numbers are not displayed in
2005 * exponential notation.
2006 *
2007 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
2008 * It creates strings which are too long for absolute values between 10^-4 and
2009 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
2010 * output examples.
2011 *
2012 * @param {Number} x The number to format
2013 * @param {Number} opt_precision The precision to use, default 2.
2014 * @return {String} A string formatted like %g in printf. The max generated
2015 * string length should be precision + 6 (e.g 1.123e+300).
2016 */
2017 Dygraph.floatFormat = function(x, opt_precision) {
2018 // Avoid invalid precision values; [1, 21] is the valid range.
2019 var p = Math.min(Math.max(1, opt_precision || 2), 21);
2020
2021 // This is deceptively simple. The actual algorithm comes from:
2022 //
2023 // Max allowed length = p + 4
2024 // where 4 comes from 'e+n' and '.'.
2025 //
2026 // Length of fixed format = 2 + y + p
2027 // where 2 comes from '0.' and y = # of leading zeroes.
2028 //
2029 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
2030 // 1.0e-3.
2031 //
2032 // Since the behavior of toPrecision() is identical for larger numbers, we
2033 // don't have to worry about the other bound.
2034 //
2035 // Finally, the argument for toExponential() is the number of trailing digits,
2036 // so we take off 1 for the value before the '.'.
2037 return (Math.abs(x) < 1.0e-3 && x != 0.0) ?
2038 x.toExponential(p - 1) : x.toPrecision(p);
2039 };
2040
2041 /**
2042 * @private
2043 * Return a string version of a number. This respects the digitsAfterDecimal
2044 * and maxNumberWidth options.
2045 * @param {Number} x The number to be formatted
2046 * @param {Dygraph} g The dygraph object
2047 */
2048 Dygraph.numberFormatter = function(x, g) {
2049 var sigFigs = g.attr_('sigFigs');
2050
2051 if (sigFigs !== null) {
2052 // User has opted for a fixed number of significant figures.
2053 return Dygraph.floatFormat(x, sigFigs);
2054 }
2055
2056 var digits = g.attr_('digitsAfterDecimal');
2057 var maxNumberWidth = g.attr_('maxNumberWidth');
2058
2059 // switch to scientific notation if we underflow or overflow fixed display.
2060 if (x !== 0.0 &&
2061 (Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
2062 Math.abs(x) < Math.pow(10, -digits))) {
2063 return x.toExponential(digits);
2064 } else {
2065 return '' + Dygraph.round_(x, digits);
2066 }
2067 };
2068
2069 /**
2070 * @private
2071 * Converts '9' to '09' (useful for dates)
2072 */
2073 Dygraph.zeropad = function(x) {
2074 if (x < 10) return "0" + x; else return "" + x;
2075 };
2076
2077 /**
2078 * Return a string version of the hours, minutes and seconds portion of a date.
2079 * @param {Number} date The JavaScript date (ms since epoch)
2080 * @return {String} A time of the form "HH:MM:SS"
2081 * @private
2082 */
2083 Dygraph.hmsString_ = function(date) {
2084 var zeropad = Dygraph.zeropad;
2085 var d = new Date(date);
2086 if (d.getSeconds()) {
2087 return zeropad(d.getHours()) + ":" +
2088 zeropad(d.getMinutes()) + ":" +
2089 zeropad(d.getSeconds());
2090 } else {
2091 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
2092 }
2093 };
2094
2095 /**
2096 * Convert a JS date to a string appropriate to display on an axis that
2097 * is displaying values at the stated granularity.
2098 * @param {Date} date The date to format
2099 * @param {Number} granularity One of the Dygraph granularity constants
2100 * @return {String} The formatted date
2101 * @private
2102 */
2103 Dygraph.dateAxisFormatter = function(date, granularity) {
2104 if (granularity >= Dygraph.DECADAL) {
2105 return date.strftime('%Y');
2106 } else if (granularity >= Dygraph.MONTHLY) {
2107 return date.strftime('%b %y');
2108 } else {
2109 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
2110 if (frac == 0 || granularity >= Dygraph.DAILY) {
2111 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
2112 } else {
2113 return Dygraph.hmsString_(date.getTime());
2114 }
2115 }
2116 };
2117
2118 /**
2119 * Convert a JS date (millis since epoch) to YYYY/MM/DD
2120 * @param {Number} date The JavaScript date (ms since epoch)
2121 * @return {String} A date of the form "YYYY/MM/DD"
2122 * @private
2123 */
2124 Dygraph.dateString_ = function(date) {
2125 var zeropad = Dygraph.zeropad;
2126 var d = new Date(date);
2127
2128 // Get the year:
2129 var year = "" + d.getFullYear();
2130 // Get a 0 padded month string
2131 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
2132 // Get a 0 padded day string
2133 var day = zeropad(d.getDate());
2134
2135 var ret = "";
2136 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
2137 if (frac) ret = " " + Dygraph.hmsString_(date);
2138
2139 return year + "/" + month + "/" + day + ret;
2140 };
2141
2142 /**
2143 * Round a number to the specified number of digits past the decimal point.
2144 * @param {Number} num The number to round
2145 * @param {Number} places The number of decimals to which to round
2146 * @return {Number} The rounded number
2147 * @private
2148 */
2149 Dygraph.round_ = function(num, places) {
2150 var shift = Math.pow(10, places);
2151 return Math.round(num * shift)/shift;
2152 };
2153
2154 /**
2155 * Fires when there's data available to be graphed.
2156 * @param {String} data Raw CSV data to be plotted
2157 * @private
2158 */
2159 Dygraph.prototype.loadedEvent_ = function(data) {
2160 this.rawData_ = this.parseCSV_(data);
2161 this.predraw_();
2162 };
2163
2164 Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
2165 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
2166 Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
2167
2168 /**
2169 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2170 * @private
2171 */
2172 Dygraph.prototype.addXTicks_ = function() {
2173 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2174 var range;
2175 if (this.dateWindow_) {
2176 range = [this.dateWindow_[0], this.dateWindow_[1]];
2177 } else {
2178 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
2179 }
2180
2181 var xTicks = this.attr_('xTicker')(range[0], range[1], this);
2182 this.layout_.setXTicks(xTicks);
2183 };
2184
2185 // Time granularity enumeration
2186 Dygraph.SECONDLY = 0;
2187 Dygraph.TWO_SECONDLY = 1;
2188 Dygraph.FIVE_SECONDLY = 2;
2189 Dygraph.TEN_SECONDLY = 3;
2190 Dygraph.THIRTY_SECONDLY = 4;
2191 Dygraph.MINUTELY = 5;
2192 Dygraph.TWO_MINUTELY = 6;
2193 Dygraph.FIVE_MINUTELY = 7;
2194 Dygraph.TEN_MINUTELY = 8;
2195 Dygraph.THIRTY_MINUTELY = 9;
2196 Dygraph.HOURLY = 10;
2197 Dygraph.TWO_HOURLY = 11;
2198 Dygraph.SIX_HOURLY = 12;
2199 Dygraph.DAILY = 13;
2200 Dygraph.WEEKLY = 14;
2201 Dygraph.MONTHLY = 15;
2202 Dygraph.QUARTERLY = 16;
2203 Dygraph.BIANNUAL = 17;
2204 Dygraph.ANNUAL = 18;
2205 Dygraph.DECADAL = 19;
2206 Dygraph.CENTENNIAL = 20;
2207 Dygraph.NUM_GRANULARITIES = 21;
2208
2209 Dygraph.SHORT_SPACINGS = [];
2210 Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
2211 Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
2212 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
2213 Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
2214 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
2215 Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
2216 Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
2217 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
2218 Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
2219 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
2220 Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
2221 Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
2222 Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
2223 Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
2224 Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
2225
2226 /**
2227 * @private
2228 * If we used this time granularity, how many ticks would there be?
2229 * This is only an approximation, but it's generally good enough.
2230 */
2231 Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
2232 if (granularity < Dygraph.MONTHLY) {
2233 // Generate one tick mark for every fixed interval of time.
2234 var spacing = Dygraph.SHORT_SPACINGS[granularity];
2235 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
2236 } else {
2237 var year_mod = 1; // e.g. to only print one point every 10 years.
2238 var num_months = 12;
2239 if (granularity == Dygraph.QUARTERLY) num_months = 3;
2240 if (granularity == Dygraph.BIANNUAL) num_months = 2;
2241 if (granularity == Dygraph.ANNUAL) num_months = 1;
2242 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
2243 if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
2244
2245 var msInYear = 365.2524 * 24 * 3600 * 1000;
2246 var num_years = 1.0 * (end_time - start_time) / msInYear;
2247 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
2248 }
2249 };
2250
2251 /**
2252 * @private
2253 *
2254 * Construct an x-axis of nicely-formatted times on meaningful boundaries
2255 * (e.g. 'Jan 09' rather than 'Jan 22, 2009').
2256 *
2257 * Returns an array containing {v: millis, label: label} dictionaries.
2258 */
2259 Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
2260 var formatter = this.attr_("xAxisLabelFormatter");
2261 var ticks = [];
2262 if (granularity < Dygraph.MONTHLY) {
2263 // Generate one tick mark for every fixed interval of time.
2264 var spacing = Dygraph.SHORT_SPACINGS[granularity];
2265 var format = '%d%b'; // e.g. "1Jan"
2266
2267 // Find a time less than start_time which occurs on a "nice" time boundary
2268 // for this granularity.
2269 var g = spacing / 1000;
2270 var d = new Date(start_time);
2271 if (g <= 60) { // seconds
2272 var x = d.getSeconds(); d.setSeconds(x - x % g);
2273 } else {
2274 d.setSeconds(0);
2275 g /= 60;
2276 if (g <= 60) { // minutes
2277 var x = d.getMinutes(); d.setMinutes(x - x % g);
2278 } else {
2279 d.setMinutes(0);
2280 g /= 60;
2281
2282 if (g <= 24) { // days
2283 var x = d.getHours(); d.setHours(x - x % g);
2284 } else {
2285 d.setHours(0);
2286 g /= 24;
2287
2288 if (g == 7) { // one week
2289 d.setDate(d.getDate() - d.getDay());
2290 }
2291 }
2292 }
2293 }
2294 start_time = d.getTime();
2295
2296 for (var t = start_time; t <= end_time; t += spacing) {
2297 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
2298 }
2299 } else {
2300 // Display a tick mark on the first of a set of months of each year.
2301 // Years get a tick mark iff y % year_mod == 0. This is useful for
2302 // displaying a tick mark once every 10 years, say, on long time scales.
2303 var months;
2304 var year_mod = 1; // e.g. to only print one point every 10 years.
2305
2306 if (granularity == Dygraph.MONTHLY) {
2307 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
2308 } else if (granularity == Dygraph.QUARTERLY) {
2309 months = [ 0, 3, 6, 9 ];
2310 } else if (granularity == Dygraph.BIANNUAL) {
2311 months = [ 0, 6 ];
2312 } else if (granularity == Dygraph.ANNUAL) {
2313 months = [ 0 ];
2314 } else if (granularity == Dygraph.DECADAL) {
2315 months = [ 0 ];
2316 year_mod = 10;
2317 } else if (granularity == Dygraph.CENTENNIAL) {
2318 months = [ 0 ];
2319 year_mod = 100;
2320 } else {
2321 this.warn("Span of dates is too long");
2322 }
2323
2324 var start_year = new Date(start_time).getFullYear();
2325 var end_year = new Date(end_time).getFullYear();
2326 var zeropad = Dygraph.zeropad;
2327 for (var i = start_year; i <= end_year; i++) {
2328 if (i % year_mod != 0) continue;
2329 for (var j = 0; j < months.length; j++) {
2330 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
2331 var t = Dygraph.dateStrToMillis(date_str);
2332 if (t < start_time || t > end_time) continue;
2333 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
2334 }
2335 }
2336 }
2337
2338 return ticks;
2339 };
2340
2341
2342 /**
2343 * Add ticks to the x-axis based on a date range.
2344 * @param {Number} startDate Start of the date window (millis since epoch)
2345 * @param {Number} endDate End of the date window (millis since epoch)
2346 * @param {Dygraph} self The dygraph object
2347 * @return { [Object] } Array of {label, value} tuples.
2348 * @public
2349 */
2350 Dygraph.dateTicker = function(startDate, endDate, self) {
2351 // TODO(danvk): why does this take 'self' as a param?
2352 var chosen = -1;
2353 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
2354 var num_ticks = self.NumXTicks(startDate, endDate, i);
2355 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
2356 chosen = i;
2357 break;
2358 }
2359 }
2360
2361 if (chosen >= 0) {
2362 return self.GetXAxis(startDate, endDate, chosen);
2363 } else {
2364 // TODO(danvk): signal error.
2365 }
2366 };
2367
2368 /**
2369 * @private
2370 * This is a list of human-friendly values at which to show tick marks on a log
2371 * scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
2372 * ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
2373 * NOTE: this assumes that Dygraph.LOG_SCALE = 10.
2374 */
2375 Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
2376 var vals = [];
2377 for (var power = -39; power <= 39; power++) {
2378 var range = Math.pow(10, power);
2379 for (var mult = 1; mult <= 9; mult++) {
2380 var val = range * mult;
2381 vals.push(val);
2382 }
2383 }
2384 return vals;
2385 }();
2386
2387 /**
2388 * @private
2389 * Implementation of binary search over an array.
2390 * Currently does not work when val is outside the range of arry's values.
2391 * @param { Integer } val the value to search for
2392 * @param { Integer[] } arry is the value over which to search
2393 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
2394 * If abs < 0, find the highest entry less than val.
2395 * if abs == 0, find the entry that equals val.
2396 * @param { Integer } [low] The first index in arry to consider (optional)
2397 * @param { Integer } [high] The last index in arry to consider (optional)
2398 */
2399 Dygraph.binarySearch = function(val, arry, abs, low, high) {
2400 if (low == null || high == null) {
2401 low = 0;
2402 high = arry.length - 1;
2403 }
2404 if (low > high) {
2405 return -1;
2406 }
2407 if (abs == null) {
2408 abs = 0;
2409 }
2410 var validIndex = function(idx) {
2411 return idx >= 0 && idx < arry.length;
2412 }
2413 var mid = parseInt((low + high) / 2);
2414 var element = arry[mid];
2415 if (element == val) {
2416 return mid;
2417 }
2418 if (element > val) {
2419 if (abs > 0) {
2420 // Accept if element > val, but also if prior element < val.
2421 var idx = mid - 1;
2422 if (validIndex(idx) && arry[idx] < val) {
2423 return mid;
2424 }
2425 }
2426 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
2427 }
2428 if (element < val) {
2429 if (abs < 0) {
2430 // Accept if element < val, but also if prior element > val.
2431 var idx = mid + 1;
2432 if (validIndex(idx) && arry[idx] > val) {
2433 return mid;
2434 }
2435 }
2436 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
2437 }
2438 };
2439
2440 // TODO(konigsberg): Update comment.
2441 /**
2442 * Add ticks when the x axis has numbers on it (instead of dates)
2443 *
2444 * @param {Number} minV minimum value
2445 * @param {Number} maxV maximum value
2446 * @param self
2447 * @param {function} attribute accessor function.
2448 * @return {[Object]} Array of {label, value} tuples.
2449 */
2450 Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
2451 var attr = function(k) {
2452 if (axis_props && axis_props.hasOwnProperty(k)) return axis_props[k];
2453 return self.attr_(k);
2454 };
2455
2456 var ticks = [];
2457 if (vals) {
2458 for (var i = 0; i < vals.length; i++) {
2459 ticks.push({v: vals[i]});
2460 }
2461 } else {
2462 if (axis_props && attr("logscale")) {
2463 var pixelsPerTick = attr('pixelsPerYLabel');
2464 // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
2465 var nTicks = Math.floor(self.height_ / pixelsPerTick);
2466 var minIdx = Dygraph.binarySearch(minV, Dygraph.PREFERRED_LOG_TICK_VALUES, 1);
2467 var maxIdx = Dygraph.binarySearch(maxV, Dygraph.PREFERRED_LOG_TICK_VALUES, -1);
2468 if (minIdx == -1) {
2469 minIdx = 0;
2470 }
2471 if (maxIdx == -1) {
2472 maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1;
2473 }
2474 // Count the number of tick values would appear, if we can get at least
2475 // nTicks / 4 accept them.
2476 var lastDisplayed = null;
2477 if (maxIdx - minIdx >= nTicks / 4) {
2478 var axisId = axis_props.yAxisId;
2479 for (var idx = maxIdx; idx >= minIdx; idx--) {
2480 var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx];
2481 var domCoord = axis_props.g.toDomYCoord(tickValue, axisId);
2482 var tick = { v: tickValue };
2483 if (lastDisplayed == null) {
2484 lastDisplayed = {
2485 tickValue : tickValue,
2486 domCoord : domCoord
2487 };
2488 } else {
2489 if (domCoord - lastDisplayed.domCoord >= pixelsPerTick) {
2490 lastDisplayed = {
2491 tickValue : tickValue,
2492 domCoord : domCoord
2493 };
2494 } else {
2495 tick.label = "";
2496 }
2497 }
2498 ticks.push(tick);
2499 }
2500 // Since we went in backwards order.
2501 ticks.reverse();
2502 }
2503 }
2504
2505 // ticks.length won't be 0 if the log scale function finds values to insert.
2506 if (ticks.length == 0) {
2507 // Basic idea:
2508 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
2509 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
2510 // The first spacing greater than pixelsPerYLabel is what we use.
2511 // TODO(danvk): version that works on a log scale.
2512 if (attr("labelsKMG2")) {
2513 var mults = [1, 2, 4, 8];
2514 } else {
2515 var mults = [1, 2, 5];
2516 }
2517 var scale, low_val, high_val, nTicks;
2518 // TODO(danvk): make it possible to set this for x- and y-axes independently.
2519 var pixelsPerTick = attr('pixelsPerYLabel');
2520 for (var i = -10; i < 50; i++) {
2521 if (attr("labelsKMG2")) {
2522 var base_scale = Math.pow(16, i);
2523 } else {
2524 var base_scale = Math.pow(10, i);
2525 }
2526 for (var j = 0; j < mults.length; j++) {
2527 scale = base_scale * mults[j];
2528 low_val = Math.floor(minV / scale) * scale;
2529 high_val = Math.ceil(maxV / scale) * scale;
2530 nTicks = Math.abs(high_val - low_val) / scale;
2531 var spacing = self.height_ / nTicks;
2532 // wish I could break out of both loops at once...
2533 if (spacing > pixelsPerTick) break;
2534 }
2535 if (spacing > pixelsPerTick) break;
2536 }
2537
2538 // Construct the set of ticks.
2539 // Allow reverse y-axis if it's explicitly requested.
2540 if (low_val > high_val) scale *= -1;
2541 for (var i = 0; i < nTicks; i++) {
2542 var tickV = low_val + i * scale;
2543 ticks.push( {v: tickV} );
2544 }
2545 }
2546 }
2547
2548 // Add formatted labels to the ticks.
2549 var k;
2550 var k_labels = [];
2551 if (attr("labelsKMB")) {
2552 k = 1000;
2553 k_labels = [ "K", "M", "B", "T" ];
2554 }
2555 if (attr("labelsKMG2")) {
2556 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
2557 k = 1024;
2558 k_labels = [ "k", "M", "G", "T" ];
2559 }
2560 var formatter = attr('yAxisLabelFormatter') ?
2561 attr('yAxisLabelFormatter') : attr('yValueFormatter');
2562
2563 // Add labels to the ticks.
2564 for (var i = 0; i < ticks.length; i++) {
2565 if (ticks[i].label !== undefined) continue; // Use current label.
2566 var tickV = ticks[i].v;
2567 var absTickV = Math.abs(tickV);
2568 var label = formatter(tickV, self);
2569 if (k_labels.length > 0) {
2570 // Round up to an appropriate unit.
2571 var n = k*k*k*k;
2572 for (var j = 3; j >= 0; j--, n /= k) {
2573 if (absTickV >= n) {
2574 label = Dygraph.round_(tickV / n, attr('digitsAfterDecimal')) + k_labels[j];
2575 break;
2576 }
2577 }
2578 }
2579 ticks[i].label = label;
2580 }
2581
2582 return ticks;
2583 };
2584
2585 /**
2586 * @private
2587 * Computes the range of the data series (including confidence intervals).
2588 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2589 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2590 * @return [low, high]
2591 */
2592 Dygraph.prototype.extremeValues_ = function(series) {
2593 var minY = null, maxY = null;
2594
2595 var bars = this.attr_("errorBars") || this.attr_("customBars");
2596 if (bars) {
2597 // With custom bars, maxY is the max of the high values.
2598 for (var j = 0; j < series.length; j++) {
2599 var y = series[j][1][0];
2600 if (!y) continue;
2601 var low = y - series[j][1][1];
2602 var high = y + series[j][1][2];
2603 if (low > y) low = y; // this can happen with custom bars,
2604 if (high < y) high = y; // e.g. in tests/custom-bars.html
2605 if (maxY == null || high > maxY) {
2606 maxY = high;
2607 }
2608 if (minY == null || low < minY) {
2609 minY = low;
2610 }
2611 }
2612 } else {
2613 for (var j = 0; j < series.length; j++) {
2614 var y = series[j][1];
2615 if (y === null || isNaN(y)) continue;
2616 if (maxY == null || y > maxY) {
2617 maxY = y;
2618 }
2619 if (minY == null || y < minY) {
2620 minY = y;
2621 }
2622 }
2623 }
2624
2625 return [minY, maxY];
2626 };
2627
2628 /**
2629 * @private
2630 * This function is called once when the chart's data is changed or the options
2631 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2632 * idea is that values derived from the chart's data can be computed here,
2633 * rather than every time the chart is drawn. This includes things like the
2634 * number of axes, rolling averages, etc.
2635 */
2636 Dygraph.prototype.predraw_ = function() {
2637 // TODO(danvk): move more computations out of drawGraph_ and into here.
2638 this.computeYAxes_();
2639
2640 // Create a new plotter.
2641 if (this.plotter_) this.plotter_.clear();
2642 this.plotter_ = new DygraphCanvasRenderer(this,
2643 this.hidden_,
2644 this.hidden_ctx_,
2645 this.layout_);
2646
2647 // The roller sits in the bottom left corner of the chart. We don't know where
2648 // this will be until the options are available, so it's positioned here.
2649 this.createRollInterface_();
2650
2651 // Same thing applies for the labelsDiv. It's right edge should be flush with
2652 // the right edge of the charting area (which may not be the same as the right
2653 // edge of the div, if we have two y-axes.
2654 this.positionLabelsDiv_();
2655
2656 // If the data or options have changed, then we'd better redraw.
2657 this.drawGraph_();
2658 };
2659
2660 /**
2661 * Update the graph with new data. This method is called when the viewing area
2662 * has changed. If the underlying data or options have changed, predraw_ will
2663 * be called before drawGraph_ is called.
2664 * @private
2665 */
2666 Dygraph.prototype.drawGraph_ = function() {
2667 var data = this.rawData_;
2668
2669 // This is used to set the second parameter to drawCallback, below.
2670 var is_initial_draw = this.is_initial_draw_;
2671 this.is_initial_draw_ = false;
2672
2673 var minY = null, maxY = null;
2674 this.layout_.removeAllDatasets();
2675 this.setColors_();
2676 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
2677
2678 // Loop over the fields (series). Go from the last to the first,
2679 // because if they're stacked that's how we accumulate the values.
2680
2681 var cumulative_y = []; // For stacked series.
2682 var datasets = [];
2683
2684 var extremes = {}; // series name -> [low, high]
2685
2686 // Loop over all fields and create datasets
2687 for (var i = data[0].length - 1; i >= 1; i--) {
2688 if (!this.visibility()[i - 1]) continue;
2689
2690 var seriesName = this.attr_("labels")[i];
2691 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
2692 var logScale = this.attr_('logscale', i);
2693
2694 var series = [];
2695 for (var j = 0; j < data.length; j++) {
2696 var date = data[j][0];
2697 var point = data[j][i];
2698 if (logScale) {
2699 // On the log scale, points less than zero do not exist.
2700 // This will create a gap in the chart. Note that this ignores
2701 // connectSeparatedPoints.
2702 if (point <= 0) {
2703 point = null;
2704 }
2705 series.push([date, point]);
2706 } else {
2707 if (point != null || !connectSeparatedPoints) {
2708 series.push([date, point]);
2709 }
2710 }
2711 }
2712
2713 // TODO(danvk): move this into predraw_. It's insane to do it here.
2714 series = this.rollingAverage(series, this.rollPeriod_);
2715
2716 // Prune down to the desired range, if necessary (for zooming)
2717 // Because there can be lines going to points outside of the visible area,
2718 // we actually prune to visible points, plus one on either side.
2719 var bars = this.attr_("errorBars") || this.attr_("customBars");
2720 if (this.dateWindow_) {
2721 var low = this.dateWindow_[0];
2722 var high= this.dateWindow_[1];
2723 var pruned = [];
2724 // TODO(danvk): do binary search instead of linear search.
2725 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2726 var firstIdx = null, lastIdx = null;
2727 for (var k = 0; k < series.length; k++) {
2728 if (series[k][0] >= low && firstIdx === null) {
2729 firstIdx = k;
2730 }
2731 if (series[k][0] <= high) {
2732 lastIdx = k;
2733 }
2734 }
2735 if (firstIdx === null) firstIdx = 0;
2736 if (firstIdx > 0) firstIdx--;
2737 if (lastIdx === null) lastIdx = series.length - 1;
2738 if (lastIdx < series.length - 1) lastIdx++;
2739 this.boundaryIds_[i-1] = [firstIdx, lastIdx];
2740 for (var k = firstIdx; k <= lastIdx; k++) {
2741 pruned.push(series[k]);
2742 }
2743 series = pruned;
2744 } else {
2745 this.boundaryIds_[i-1] = [0, series.length-1];
2746 }
2747
2748 var seriesExtremes = this.extremeValues_(series);
2749
2750 if (bars) {
2751 for (var j=0; j<series.length; j++) {
2752 val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]];
2753 series[j] = val;
2754 }
2755 } else if (this.attr_("stackedGraph")) {
2756 var l = series.length;
2757 var actual_y;
2758 for (var j = 0; j < l; j++) {
2759 // If one data set has a NaN, let all subsequent stacked
2760 // sets inherit the NaN -- only start at 0 for the first set.
2761 var x = series[j][0];
2762 if (cumulative_y[x] === undefined) {
2763 cumulative_y[x] = 0;
2764 }
2765
2766 actual_y = series[j][1];
2767 cumulative_y[x] += actual_y;
2768
2769 series[j] = [x, cumulative_y[x]]
2770
2771 if (cumulative_y[x] > seriesExtremes[1]) {
2772 seriesExtremes[1] = cumulative_y[x];
2773 }
2774 if (cumulative_y[x] < seriesExtremes[0]) {
2775 seriesExtremes[0] = cumulative_y[x];
2776 }
2777 }
2778 }
2779 extremes[seriesName] = seriesExtremes;
2780
2781 datasets[i] = series;
2782 }
2783
2784 for (var i = 1; i < datasets.length; i++) {
2785 if (!this.visibility()[i - 1]) continue;
2786 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
2787 }
2788
2789 this.computeYAxisRanges_(extremes);
2790 this.layout_.setYAxes(this.axes_);
2791
2792 this.addXTicks_();
2793
2794 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2795 var tmp_zoomed_x = this.zoomed_x_;
2796 // Tell PlotKit to use this new data and render itself
2797 this.layout_.setDateWindow(this.dateWindow_);
2798 this.zoomed_x_ = tmp_zoomed_x;
2799 this.layout_.evaluateWithError();
2800 this.plotter_.clear();
2801 this.plotter_.render();
2802 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2803 this.canvas_.height);
2804
2805 if (is_initial_draw) {
2806 // Generate a static legend before any particular point is selected.
2807 this.setLegendHTML_();
2808 } else {
2809 if (typeof(this.selPoints_) !== 'undefined' && this.selPoints_.length) {
2810 // We should select the point nearest the page x/y here, but it's easier
2811 // to just clear the selection. This prevents erroneous hover dots from
2812 // being displayed.
2813 this.clearSelection();
2814 } else {
2815 this.clearSelection();
2816 }
2817 }
2818
2819 if (this.attr_("drawCallback") !== null) {
2820 this.attr_("drawCallback")(this, is_initial_draw);
2821 }
2822 };
2823
2824 /**
2825 * @private
2826 * Determine properties of the y-axes which are independent of the data
2827 * currently being displayed. This includes things like the number of axes and
2828 * the style of the axes. It does not include the range of each axis and its
2829 * tick marks.
2830 * This fills in this.axes_ and this.seriesToAxisMap_.
2831 * axes_ = [ { options } ]
2832 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2833 * indices are into the axes_ array.
2834 */
2835 Dygraph.prototype.computeYAxes_ = function() {
2836 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
2837 this.seriesToAxisMap_ = {};
2838
2839 // Get a list of series names.
2840 var labels = this.attr_("labels");
2841 var series = {};
2842 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
2843
2844 // all options which could be applied per-axis:
2845 var axisOptions = [
2846 'includeZero',
2847 'valueRange',
2848 'labelsKMB',
2849 'labelsKMG2',
2850 'pixelsPerYLabel',
2851 'yAxisLabelWidth',
2852 'axisLabelFontSize',
2853 'axisTickSize',
2854 'logscale'
2855 ];
2856
2857 // Copy global axis options over to the first axis.
2858 for (var i = 0; i < axisOptions.length; i++) {
2859 var k = axisOptions[i];
2860 var v = this.attr_(k);
2861 if (v) this.axes_[0][k] = v;
2862 }
2863
2864 // Go through once and add all the axes.
2865 for (var seriesName in series) {
2866 if (!series.hasOwnProperty(seriesName)) continue;
2867 var axis = this.attr_("axis", seriesName);
2868 if (axis == null) {
2869 this.seriesToAxisMap_[seriesName] = 0;
2870 continue;
2871 }
2872 if (typeof(axis) == 'object') {
2873 // Add a new axis, making a copy of its per-axis options.
2874 var opts = {};
2875 Dygraph.update(opts, this.axes_[0]);
2876 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
2877 var yAxisId = this.axes_.length;
2878 opts.yAxisId = yAxisId;
2879 opts.g = this;
2880 Dygraph.update(opts, axis);
2881 this.axes_.push(opts);
2882 this.seriesToAxisMap_[seriesName] = yAxisId;
2883 }
2884 }
2885
2886 // Go through one more time and assign series to an axis defined by another
2887 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2888 for (var seriesName in series) {
2889 if (!series.hasOwnProperty(seriesName)) continue;
2890 var axis = this.attr_("axis", seriesName);
2891 if (typeof(axis) == 'string') {
2892 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
2893 this.error("Series " + seriesName + " wants to share a y-axis with " +
2894 "series " + axis + ", which does not define its own axis.");
2895 return null;
2896 }
2897 var idx = this.seriesToAxisMap_[axis];
2898 this.seriesToAxisMap_[seriesName] = idx;
2899 }
2900 }
2901
2902 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2903 // this last so that hiding the first series doesn't destroy the axis
2904 // properties of the primary axis.
2905 var seriesToAxisFiltered = {};
2906 var vis = this.visibility();
2907 for (var i = 1; i < labels.length; i++) {
2908 var s = labels[i];
2909 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2910 }
2911 this.seriesToAxisMap_ = seriesToAxisFiltered;
2912 };
2913
2914 /**
2915 * Returns the number of y-axes on the chart.
2916 * @return {Number} the number of axes.
2917 */
2918 Dygraph.prototype.numAxes = function() {
2919 var last_axis = 0;
2920 for (var series in this.seriesToAxisMap_) {
2921 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2922 var idx = this.seriesToAxisMap_[series];
2923 if (idx > last_axis) last_axis = idx;
2924 }
2925 return 1 + last_axis;
2926 };
2927
2928 /**
2929 * @private
2930 * Returns axis properties for the given series.
2931 * @param { String } setName The name of the series for which to get axis
2932 * properties, e.g. 'Y1'.
2933 * @return { Object } The axis properties.
2934 */
2935 Dygraph.prototype.axisPropertiesForSeries = function(series) {
2936 // TODO(danvk): handle errors.
2937 return this.axes_[this.seriesToAxisMap_[series]];
2938 };
2939
2940 /**
2941 * @private
2942 * Determine the value range and tick marks for each axis.
2943 * @param {Object} extremes A mapping from seriesName -> [low, high]
2944 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2945 */
2946 Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2947 // Build a map from axis number -> [list of series names]
2948 var seriesForAxis = [];
2949 for (var series in this.seriesToAxisMap_) {
2950 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2951 var idx = this.seriesToAxisMap_[series];
2952 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2953 seriesForAxis[idx].push(series);
2954 }
2955
2956 // Compute extreme values, a span and tick marks for each axis.
2957 for (var i = 0; i < this.axes_.length; i++) {
2958 var axis = this.axes_[i];
2959
2960 if (!seriesForAxis[i]) {
2961 // If no series are defined or visible then use a reasonable default
2962 axis.extremeRange = [0, 1];
2963 } else {
2964 // Calculate the extremes of extremes.
2965 var series = seriesForAxis[i];
2966 var minY = Infinity; // extremes[series[0]][0];
2967 var maxY = -Infinity; // extremes[series[0]][1];
2968 var extremeMinY, extremeMaxY;
2969 for (var j = 0; j < series.length; j++) {
2970 // Only use valid extremes to stop null data series' from corrupting the scale.
2971 extremeMinY = extremes[series[j]][0];
2972 if (extremeMinY != null) {
2973 minY = Math.min(extremeMinY, minY);
2974 }
2975 extremeMaxY = extremes[series[j]][1];
2976 if (extremeMaxY != null) {
2977 maxY = Math.max(extremeMaxY, maxY);
2978 }
2979 }
2980 if (axis.includeZero && minY > 0) minY = 0;
2981
2982 // Ensure we have a valid scale, otherwise defualt to zero for safety.
2983 if (minY == Infinity) minY = 0;
2984 if (maxY == -Infinity) maxY = 0;
2985
2986 // Add some padding and round up to an integer to be human-friendly.
2987 var span = maxY - minY;
2988 // special case: if we have no sense of scale, use +/-10% of the sole value.
2989 if (span == 0) { span = maxY; }
2990
2991 var maxAxisY;
2992 var minAxisY;
2993 if (axis.logscale) {
2994 var maxAxisY = maxY + 0.1 * span;
2995 var minAxisY = minY;
2996 } else {
2997 var maxAxisY = maxY + 0.1 * span;
2998 var minAxisY = minY - 0.1 * span;
2999
3000 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
3001 if (!this.attr_("avoidMinZero")) {
3002 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
3003 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
3004 }
3005
3006 if (this.attr_("includeZero")) {
3007 if (maxY < 0) maxAxisY = 0;
3008 if (minY > 0) minAxisY = 0;
3009 }
3010 }
3011 axis.extremeRange = [minAxisY, maxAxisY];
3012 }
3013 if (axis.valueWindow) {
3014 // This is only set if the user has zoomed on the y-axis. It is never set
3015 // by a user. It takes precedence over axis.valueRange because, if you set
3016 // valueRange, you'd still expect to be able to pan.
3017 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
3018 } else if (axis.valueRange) {
3019 // This is a user-set value range for this axis.
3020 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
3021 } else {
3022 axis.computedValueRange = axis.extremeRange;
3023 }
3024
3025 // Add ticks. By default, all axes inherit the tick positions of the
3026 // primary axis. However, if an axis is specifically marked as having
3027 // independent ticks, then that is permissible as well.
3028 if (i == 0 || axis.independentTicks) {
3029 axis.ticks =
3030 Dygraph.numericTicks(axis.computedValueRange[0],
3031 axis.computedValueRange[1],
3032 this,
3033 axis);
3034 } else {
3035 var p_axis = this.axes_[0];
3036 var p_ticks = p_axis.ticks;
3037 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
3038 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
3039 var tick_values = [];
3040 for (var i = 0; i < p_ticks.length; i++) {
3041 var y_frac = (p_ticks[i].v - p_axis.computedValueRange[0]) / p_scale;
3042 var y_val = axis.computedValueRange[0] + y_frac * scale;
3043 tick_values.push(y_val);
3044 }
3045
3046 axis.ticks =
3047 Dygraph.numericTicks(axis.computedValueRange[0],
3048 axis.computedValueRange[1],
3049 this, axis, tick_values);
3050 }
3051 }
3052 };
3053
3054 /**
3055 * @private
3056 * Calculates the rolling average of a data set.
3057 * If originalData is [label, val], rolls the average of those.
3058 * If originalData is [label, [, it's interpreted as [value, stddev]
3059 * and the roll is returned in the same form, with appropriately reduced
3060 * stddev for each value.
3061 * Note that this is where fractional input (i.e. '5/10') is converted into
3062 * decimal values.
3063 * @param {Array} originalData The data in the appropriate format (see above)
3064 * @param {Number} rollPeriod The number of points over which to average the
3065 * data
3066 */
3067 Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
3068 if (originalData.length < 2)
3069 return originalData;
3070 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
3071 var rollingData = [];
3072 var sigma = this.attr_("sigma");
3073
3074 if (this.fractions_) {
3075 var num = 0;
3076 var den = 0; // numerator/denominator
3077 var mult = 100.0;
3078 for (var i = 0; i < originalData.length; i++) {
3079 num += originalData[i][1][0];
3080 den += originalData[i][1][1];
3081 if (i - rollPeriod >= 0) {
3082 num -= originalData[i - rollPeriod][1][0];
3083 den -= originalData[i - rollPeriod][1][1];
3084 }
3085
3086 var date = originalData[i][0];
3087 var value = den ? num / den : 0.0;
3088 if (this.attr_("errorBars")) {
3089 if (this.wilsonInterval_) {
3090 // For more details on this confidence interval, see:
3091 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
3092 if (den) {
3093 var p = value < 0 ? 0 : value, n = den;
3094 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
3095 var denom = 1 + sigma * sigma / den;
3096 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
3097 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
3098 rollingData[i] = [date,
3099 [p * mult, (p - low) * mult, (high - p) * mult]];
3100 } else {
3101 rollingData[i] = [date, [0, 0, 0]];
3102 }
3103 } else {
3104 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
3105 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
3106 }
3107 } else {
3108 rollingData[i] = [date, mult * value];
3109 }
3110 }
3111 } else if (this.attr_("customBars")) {
3112 var low = 0;
3113 var mid = 0;
3114 var high = 0;
3115 var count = 0;
3116 for (var i = 0; i < originalData.length; i++) {
3117 var data = originalData[i][1];
3118 var y = data[1];
3119 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
3120
3121 if (y != null && !isNaN(y)) {
3122 low += data[0];
3123 mid += y;
3124 high += data[2];
3125 count += 1;
3126 }
3127 if (i - rollPeriod >= 0) {
3128 var prev = originalData[i - rollPeriod];
3129 if (prev[1][1] != null && !isNaN(prev[1][1])) {
3130 low -= prev[1][0];
3131 mid -= prev[1][1];
3132 high -= prev[1][2];
3133 count -= 1;
3134 }
3135 }
3136 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
3137 1.0 * (mid - low) / count,
3138 1.0 * (high - mid) / count ]];
3139 }
3140 } else {
3141 // Calculate the rolling average for the first rollPeriod - 1 points where
3142 // there is not enough data to roll over the full number of points
3143 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
3144 if (!this.attr_("errorBars")){
3145 if (rollPeriod == 1) {
3146 return originalData;
3147 }
3148
3149 for (var i = 0; i < originalData.length; i++) {
3150 var sum = 0;
3151 var num_ok = 0;
3152 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
3153 var y = originalData[j][1];
3154 if (y == null || isNaN(y)) continue;
3155 num_ok++;
3156 sum += originalData[j][1];
3157 }
3158 if (num_ok) {
3159 rollingData[i] = [originalData[i][0], sum / num_ok];
3160 } else {
3161 rollingData[i] = [originalData[i][0], null];
3162 }
3163 }
3164
3165 } else {
3166 for (var i = 0; i < originalData.length; i++) {
3167 var sum = 0;
3168 var variance = 0;
3169 var num_ok = 0;
3170 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
3171 var y = originalData[j][1][0];
3172 if (y == null || isNaN(y)) continue;
3173 num_ok++;
3174 sum += originalData[j][1][0];
3175 variance += Math.pow(originalData[j][1][1], 2);
3176 }
3177 if (num_ok) {
3178 var stddev = Math.sqrt(variance) / num_ok;
3179 rollingData[i] = [originalData[i][0],
3180 [sum / num_ok, sigma * stddev, sigma * stddev]];
3181 } else {
3182 rollingData[i] = [originalData[i][0], [null, null, null]];
3183 }
3184 }
3185 }
3186 }
3187
3188 return rollingData;
3189 };
3190
3191 /**
3192 * @private
3193 * Parses a date, returning the number of milliseconds since epoch. This can be
3194 * passed in as an xValueParser in the Dygraph constructor.
3195 * TODO(danvk): enumerate formats that this understands.
3196 * @param {String} A date in YYYYMMDD format.
3197 * @return {Number} Milliseconds since epoch.
3198 */
3199 Dygraph.dateParser = function(dateStr, self) {
3200 var dateStrSlashed;
3201 var d;
3202 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
3203 dateStrSlashed = dateStr.replace("-", "/", "g");
3204 while (dateStrSlashed.search("-") != -1) {
3205 dateStrSlashed = dateStrSlashed.replace("-", "/");
3206 }
3207 d = Dygraph.dateStrToMillis(dateStrSlashed);
3208 } else if (dateStr.length == 8) { // e.g. '20090712'
3209 // TODO(danvk): remove support for this format. It's confusing.
3210 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
3211 + "/" + dateStr.substr(6,2);
3212 d = Dygraph.dateStrToMillis(dateStrSlashed);
3213 } else {
3214 // Any format that Date.parse will accept, e.g. "2009/07/12" or
3215 // "2009/07/12 12:34:56"
3216 d = Dygraph.dateStrToMillis(dateStr);
3217 }
3218
3219 if (!d || isNaN(d)) {
3220 self.error("Couldn't parse " + dateStr + " as a date");
3221 }
3222 return d;
3223 };
3224
3225 /**
3226 * Detects the type of the str (date or numeric) and sets the various
3227 * formatting attributes in this.attrs_ based on this type.
3228 * @param {String} str An x value.
3229 * @private
3230 */
3231 Dygraph.prototype.detectTypeFromString_ = function(str) {
3232 var isDate = false;
3233 if (str.indexOf('-') > 0 ||
3234 str.indexOf('/') >= 0 ||
3235 isNaN(parseFloat(str))) {
3236 isDate = true;
3237 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
3238 // TODO(danvk): remove support for this format.
3239 isDate = true;
3240 }
3241
3242 if (isDate) {
3243 this.attrs_.xValueFormatter = Dygraph.dateString_;
3244 this.attrs_.xValueParser = Dygraph.dateParser;
3245 this.attrs_.xTicker = Dygraph.dateTicker;
3246 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
3247 } else {
3248 // TODO(danvk): use Dygraph.numberFormatter here?
3249 /** @private (shut up, jsdoc!) */
3250 this.attrs_.xValueFormatter = function(x) { return x; };
3251 /** @private (shut up, jsdoc!) */
3252 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
3253 this.attrs_.xTicker = Dygraph.numericTicks;
3254 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
3255 }
3256 };
3257
3258 /**
3259 * Parses the value as a floating point number. This is like the parseFloat()
3260 * built-in, but with a few differences:
3261 * - the empty string is parsed as null, rather than NaN.
3262 * - if the string cannot be parsed at all, an error is logged.
3263 * If the string can't be parsed, this method returns null.
3264 * @param {String} x The string to be parsed
3265 * @param {Number} opt_line_no The line number from which the string comes.
3266 * @param {String} opt_line The text of the line from which the string comes.
3267 * @private
3268 */
3269
3270 // Parse the x as a float or return null if it's not a number.
3271 Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
3272 var val = parseFloat(x);
3273 if (!isNaN(val)) return val;
3274
3275 // Try to figure out what happeend.
3276 // If the value is the empty string, parse it as null.
3277 if (/^ *$/.test(x)) return null;
3278
3279 // If it was actually "NaN", return it as NaN.
3280 if (/^ *nan *$/i.test(x)) return NaN;
3281
3282 // Looks like a parsing error.
3283 var msg = "Unable to parse '" + x + "' as a number";
3284 if (opt_line !== null && opt_line_no !== null) {
3285 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
3286 }
3287 this.error(msg);
3288
3289 return null;
3290 };
3291
3292 /**
3293 * @private
3294 * Parses a string in a special csv format. We expect a csv file where each
3295 * line is a date point, and the first field in each line is the date string.
3296 * We also expect that all remaining fields represent series.
3297 * if the errorBars attribute is set, then interpret the fields as:
3298 * date, series1, stddev1, series2, stddev2, ...
3299 * @param {[Object]} data See above.
3300 *
3301 * @return [Object] An array with one entry for each row. These entries
3302 * are an array of cells in that row. The first entry is the parsed x-value for
3303 * the row. The second, third, etc. are the y-values. These can take on one of
3304 * three forms, depending on the CSV and constructor parameters:
3305 * 1. numeric value
3306 * 2. [ value, stddev ]
3307 * 3. [ low value, center value, high value ]
3308 */
3309 Dygraph.prototype.parseCSV_ = function(data) {
3310 var ret = [];
3311 var lines = data.split("\n");
3312
3313 // Use the default delimiter or fall back to a tab if that makes sense.
3314 var delim = this.attr_('delimiter');
3315 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
3316 delim = '\t';
3317 }
3318
3319 var start = 0;
3320 if (!('labels' in this.user_attrs_)) {
3321 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3322 start = 1;
3323 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
3324 }
3325 var line_no = 0;
3326
3327 var xParser;
3328 var defaultParserSet = false; // attempt to auto-detect x value type
3329 var expectedCols = this.attr_("labels").length;
3330 var outOfOrder = false;
3331 for (var i = start; i < lines.length; i++) {
3332 var line = lines[i];
3333 line_no = i;
3334 if (line.length == 0) continue; // skip blank lines
3335 if (line[0] == '#') continue; // skip comment lines
3336 var inFields = line.split(delim);
3337 if (inFields.length < 2) continue;
3338
3339 var fields = [];
3340 if (!defaultParserSet) {
3341 this.detectTypeFromString_(inFields[0]);
3342 xParser = this.attr_("xValueParser");
3343 defaultParserSet = true;
3344 }
3345 fields[0] = xParser(inFields[0], this);
3346
3347 // If fractions are expected, parse the numbers as "A/B"
3348 if (this.fractions_) {
3349 for (var j = 1; j < inFields.length; j++) {
3350 // TODO(danvk): figure out an appropriate way to flag parse errors.
3351 var vals = inFields[j].split("/");
3352 if (vals.length != 2) {
3353 this.error('Expected fractional "num/den" values in CSV data ' +
3354 "but found a value '" + inFields[j] + "' on line " +
3355 (1 + i) + " ('" + line + "') which is not of this form.");
3356 fields[j] = [0, 0];
3357 } else {
3358 fields[j] = [this.parseFloat_(vals[0], i, line),
3359 this.parseFloat_(vals[1], i, line)];
3360 }
3361 }
3362 } else if (this.attr_("errorBars")) {
3363 // If there are error bars, values are (value, stddev) pairs
3364 if (inFields.length % 2 != 1) {
3365 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3366 'but line ' + (1 + i) + ' has an odd number of values (' +
3367 (inFields.length - 1) + "): '" + line + "'");
3368 }
3369 for (var j = 1; j < inFields.length; j += 2) {
3370 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3371 this.parseFloat_(inFields[j + 1], i, line)];
3372 }
3373 } else if (this.attr_("customBars")) {
3374 // Bars are a low;center;high tuple
3375 for (var j = 1; j < inFields.length; j++) {
3376 var val = inFields[j];
3377 if (/^ *$/.test(val)) {
3378 fields[j] = [null, null, null];
3379 } else {
3380 var vals = val.split(";");
3381 if (vals.length == 3) {
3382 fields[j] = [ this.parseFloat_(vals[0], i, line),
3383 this.parseFloat_(vals[1], i, line),
3384 this.parseFloat_(vals[2], i, line) ];
3385 } else {
3386 this.warning('When using customBars, values must be either blank ' +
3387 'or "low;center;high" tuples (got "' + val +
3388 '" on line ' + (1+i));
3389 }
3390 }
3391 }
3392 } else {
3393 // Values are just numbers
3394 for (var j = 1; j < inFields.length; j++) {
3395 fields[j] = this.parseFloat_(inFields[j], i, line);
3396 }
3397 }
3398 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3399 outOfOrder = true;
3400 }
3401
3402 if (fields.length != expectedCols) {
3403 this.error("Number of columns in line " + i + " (" + fields.length +
3404 ") does not agree with number of labels (" + expectedCols +
3405 ") " + line);
3406 }
3407
3408 // If the user specified the 'labels' option and none of the cells of the
3409 // first row parsed correctly, then they probably double-specified the
3410 // labels. We go with the values set in the option, discard this row and
3411 // log a warning to the JS console.
3412 if (i == 0 && this.attr_('labels')) {
3413 var all_null = true;
3414 for (var j = 0; all_null && j < fields.length; j++) {
3415 if (fields[j]) all_null = false;
3416 }
3417 if (all_null) {
3418 this.warn("The dygraphs 'labels' option is set, but the first row of " +
3419 "CSV data ('" + line + "') appears to also contain labels. " +
3420 "Will drop the CSV labels and use the option labels.");
3421 continue;
3422 }
3423 }
3424 ret.push(fields);
3425 }
3426
3427 if (outOfOrder) {
3428 this.warn("CSV is out of order; order it correctly to speed loading.");
3429 ret.sort(function(a,b) { return a[0] - b[0] });
3430 }
3431
3432 return ret;
3433 };
3434
3435 /**
3436 * @private
3437 * The user has provided their data as a pre-packaged JS array. If the x values
3438 * are numeric, this is the same as dygraphs' internal format. If the x values
3439 * are dates, we need to convert them from Date objects to ms since epoch.
3440 * @param {[Object]} data
3441 * @return {[Object]} data with numeric x values.
3442 */
3443 Dygraph.prototype.parseArray_ = function(data) {
3444 // Peek at the first x value to see if it's numeric.
3445 if (data.length == 0) {
3446 this.error("Can't plot empty data set");
3447 return null;
3448 }
3449 if (data[0].length == 0) {
3450 this.error("Data set cannot contain an empty row");
3451 return null;
3452 }
3453
3454 if (this.attr_("labels") == null) {
3455 this.warn("Using default labels. Set labels explicitly via 'labels' " +
3456 "in the options parameter");
3457 this.attrs_.labels = [ "X" ];
3458 for (var i = 1; i < data[0].length; i++) {
3459 this.attrs_.labels.push("Y" + i);
3460 }
3461 }
3462
3463 if (Dygraph.isDateLike(data[0][0])) {
3464 // Some intelligent defaults for a date x-axis.
3465 this.attrs_.xValueFormatter = Dygraph.dateString_;
3466 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
3467 this.attrs_.xTicker = Dygraph.dateTicker;
3468
3469 // Assume they're all dates.
3470 var parsedData = Dygraph.clone(data);
3471 for (var i = 0; i < data.length; i++) {
3472 if (parsedData[i].length == 0) {
3473 this.error("Row " + (1 + i) + " of data is empty");
3474 return null;
3475 }
3476 if (parsedData[i][0] == null
3477 || typeof(parsedData[i][0].getTime) != 'function'
3478 || isNaN(parsedData[i][0].getTime())) {
3479 this.error("x value in row " + (1 + i) + " is not a Date");
3480 return null;
3481 }
3482 parsedData[i][0] = parsedData[i][0].getTime();
3483 }
3484 return parsedData;
3485 } else {
3486 // Some intelligent defaults for a numeric x-axis.
3487 /** @private (shut up, jsdoc!) */
3488 this.attrs_.xValueFormatter = function(x) { return x; };
3489 this.attrs_.xTicker = Dygraph.numericTicks;
3490 return data;
3491 }
3492 };
3493
3494 /**
3495 * Parses a DataTable object from gviz.
3496 * The data is expected to have a first column that is either a date or a
3497 * number. All subsequent columns must be numbers. If there is a clear mismatch
3498 * between this.xValueParser_ and the type of the first column, it will be
3499 * fixed. Fills out rawData_.
3500 * @param {[Object]} data See above.
3501 * @private
3502 */
3503 Dygraph.prototype.parseDataTable_ = function(data) {
3504 var cols = data.getNumberOfColumns();
3505 var rows = data.getNumberOfRows();
3506
3507 var indepType = data.getColumnType(0);
3508 if (indepType == 'date' || indepType == 'datetime') {
3509 this.attrs_.xValueFormatter = Dygraph.dateString_;
3510 this.attrs_.xValueParser = Dygraph.dateParser;
3511 this.attrs_.xTicker = Dygraph.dateTicker;
3512 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
3513 } else if (indepType == 'number') {
3514 this.attrs_.xValueFormatter = function(x) { return x; };
3515 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
3516 this.attrs_.xTicker = Dygraph.numericTicks;
3517 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
3518 } else {
3519 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3520 "column 1 of DataTable input (Got '" + indepType + "')");
3521 return null;
3522 }
3523
3524 // Array of the column indices which contain data (and not annotations).
3525 var colIdx = [];
3526 var annotationCols = {}; // data index -> [annotation cols]
3527 var hasAnnotations = false;
3528 for (var i = 1; i < cols; i++) {
3529 var type = data.getColumnType(i);
3530 if (type == 'number') {
3531 colIdx.push(i);
3532 } else if (type == 'string' && this.attr_('displayAnnotations')) {
3533 // This is OK -- it's an annotation column.
3534 var dataIdx = colIdx[colIdx.length - 1];
3535 if (!annotationCols.hasOwnProperty(dataIdx)) {
3536 annotationCols[dataIdx] = [i];
3537 } else {
3538 annotationCols[dataIdx].push(i);
3539 }
3540 hasAnnotations = true;
3541 } else {
3542 this.error("Only 'number' is supported as a dependent type with Gviz." +
3543 " 'string' is only supported if displayAnnotations is true");
3544 }
3545 }
3546
3547 // Read column labels
3548 // TODO(danvk): add support back for errorBars
3549 var labels = [data.getColumnLabel(0)];
3550 for (var i = 0; i < colIdx.length; i++) {
3551 labels.push(data.getColumnLabel(colIdx[i]));
3552 if (this.attr_("errorBars")) i += 1;
3553 }
3554 this.attrs_.labels = labels;
3555 cols = labels.length;
3556
3557 var ret = [];
3558 var outOfOrder = false;
3559 var annotations = [];
3560 for (var i = 0; i < rows; i++) {
3561 var row = [];
3562 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3563 data.getValue(i, 0) === null) {
3564 this.warn("Ignoring row " + i +
3565 " of DataTable because of undefined or null first column.");
3566 continue;
3567 }
3568
3569 if (indepType == 'date' || indepType == 'datetime') {
3570 row.push(data.getValue(i, 0).getTime());
3571 } else {
3572 row.push(data.getValue(i, 0));
3573 }
3574 if (!this.attr_("errorBars")) {
3575 for (var j = 0; j < colIdx.length; j++) {
3576 var col = colIdx[j];
3577 row.push(data.getValue(i, col));
3578 if (hasAnnotations &&
3579 annotationCols.hasOwnProperty(col) &&
3580 data.getValue(i, annotationCols[col][0]) != null) {
3581 var ann = {};
3582 ann.series = data.getColumnLabel(col);
3583 ann.xval = row[0];
3584 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
3585 ann.text = '';
3586 for (var k = 0; k < annotationCols[col].length; k++) {
3587 if (k) ann.text += "\n";
3588 ann.text += data.getValue(i, annotationCols[col][k]);
3589 }
3590 annotations.push(ann);
3591 }
3592 }
3593
3594 // Strip out infinities, which give dygraphs problems later on.
3595 for (var j = 0; j < row.length; j++) {
3596 if (!isFinite(row[j])) row[j] = null;
3597 }
3598 } else {
3599 for (var j = 0; j < cols - 1; j++) {
3600 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3601 }
3602 }
3603 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3604 outOfOrder = true;
3605 }
3606 ret.push(row);
3607 }
3608
3609 if (outOfOrder) {
3610 this.warn("DataTable is out of order; order it correctly to speed loading.");
3611 ret.sort(function(a,b) { return a[0] - b[0] });
3612 }
3613 this.rawData_ = ret;
3614
3615 if (annotations.length > 0) {
3616 this.setAnnotations(annotations, true);
3617 }
3618 }
3619
3620 /**
3621 * @private
3622 * This is identical to JavaScript's built-in Date.parse() method, except that
3623 * it doesn't get replaced with an incompatible method by aggressive JS
3624 * libraries like MooTools or Joomla.
3625 * @param { String } str The date string, e.g. "2011/05/06"
3626 * @return { Integer } millis since epoch
3627 */
3628 Dygraph.dateStrToMillis = function(str) {
3629 return new Date(str).getTime();
3630 };
3631
3632 // These functions are all based on MochiKit.
3633 /**
3634 * @private
3635 */
3636 Dygraph.update = function (self, o) {
3637 if (typeof(o) != 'undefined' && o !== null) {
3638 for (var k in o) {
3639 if (o.hasOwnProperty(k)) {
3640 self[k] = o[k];
3641 }
3642 }
3643 }
3644 return self;
3645 };
3646
3647 /**
3648 * @private
3649 */
3650 Dygraph.isArrayLike = function (o) {
3651 var typ = typeof(o);
3652 if (
3653 (typ != 'object' && !(typ == 'function' &&
3654 typeof(o.item) == 'function')) ||
3655 o === null ||
3656 typeof(o.length) != 'number' ||
3657 o.nodeType === 3
3658 ) {
3659 return false;
3660 }
3661 return true;
3662 };
3663
3664 /**
3665 * @private
3666 */
3667 Dygraph.isDateLike = function (o) {
3668 if (typeof(o) != "object" || o === null ||
3669 typeof(o.getTime) != 'function') {
3670 return false;
3671 }
3672 return true;
3673 };
3674
3675 /**
3676 * @private
3677 */
3678 Dygraph.clone = function(o) {
3679 // TODO(danvk): figure out how MochiKit's version works
3680 var r = [];
3681 for (var i = 0; i < o.length; i++) {
3682 if (Dygraph.isArrayLike(o[i])) {
3683 r.push(Dygraph.clone(o[i]));
3684 } else {
3685 r.push(o[i]);
3686 }
3687 }
3688 return r;
3689 };
3690
3691
3692 /**
3693 * Get the CSV data. If it's in a function, call that function. If it's in a
3694 * file, do an XMLHttpRequest to get it.
3695 * @private
3696 */
3697 Dygraph.prototype.start_ = function() {
3698 if (typeof this.file_ == 'function') {
3699 // CSV string. Pretend we got it via XHR.
3700 this.loadedEvent_(this.file_());
3701 } else if (Dygraph.isArrayLike(this.file_)) {
3702 this.rawData_ = this.parseArray_(this.file_);
3703 this.predraw_();
3704 } else if (typeof this.file_ == 'object' &&
3705 typeof this.file_.getColumnRange == 'function') {
3706 // must be a DataTable from gviz.
3707 this.parseDataTable_(this.file_);
3708 this.predraw_();
3709 } else if (typeof this.file_ == 'string') {
3710 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3711 if (this.file_.indexOf('\n') >= 0) {
3712 this.loadedEvent_(this.file_);
3713 } else {
3714 var req = new XMLHttpRequest();
3715 var caller = this;
3716 req.onreadystatechange = function () {
3717 if (req.readyState == 4) {
3718 if (req.status == 200) {
3719 caller.loadedEvent_(req.responseText);
3720 }
3721 }
3722 };
3723
3724 req.open("GET", this.file_, true);
3725 req.send(null);
3726 }
3727 } else {
3728 this.error("Unknown data format: " + (typeof this.file_));
3729 }
3730 };
3731
3732 /**
3733 * Changes various properties of the graph. These can include:
3734 * <ul>
3735 * <li>file: changes the source data for the graph</li>
3736 * <li>errorBars: changes whether the data contains stddev</li>
3737 * </ul>
3738 *
3739 * There's a huge variety of options that can be passed to this method. For a
3740 * full list, see http://dygraphs.com/options.html.
3741 *
3742 * @param {Object} attrs The new properties and values
3743 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3744 * call to updateOptions(). If you know better, you can pass true to explicitly
3745 * block the redraw. This can be useful for chaining updateOptions() calls,
3746 * avoiding the occasional infinite loop and preventing redraws when it's not
3747 * necessary (e.g. when updating a callback).
3748 */
3749 Dygraph.prototype.updateOptions = function(attrs, block_redraw) {
3750 if (typeof(block_redraw) == 'undefined') block_redraw = false;
3751
3752 // TODO(danvk): this is a mess. Move these options into attr_.
3753 if ('rollPeriod' in attrs) {
3754 this.rollPeriod_ = attrs.rollPeriod;
3755 }
3756 if ('dateWindow' in attrs) {
3757 this.dateWindow_ = attrs.dateWindow;
3758 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
3759 this.zoomed_x_ = attrs.dateWindow != null;
3760 }
3761 }
3762 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
3763 this.zoomed_y_ = attrs.valueRange != null;
3764 }
3765
3766 // TODO(danvk): validate per-series options.
3767 // Supported:
3768 // strokeWidth
3769 // pointSize
3770 // drawPoints
3771 // highlightCircleSize
3772
3773 Dygraph.update(this.user_attrs_, attrs);
3774
3775 if (attrs['file']) {
3776 this.file_ = attrs['file'];
3777 if (!block_redraw) this.start_();
3778 } else {
3779 if (!block_redraw) this.predraw_();
3780 }
3781 };
3782
3783 /**
3784 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3785 * containing div (which has presumably changed size since the dygraph was
3786 * instantiated. If the width/height are specified, the div will be resized.
3787 *
3788 * This is far more efficient than destroying and re-instantiating a
3789 * Dygraph, since it doesn't have to reparse the underlying data.
3790 *
3791 * @param {Number} [width] Width (in pixels)
3792 * @param {Number} [height] Height (in pixels)
3793 */
3794 Dygraph.prototype.resize = function(width, height) {
3795 if (this.resize_lock) {
3796 return;
3797 }
3798 this.resize_lock = true;
3799
3800 if ((width === null) != (height === null)) {
3801 this.warn("Dygraph.resize() should be called with zero parameters or " +
3802 "two non-NULL parameters. Pretending it was zero.");
3803 width = height = null;
3804 }
3805
3806 // TODO(danvk): there should be a clear() method.
3807 this.maindiv_.innerHTML = "";
3808 this.attrs_.labelsDiv = null;
3809
3810 if (width) {
3811 this.maindiv_.style.width = width + "px";
3812 this.maindiv_.style.height = height + "px";
3813 this.width_ = width;
3814 this.height_ = height;
3815 } else {
3816 this.width_ = this.maindiv_.offsetWidth;
3817 this.height_ = this.maindiv_.offsetHeight;
3818 }
3819
3820 this.createInterface_();
3821 this.predraw_();
3822
3823 this.resize_lock = false;
3824 };
3825
3826 /**
3827 * Adjusts the number of points in the rolling average. Updates the graph to
3828 * reflect the new averaging period.
3829 * @param {Number} length Number of points over which to average the data.
3830 */
3831 Dygraph.prototype.adjustRoll = function(length) {
3832 this.rollPeriod_ = length;
3833 this.predraw_();
3834 };
3835
3836 /**
3837 * Returns a boolean array of visibility statuses.
3838 */
3839 Dygraph.prototype.visibility = function() {
3840 // Do lazy-initialization, so that this happens after we know the number of
3841 // data series.
3842 if (!this.attr_("visibility")) {
3843 this.attrs_["visibility"] = [];
3844 }
3845 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
3846 this.attr_("visibility").push(true);
3847 }
3848 return this.attr_("visibility");
3849 };
3850
3851 /**
3852 * Changes the visiblity of a series.
3853 */
3854 Dygraph.prototype.setVisibility = function(num, value) {
3855 var x = this.visibility();
3856 if (num < 0 || num >= x.length) {
3857 this.warn("invalid series number in setVisibility: " + num);
3858 } else {
3859 x[num] = value;
3860 this.predraw_();
3861 }
3862 };
3863
3864 /**
3865 * Update the list of annotations and redraw the chart.
3866 */
3867 Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3868 // Only add the annotation CSS rule once we know it will be used.
3869 Dygraph.addAnnotationRule();
3870 this.annotations_ = ann;
3871 this.layout_.setAnnotations(this.annotations_);
3872 if (!suppressDraw) {
3873 this.predraw_();
3874 }
3875 };
3876
3877 /**
3878 * Return the list of annotations.
3879 */
3880 Dygraph.prototype.annotations = function() {
3881 return this.annotations_;
3882 };
3883
3884 /**
3885 * Get the index of a series (column) given its name. The first column is the
3886 * x-axis, so the data series start with index 1.
3887 */
3888 Dygraph.prototype.indexFromSetName = function(name) {
3889 var labels = this.attr_("labels");
3890 for (var i = 0; i < labels.length; i++) {
3891 if (labels[i] == name) return i;
3892 }
3893 return null;
3894 };
3895
3896 /**
3897 * @private
3898 * Adds a default style for the annotation CSS classes to the document. This is
3899 * only executed when annotations are actually used. It is designed to only be
3900 * called once -- all calls after the first will return immediately.
3901 */
3902 Dygraph.addAnnotationRule = function() {
3903 if (Dygraph.addedAnnotationCSS) return;
3904
3905 var rule = "border: 1px solid black; " +
3906 "background-color: white; " +
3907 "text-align: center;";
3908
3909 var styleSheetElement = document.createElement("style");
3910 styleSheetElement.type = "text/css";
3911 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3912
3913 // Find the first style sheet that we can access.
3914 // We may not add a rule to a style sheet from another domain for security
3915 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3916 // adds its own style sheets from google.com.
3917 for (var i = 0; i < document.styleSheets.length; i++) {
3918 if (document.styleSheets[i].disabled) continue;
3919 var mysheet = document.styleSheets[i];
3920 try {
3921 if (mysheet.insertRule) { // Firefox
3922 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3923 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3924 } else if (mysheet.addRule) { // IE
3925 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3926 }
3927 Dygraph.addedAnnotationCSS = true;
3928 return;
3929 } catch(err) {
3930 // Was likely a security exception.
3931 }
3932 }
3933
3934 this.warn("Unable to add default annotation CSS rule; display may be off.");
3935 }
3936
3937 /**
3938 * @private
3939 * Create a new canvas element. This is more complex than a simple
3940 * document.createElement("canvas") because of IE and excanvas.
3941 */
3942 Dygraph.createCanvas = function() {
3943 var canvas = document.createElement("canvas");
3944
3945 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
3946 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
3947 canvas = G_vmlCanvasManager.initElement(canvas);
3948 }
3949
3950 return canvas;
3951 };
3952
3953 // Older pages may still use this name.
3954 DateGraph = Dygraph;