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