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