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