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