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