Initial implementation
[dygraphs.git] / dygraph.js
1 // Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2 // All Rights Reserved.
3
4 /**
5 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
6 * string. Dygraph can handle multiple series with or without error bars. The
7 * date/value ranges will be automatically set. Dygraph uses the
8 * <canvas> tag, so it only works in FF1.5+.
9 * @author danvdk@gmail.com (Dan Vanderkam)
10
11 Usage:
12 <div id="graphdiv" style="width:800px; height:500px;"></div>
13 <script type="text/javascript">
14 new Dygraph(document.getElementById("graphdiv"),
15 "datafile.csv", // CSV file with headers
16 { }); // options
17 </script>
18
19 The CSV file is of the form
20
21 Date,SeriesA,SeriesB,SeriesC
22 YYYYMMDD,A1,B1,C1
23 YYYYMMDD,A2,B2,C2
24
25 If the 'errorBars' option is set in the constructor, the input should be of
26 the form
27 Date,SeriesA,SeriesB,...
28 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
29 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
30
31 If the 'fractions' option is set, the input should be of the form:
32
33 Date,SeriesA,SeriesB,...
34 YYYYMMDD,A1/B1,A2/B2,...
35 YYYYMMDD,A1/B1,A2/B2,...
36
37 And error bars will be calculated automatically using a binomial distribution.
38
39 For further documentation and examples, see http://dygraphs.com/
40
41 */
42
43 /**
44 * An interactive, zoomable graph
45 * @param {String | Function} file A file containing CSV data or a function that
46 * returns this data. The expected format for each line is
47 * YYYYMMDD,val1,val2,... or, if attrs.errorBars is set,
48 * YYYYMMDD,val1,stddev1,val2,stddev2,...
49 * @param {Object} attrs Various other attributes, e.g. errorBars determines
50 * whether the input data contains error ranges.
51 */
52 Dygraph = function(div, data, opts) {
53 if (arguments.length > 0) {
54 if (arguments.length == 4) {
55 // Old versions of dygraphs took in the series labels as a constructor
56 // parameter. This doesn't make sense anymore, but it's easy to continue
57 // to support this usage.
58 this.warn("Using deprecated four-argument dygraph constructor");
59 this.__old_init__(div, data, arguments[2], arguments[3]);
60 } else {
61 this.__init__(div, data, opts);
62 }
63 }
64 };
65
66 Dygraph.NAME = "Dygraph";
67 Dygraph.VERSION = "1.2";
68 Dygraph.__repr__ = function() {
69 return "[" + this.NAME + " " + this.VERSION + "]";
70 };
71 Dygraph.toString = function() {
72 return this.__repr__();
73 };
74
75 /**
76 * Formatting to use for an integer number.
77 *
78 * @param {Number} x The number to format
79 * @param {Number} unused_precision The precision to use, ignored.
80 * @return {String} A string formatted like %g in printf. The max generated
81 * string length should be precision + 6 (e.g 1.123e+300).
82 */
83 Dygraph.intFormat = function(x, unused_precision) {
84 return x.toString();
85 }
86
87 /**
88 * Number formatting function which mimicks the behavior of %g in printf, i.e.
89 * either exponential or fixed format (without trailing 0s) is used depending on
90 * the length of the generated string. The advantage of this format is that
91 * there is a predictable upper bound on the resulting string length,
92 * significant figures are not dropped, and normal numbers are not displayed in
93 * exponential notation.
94 *
95 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
96 * It creates strings which are too long for absolute values between 10^-4 and
97 * 10^-6. See tests/number-format.html for output examples.
98 *
99 * @param {Number} x The number to format
100 * @param {Number} opt_precision The precision to use, default 2.
101 * @return {String} A string formatted like %g in printf. The max generated
102 * string length should be precision + 6 (e.g 1.123e+300).
103 */
104 Dygraph.floatFormat = function(x, opt_precision) {
105 // Avoid invalid precision values; [1, 21] is the valid range.
106 var p = Math.min(Math.max(1, opt_precision || 2), 21);
107
108 // This is deceptively simple. The actual algorithm comes from:
109 //
110 // Max allowed length = p + 4
111 // where 4 comes from 'e+n' and '.'.
112 //
113 // Length of fixed format = 2 + y + p
114 // where 2 comes from '0.' and y = # of leading zeroes.
115 //
116 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
117 // 1.0e-3.
118 //
119 // Since the behavior of toPrecision() is identical for larger numbers, we
120 // don't have to worry about the other bound.
121 //
122 // Finally, the argument for toExponential() is the number of trailing digits,
123 // so we take off 1 for the value before the '.'.
124 return (Math.abs(x) < 1.0e-3 && x != 0.0) ?
125 x.toExponential(p - 1) : x.toPrecision(p);
126 };
127
128 // Various default values
129 Dygraph.DEFAULT_ROLL_PERIOD = 1;
130 Dygraph.DEFAULT_WIDTH = 480;
131 Dygraph.DEFAULT_HEIGHT = 320;
132 Dygraph.AXIS_LINE_WIDTH = 0.3;
133
134 Dygraph.LOG_SCALE = 10;
135 Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
136 Dygraph.log10 = function(x) {
137 return Math.log(x) / Dygraph.LN_TEN;
138 }
139
140 // Default attribute values.
141 Dygraph.DEFAULT_ATTRS = {
142 highlightCircleSize: 3,
143 pixelsPerXLabel: 60,
144 pixelsPerYLabel: 30,
145
146 labelsDivWidth: 250,
147 labelsDivStyles: {
148 // TODO(danvk): move defaults from createStatusMessage_ here.
149 },
150 labelsSeparateLines: false,
151 labelsShowZeroValues: true,
152 labelsKMB: false,
153 labelsKMG2: false,
154 showLabelsOnHighlight: true,
155
156 yValueFormatter: function(x, opt_precision) {
157 var s = Dygraph.floatFormat(x, opt_precision);
158 var s2 = Dygraph.intFormat(x);
159 return s.length < s2.length ? s : s2;
160 },
161
162 strokeWidth: 1.0,
163
164 axisTickSize: 3,
165 axisLabelFontSize: 14,
166 xAxisLabelWidth: 50,
167 yAxisLabelWidth: 50,
168 xAxisLabelFormatter: Dygraph.dateAxisFormatter,
169 rightGap: 5,
170
171 showRoller: false,
172 xValueFormatter: Dygraph.dateString_,
173 xValueParser: Dygraph.dateParser,
174 xTicker: Dygraph.dateTicker,
175
176 delimiter: ',',
177
178 sigma: 2.0,
179 errorBars: false,
180 fractions: false,
181 wilsonInterval: true, // only relevant if fractions is true
182 customBars: false,
183 fillGraph: false,
184 fillAlpha: 0.15,
185 connectSeparatedPoints: false,
186
187 stackedGraph: false,
188 hideOverlayOnMouseOut: true,
189
190 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
191 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
192
193 stepPlot: false,
194 avoidMinZero: false,
195
196 // Sizes of the various chart labels.
197 titleHeight: 16,
198 xLabelHeight: 16,
199 yLabelWidth: 16,
200
201 interactionModel: null // will be set to Dygraph.defaultInteractionModel.
202 };
203
204 // Various logging levels.
205 Dygraph.DEBUG = 1;
206 Dygraph.INFO = 2;
207 Dygraph.WARNING = 3;
208 Dygraph.ERROR = 3;
209
210 // Directions for panning and zooming. Use bit operations when combined
211 // values are possible.
212 Dygraph.HORIZONTAL = 1;
213 Dygraph.VERTICAL = 2;
214
215 // Used for initializing annotation CSS rules only once.
216 Dygraph.addedAnnotationCSS = false;
217
218 Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
219 // Labels is no longer a constructor parameter, since it's typically set
220 // directly from the data source. It also conains a name for the x-axis,
221 // which the previous constructor form did not.
222 if (labels != null) {
223 var new_labels = ["Date"];
224 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
225 Dygraph.update(attrs, { 'labels': new_labels });
226 }
227 this.__init__(div, file, attrs);
228 };
229
230 /**
231 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
232 * and context &lt;canvas&gt; inside of it. See the constructor for details.
233 * on the parameters.
234 * @param {Element} div the Element to render the graph into.
235 * @param {String | Function} file Source data
236 * @param {Object} attrs Miscellaneous other options
237 * @private
238 */
239 Dygraph.prototype.__init__ = function(div, file, attrs) {
240 // Hack for IE: if we're using excanvas and the document hasn't finished
241 // loading yet (and hence may not have initialized whatever it needs to
242 // initialize), then keep calling this routine periodically until it has.
243 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
244 typeof(G_vmlCanvasManager) != 'undefined' &&
245 document.readyState != 'complete') {
246 var self = this;
247 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
248 }
249
250 // Support two-argument constructor
251 if (attrs == null) { attrs = {}; }
252
253 // Copy the important bits into the object
254 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
255 this.maindiv_ = div;
256 this.file_ = file;
257 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
258 this.previousVerticalX_ = -1;
259 this.fractions_ = attrs.fractions || false;
260 this.dateWindow_ = attrs.dateWindow || null;
261
262 this.wilsonInterval_ = attrs.wilsonInterval || true;
263 this.is_initial_draw_ = true;
264 this.annotations_ = [];
265
266 // Number of digits to use when labeling the x (if numeric) and y axis
267 // ticks.
268 this.numXDigits_ = 2;
269 this.numYDigits_ = 2;
270
271 // When labeling x (if numeric) or y values in the legend, there are
272 // numDigits + numExtraDigits of precision used. For axes labels with N
273 // digits of precision, the data should be displayed with at least N+1 digits
274 // of precision. The reason for this is to divide each interval between
275 // successive ticks into tenths (for 1) or hundredths (for 2), etc. For
276 // example, if the labels are [0, 1, 2], we want data to be displayed as
277 // 0.1, 1.3, etc.
278 this.numExtraDigits_ = 1;
279
280 // Clear the div. This ensure that, if multiple dygraphs are passed the same
281 // div, then only one will be drawn.
282 div.innerHTML = "";
283
284 // If the div isn't already sized then inherit from our attrs or
285 // give it a default size.
286 if (div.style.width == '') {
287 div.style.width = (attrs.width || Dygraph.DEFAULT_WIDTH) + "px";
288 }
289 if (div.style.height == '') {
290 div.style.height = (attrs.height || Dygraph.DEFAULT_HEIGHT) + "px";
291 }
292 this.width_ = parseInt(div.style.width, 10);
293 this.height_ = parseInt(div.style.height, 10);
294 // The div might have been specified as percent of the current window size,
295 // convert that to an appropriate number of pixels.
296 if (div.style.width.indexOf("%") == div.style.width.length - 1) {
297 this.width_ = div.offsetWidth;
298 }
299 if (div.style.height.indexOf("%") == div.style.height.length - 1) {
300 this.height_ = div.offsetHeight;
301 }
302
303 if (this.width_ == 0) {
304 this.error("dygraph has zero width. Please specify a width in pixels.");
305 }
306 if (this.height_ == 0) {
307 this.error("dygraph has zero height. Please specify a height in pixels.");
308 }
309
310 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
311 if (attrs['stackedGraph']) {
312 attrs['fillGraph'] = true;
313 // TODO(nikhilk): Add any other stackedGraph checks here.
314 }
315
316 // Dygraphs has many options, some of which interact with one another.
317 // To keep track of everything, we maintain two sets of options:
318 //
319 // this.user_attrs_ only options explicitly set by the user.
320 // this.attrs_ defaults, options derived from user_attrs_, data.
321 //
322 // Options are then accessed this.attr_('attr'), which first looks at
323 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
324 // defaults without overriding behavior that the user specifically asks for.
325 this.user_attrs_ = {};
326 Dygraph.update(this.user_attrs_, attrs);
327
328 this.attrs_ = {};
329 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
330
331 this.boundaryIds_ = [];
332
333 // Make a note of whether labels will be pulled from the CSV file.
334 this.labelsFromCSV_ = (this.attr_("labels") == null);
335
336 // Create the containing DIV and other interactive elements
337 this.createInterface_();
338
339 this.start_();
340 };
341
342 Dygraph.prototype.toString = function() {
343 var maindiv = this.maindiv_;
344 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
345 return "[Dygraph " + id + "]";
346 }
347
348 Dygraph.prototype.attr_ = function(name, seriesName) {
349 // <REMOVE_FOR_COMBINED>
350 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
351 this.error('Must include options reference JS for testing');
352 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
353 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
354 'in the Dygraphs.OPTIONS_REFERENCE listing.');
355 // Only log this error once.
356 Dygraph.OPTIONS_REFERENCE[name] = true;
357 }
358 // </REMOVE_FOR_COMBINED>
359 if (seriesName &&
360 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
361 this.user_attrs_[seriesName] != null &&
362 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
363 return this.user_attrs_[seriesName][name];
364 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
365 return this.user_attrs_[name];
366 } else if (typeof(this.attrs_[name]) != 'undefined') {
367 return this.attrs_[name];
368 } else {
369 return null;
370 }
371 };
372
373 // TODO(danvk): any way I can get the line numbers to be this.warn call?
374 Dygraph.prototype.log = function(severity, message) {
375 if (typeof(console) != 'undefined') {
376 switch (severity) {
377 case Dygraph.DEBUG:
378 console.debug('dygraphs: ' + message);
379 break;
380 case Dygraph.INFO:
381 console.info('dygraphs: ' + message);
382 break;
383 case Dygraph.WARNING:
384 console.warn('dygraphs: ' + message);
385 break;
386 case Dygraph.ERROR:
387 console.error('dygraphs: ' + message);
388 break;
389 }
390 }
391 }
392 Dygraph.prototype.info = function(message) {
393 this.log(Dygraph.INFO, message);
394 }
395 Dygraph.prototype.warn = function(message) {
396 this.log(Dygraph.WARNING, message);
397 }
398 Dygraph.prototype.error = function(message) {
399 this.log(Dygraph.ERROR, message);
400 }
401
402 /**
403 * Returns the current rolling period, as set by the user or an option.
404 * @return {Number} The number of points in the rolling window
405 */
406 Dygraph.prototype.rollPeriod = function() {
407 return this.rollPeriod_;
408 };
409
410 /**
411 * Returns the currently-visible x-range. This can be affected by zooming,
412 * panning or a call to updateOptions.
413 * Returns a two-element array: [left, right].
414 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
415 */
416 Dygraph.prototype.xAxisRange = function() {
417 if (this.dateWindow_) return this.dateWindow_;
418
419 // The entire chart is visible.
420 var left = this.rawData_[0][0];
421 var right = this.rawData_[this.rawData_.length - 1][0];
422 return [left, right];
423 };
424
425 /**
426 * Returns the currently-visible y-range for an axis. This can be affected by
427 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
428 * called with no arguments, returns the range of the first axis.
429 * Returns a two-element array: [bottom, top].
430 */
431 Dygraph.prototype.yAxisRange = function(idx) {
432 if (typeof(idx) == "undefined") idx = 0;
433 if (idx < 0 || idx >= this.axes_.length) return null;
434 return [ this.axes_[idx].computedValueRange[0],
435 this.axes_[idx].computedValueRange[1] ];
436 };
437
438 /**
439 * Returns the currently-visible y-ranges for each axis. This can be affected by
440 * zooming, panning, calls to updateOptions, etc.
441 * Returns an array of [bottom, top] pairs, one for each y-axis.
442 */
443 Dygraph.prototype.yAxisRanges = function() {
444 var ret = [];
445 for (var i = 0; i < this.axes_.length; i++) {
446 ret.push(this.yAxisRange(i));
447 }
448 return ret;
449 };
450
451 // TODO(danvk): use these functions throughout dygraphs.
452 /**
453 * Convert from data coordinates to canvas/div X/Y coordinates.
454 * If specified, do this conversion for the coordinate system of a particular
455 * axis. Uses the first axis by default.
456 * Returns a two-element array: [X, Y]
457 *
458 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
459 * instead of toDomCoords(null, y, axis).
460 */
461 Dygraph.prototype.toDomCoords = function(x, y, axis) {
462 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
463 };
464
465 /**
466 * Convert from data x coordinates to canvas/div X coordinate.
467 * If specified, do this conversion for the coordinate system of a particular
468 * axis.
469 * Returns a single value or null if x is null.
470 */
471 Dygraph.prototype.toDomXCoord = function(x) {
472 if (x == null) {
473 return null;
474 };
475
476 var area = this.plotter_.area;
477 var xRange = this.xAxisRange();
478 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
479 }
480
481 /**
482 * Convert from data x coordinates to canvas/div Y coordinate and optional
483 * axis. Uses the first axis by default.
484 *
485 * returns a single value or null if y is null.
486 */
487 Dygraph.prototype.toDomYCoord = function(y, axis) {
488 var pct = this.toPercentYCoord(y, axis);
489
490 if (pct == null) {
491 return null;
492 }
493 var area = this.plotter_.area;
494 return area.y + pct * area.h;
495 }
496
497 /**
498 * Convert from canvas/div coords to data coordinates.
499 * If specified, do this conversion for the coordinate system of a particular
500 * axis. Uses the first axis by default.
501 * Returns a two-element array: [X, Y].
502 *
503 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
504 * instead of toDataCoords(null, y, axis).
505 */
506 Dygraph.prototype.toDataCoords = function(x, y, axis) {
507 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
508 };
509
510 /**
511 * Convert from canvas/div x coordinate to data coordinate.
512 *
513 * If x is null, this returns null.
514 */
515 Dygraph.prototype.toDataXCoord = function(x) {
516 if (x == null) {
517 return null;
518 }
519
520 var area = this.plotter_.area;
521 var xRange = this.xAxisRange();
522 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
523 };
524
525 /**
526 * Convert from canvas/div y coord to value.
527 *
528 * If y is null, this returns null.
529 * if axis is null, this uses the first axis.
530 */
531 Dygraph.prototype.toDataYCoord = function(y, axis) {
532 if (y == null) {
533 return null;
534 }
535
536 var area = this.plotter_.area;
537 var yRange = this.yAxisRange(axis);
538
539 if (typeof(axis) == "undefined") axis = 0;
540 if (!this.axes_[axis].logscale) {
541 return yRange[0] + (area.h - y) / area.h * (yRange[1] - yRange[0]);
542 } else {
543 // Computing the inverse of toDomCoord.
544 var pct = (y - area.y) / area.h
545
546 // Computing the inverse of toPercentYCoord. The function was arrived at with
547 // the following steps:
548 //
549 // Original calcuation:
550 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
551 //
552 // Move denominator to both sides:
553 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
554 //
555 // subtract logr1, and take the negative value.
556 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
557 //
558 // Swap both sides of the equation, and we can compute the log of the
559 // return value. Which means we just need to use that as the exponent in
560 // e^exponent.
561 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
562
563 var logr1 = Dygraph.log10(yRange[1]);
564 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
565 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
566 return value;
567 }
568 };
569
570 /**
571 * Converts a y for an axis to a percentage from the top to the
572 * bottom of the div.
573 *
574 * If the coordinate represents a value visible on the canvas, then
575 * the value will be between 0 and 1, where 0 is the top of the canvas.
576 * However, this method will return values outside the range, as
577 * values can fall outside the canvas.
578 *
579 * If y is null, this returns null.
580 * if axis is null, this uses the first axis.
581 */
582 Dygraph.prototype.toPercentYCoord = function(y, axis) {
583 if (y == null) {
584 return null;
585 }
586 if (typeof(axis) == "undefined") axis = 0;
587
588 var area = this.plotter_.area;
589 var yRange = this.yAxisRange(axis);
590
591 var pct;
592 if (!this.axes_[axis].logscale) {
593 // yrange[1] - y is unit distance from the bottom.
594 // yrange[1] - yrange[0] is the scale of the range.
595 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
596 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
597 } else {
598 var logr1 = Dygraph.log10(yRange[1]);
599 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
600 }
601 return pct;
602 }
603
604 /**
605 * Returns the number of columns (including the independent variable).
606 */
607 Dygraph.prototype.numColumns = function() {
608 return this.rawData_[0].length;
609 };
610
611 /**
612 * Returns the number of rows (excluding any header/label row).
613 */
614 Dygraph.prototype.numRows = function() {
615 return this.rawData_.length;
616 };
617
618 /**
619 * Returns the value in the given row and column. If the row and column exceed
620 * the bounds on the data, returns null. Also returns null if the value is
621 * missing.
622 */
623 Dygraph.prototype.getValue = function(row, col) {
624 if (row < 0 || row > this.rawData_.length) return null;
625 if (col < 0 || col > this.rawData_[row].length) return null;
626
627 return this.rawData_[row][col];
628 };
629
630 Dygraph.addEvent = function(el, evt, fn) {
631 var normed_fn = function(e) {
632 if (!e) var e = window.event;
633 fn(e);
634 };
635 if (window.addEventListener) { // Mozilla, Netscape, Firefox
636 el.addEventListener(evt, normed_fn, false);
637 } else { // IE
638 el.attachEvent('on' + evt, normed_fn);
639 }
640 };
641
642
643 // Based on the article at
644 // http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
645 Dygraph.cancelEvent = function(e) {
646 e = e ? e : window.event;
647 if (e.stopPropagation) {
648 e.stopPropagation();
649 }
650 if (e.preventDefault) {
651 e.preventDefault();
652 }
653 e.cancelBubble = true;
654 e.cancel = true;
655 e.returnValue = false;
656 return false;
657 }
658
659
660 /**
661 * Generates interface elements for the Dygraph: a containing div, a div to
662 * display the current point, and a textbox to adjust the rolling average
663 * period. Also creates the Renderer/Layout elements.
664 * @private
665 */
666 Dygraph.prototype.createInterface_ = function() {
667 // Create the all-enclosing graph div
668 var enclosing = this.maindiv_;
669
670 this.graphDiv = document.createElement("div");
671 this.graphDiv.style.width = this.width_ + "px";
672 this.graphDiv.style.height = this.height_ + "px";
673 enclosing.appendChild(this.graphDiv);
674
675 // Create the canvas for interactive parts of the chart.
676 this.canvas_ = Dygraph.createCanvas();
677 this.canvas_.style.position = "absolute";
678 this.canvas_.width = this.width_;
679 this.canvas_.height = this.height_;
680 this.canvas_.style.width = this.width_ + "px"; // for IE
681 this.canvas_.style.height = this.height_ + "px"; // for IE
682
683 // ... and for static parts of the chart.
684 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
685
686 // The interactive parts of the graph are drawn on top of the chart.
687 this.graphDiv.appendChild(this.hidden_);
688 this.graphDiv.appendChild(this.canvas_);
689 this.mouseEventElement_ = this.canvas_;
690
691 var dygraph = this;
692 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
693 dygraph.mouseMove_(e);
694 });
695 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
696 dygraph.mouseOut_(e);
697 });
698
699 // Create the grapher
700 // TODO(danvk): why does the Layout need its own set of options?
701 this.layoutOptions_ = { 'xOriginIsZero': false };
702 Dygraph.update(this.layoutOptions_, this.attrs_);
703 Dygraph.update(this.layoutOptions_, this.user_attrs_);
704 Dygraph.update(this.layoutOptions_, {
705 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
706
707 this.layout_ = new DygraphLayout(this, this.layoutOptions_);
708
709 // TODO(danvk): why does the Renderer need its own set of options?
710 this.renderOptions_ = { colorScheme: this.colors_,
711 strokeColor: null,
712 axisLineWidth: Dygraph.AXIS_LINE_WIDTH };
713 Dygraph.update(this.renderOptions_, this.attrs_);
714 Dygraph.update(this.renderOptions_, this.user_attrs_);
715
716 this.createStatusMessage_();
717 this.createDragInterface_();
718 };
719
720 /**
721 * Detach DOM elements in the dygraph and null out all data references.
722 * Calling this when you're done with a dygraph can dramatically reduce memory
723 * usage. See, e.g., the tests/perf.html example.
724 */
725 Dygraph.prototype.destroy = function() {
726 var removeRecursive = function(node) {
727 while (node.hasChildNodes()) {
728 removeRecursive(node.firstChild);
729 node.removeChild(node.firstChild);
730 }
731 };
732 removeRecursive(this.maindiv_);
733
734 var nullOut = function(obj) {
735 for (var n in obj) {
736 if (typeof(obj[n]) === 'object') {
737 obj[n] = null;
738 }
739 }
740 };
741
742 // These may not all be necessary, but it can't hurt...
743 nullOut(this.layout_);
744 nullOut(this.plotter_);
745 nullOut(this);
746 };
747
748 /**
749 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
750 * this particular canvas. All Dygraph work is done on this.canvas_.
751 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
752 * @return {Object} The newly-created canvas
753 * @private
754 */
755 Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
756 var h = Dygraph.createCanvas();
757 h.style.position = "absolute";
758 // TODO(danvk): h should be offset from canvas. canvas needs to include
759 // some extra area to make it easier to zoom in on the far left and far
760 // right. h needs to be precisely the plot area, so that clipping occurs.
761 h.style.top = canvas.style.top;
762 h.style.left = canvas.style.left;
763 h.width = this.width_;
764 h.height = this.height_;
765 h.style.width = this.width_ + "px"; // for IE
766 h.style.height = this.height_ + "px"; // for IE
767 return h;
768 };
769
770 // Taken from MochiKit.Color
771 Dygraph.hsvToRGB = function (hue, saturation, value) {
772 var red;
773 var green;
774 var blue;
775 if (saturation === 0) {
776 red = value;
777 green = value;
778 blue = value;
779 } else {
780 var i = Math.floor(hue * 6);
781 var f = (hue * 6) - i;
782 var p = value * (1 - saturation);
783 var q = value * (1 - (saturation * f));
784 var t = value * (1 - (saturation * (1 - f)));
785 switch (i) {
786 case 1: red = q; green = value; blue = p; break;
787 case 2: red = p; green = value; blue = t; break;
788 case 3: red = p; green = q; blue = value; break;
789 case 4: red = t; green = p; blue = value; break;
790 case 5: red = value; green = p; blue = q; break;
791 case 6: // fall through
792 case 0: red = value; green = t; blue = p; break;
793 }
794 }
795 red = Math.floor(255 * red + 0.5);
796 green = Math.floor(255 * green + 0.5);
797 blue = Math.floor(255 * blue + 0.5);
798 return 'rgb(' + red + ',' + green + ',' + blue + ')';
799 };
800
801
802 /**
803 * Generate a set of distinct colors for the data series. This is done with a
804 * color wheel. Saturation/Value are customizable, and the hue is
805 * equally-spaced around the color wheel. If a custom set of colors is
806 * specified, that is used instead.
807 * @private
808 */
809 Dygraph.prototype.setColors_ = function() {
810 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
811 // away with this.renderOptions_.
812 var num = this.attr_("labels").length - 1;
813 this.colors_ = [];
814 var colors = this.attr_('colors');
815 if (!colors) {
816 var sat = this.attr_('colorSaturation') || 1.0;
817 var val = this.attr_('colorValue') || 0.5;
818 var half = Math.ceil(num / 2);
819 for (var i = 1; i <= num; i++) {
820 if (!this.visibility()[i-1]) continue;
821 // alternate colors for high contrast.
822 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
823 var hue = (1.0 * idx/ (1 + num));
824 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
825 }
826 } else {
827 for (var i = 0; i < num; i++) {
828 if (!this.visibility()[i]) continue;
829 var colorStr = colors[i % colors.length];
830 this.colors_.push(colorStr);
831 }
832 }
833
834 // TODO(danvk): update this w/r/t/ the new options system.
835 this.renderOptions_.colorScheme = this.colors_;
836 Dygraph.update(this.plotter_.options, this.renderOptions_);
837 Dygraph.update(this.layoutOptions_, this.user_attrs_);
838 Dygraph.update(this.layoutOptions_, this.attrs_);
839 }
840
841 /**
842 * Return the list of colors. This is either the list of colors passed in the
843 * attributes, or the autogenerated list of rgb(r,g,b) strings.
844 * @return {Array<string>} The list of colors.
845 */
846 Dygraph.prototype.getColors = function() {
847 return this.colors_;
848 };
849
850 // The following functions are from quirksmode.org with a modification for Safari from
851 // http://blog.firetree.net/2005/07/04/javascript-find-position/
852 // http://www.quirksmode.org/js/findpos.html
853 Dygraph.findPosX = function(obj) {
854 var curleft = 0;
855 if(obj.offsetParent)
856 while(1)
857 {
858 curleft += obj.offsetLeft;
859 if(!obj.offsetParent)
860 break;
861 obj = obj.offsetParent;
862 }
863 else if(obj.x)
864 curleft += obj.x;
865 return curleft;
866 };
867
868 Dygraph.findPosY = function(obj) {
869 var curtop = 0;
870 if(obj.offsetParent)
871 while(1)
872 {
873 curtop += obj.offsetTop;
874 if(!obj.offsetParent)
875 break;
876 obj = obj.offsetParent;
877 }
878 else if(obj.y)
879 curtop += obj.y;
880 return curtop;
881 };
882
883
884
885 /**
886 * Create the div that contains information on the selected point(s)
887 * This goes in the top right of the canvas, unless an external div has already
888 * been specified.
889 * @private
890 */
891 Dygraph.prototype.createStatusMessage_ = function() {
892 var userLabelsDiv = this.user_attrs_["labelsDiv"];
893 if (userLabelsDiv && null != userLabelsDiv
894 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
895 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
896 }
897 if (!this.attr_("labelsDiv")) {
898 var divWidth = this.attr_('labelsDivWidth');
899 var messagestyle = {
900 "position": "absolute",
901 "fontSize": "14px",
902 "zIndex": 10,
903 "width": divWidth + "px",
904 "top": "0px",
905 "left": (this.width_ - divWidth - 2) + "px",
906 "background": "white",
907 "textAlign": "left",
908 "overflow": "hidden"};
909 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
910 var div = document.createElement("div");
911 for (var name in messagestyle) {
912 if (messagestyle.hasOwnProperty(name)) {
913 div.style[name] = messagestyle[name];
914 }
915 }
916 this.graphDiv.appendChild(div);
917 this.attrs_.labelsDiv = div;
918 }
919 };
920
921 /**
922 * Position the labels div so that:
923 * - its right edge is flush with the right edge of the charting area
924 * - its top edge is flush with the top edge of the charting area
925 */
926 Dygraph.prototype.positionLabelsDiv_ = function() {
927 // Don't touch a user-specified labelsDiv.
928 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
929
930 var area = this.plotter_.area;
931 var div = this.attr_("labelsDiv");
932 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
933 div.style.top = area.y + "px";
934 };
935
936 /**
937 * Create the text box to adjust the averaging period
938 * @private
939 */
940 Dygraph.prototype.createRollInterface_ = function() {
941 // Create a roller if one doesn't exist already.
942 if (!this.roller_) {
943 this.roller_ = document.createElement("input");
944 this.roller_.type = "text";
945 this.roller_.style.display = "none";
946 this.graphDiv.appendChild(this.roller_);
947 }
948
949 var display = this.attr_('showRoller') ? 'block' : 'none';
950
951 var textAttr = { "position": "absolute",
952 "zIndex": 10,
953 "top": (this.plotter_.area.h - 25) + "px",
954 "left": (this.plotter_.area.x + 1) + "px",
955 "display": display
956 };
957 this.roller_.size = "2";
958 this.roller_.value = this.rollPeriod_;
959 for (var name in textAttr) {
960 if (textAttr.hasOwnProperty(name)) {
961 this.roller_.style[name] = textAttr[name];
962 }
963 }
964
965 var dygraph = this;
966 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
967 };
968
969 // These functions are taken from MochiKit.Signal
970 Dygraph.pageX = function(e) {
971 if (e.pageX) {
972 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
973 } else {
974 var de = document;
975 var b = document.body;
976 return e.clientX +
977 (de.scrollLeft || b.scrollLeft) -
978 (de.clientLeft || 0);
979 }
980 };
981
982 Dygraph.pageY = function(e) {
983 if (e.pageY) {
984 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
985 } else {
986 var de = document;
987 var b = document.body;
988 return e.clientY +
989 (de.scrollTop || b.scrollTop) -
990 (de.clientTop || 0);
991 }
992 };
993
994 Dygraph.prototype.dragGetX_ = function(e, context) {
995 return Dygraph.pageX(e) - context.px
996 };
997
998 Dygraph.prototype.dragGetY_ = function(e, context) {
999 return Dygraph.pageY(e) - context.py
1000 };
1001
1002 // Called in response to an interaction model operation that
1003 // should start the default panning behavior.
1004 //
1005 // It's used in the default callback for "mousedown" operations.
1006 // Custom interaction model builders can use it to provide the default
1007 // panning behavior.
1008 //
1009 Dygraph.startPan = function(event, g, context) {
1010 context.isPanning = true;
1011 var xRange = g.xAxisRange();
1012 context.dateRange = xRange[1] - xRange[0];
1013 context.initialLeftmostDate = xRange[0];
1014 context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
1015
1016 // Record the range of each y-axis at the start of the drag.
1017 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
1018 context.is2DPan = false;
1019 for (var i = 0; i < g.axes_.length; i++) {
1020 var axis = g.axes_[i];
1021 var yRange = g.yAxisRange(i);
1022 // TODO(konigsberg): These values should be in |context|.
1023 // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
1024 if (axis.logscale) {
1025 axis.initialTopValue = Dygraph.log10(yRange[1]);
1026 axis.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]);
1027 } else {
1028 axis.initialTopValue = yRange[1];
1029 axis.dragValueRange = yRange[1] - yRange[0];
1030 }
1031 axis.unitsPerPixel = axis.dragValueRange / (g.plotter_.area.h - 1);
1032
1033 // While calculating axes, set 2dpan.
1034 if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
1035 }
1036 };
1037
1038 // Called in response to an interaction model operation that
1039 // responds to an event that pans the view.
1040 //
1041 // It's used in the default callback for "mousemove" operations.
1042 // Custom interaction model builders can use it to provide the default
1043 // panning behavior.
1044 //
1045 Dygraph.movePan = function(event, g, context) {
1046 context.dragEndX = g.dragGetX_(event, context);
1047 context.dragEndY = g.dragGetY_(event, context);
1048
1049 var minDate = context.initialLeftmostDate -
1050 (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
1051 var maxDate = minDate + context.dateRange;
1052 g.dateWindow_ = [minDate, maxDate];
1053
1054 // y-axis scaling is automatic unless this is a full 2D pan.
1055 if (context.is2DPan) {
1056 // Adjust each axis appropriately.
1057 for (var i = 0; i < g.axes_.length; i++) {
1058 var axis = g.axes_[i];
1059
1060 var pixelsDragged = context.dragEndY - context.dragStartY;
1061 var unitsDragged = pixelsDragged * axis.unitsPerPixel;
1062
1063 // In log scale, maxValue and minValue are the logs of those values.
1064 var maxValue = axis.initialTopValue + unitsDragged;
1065 var minValue = maxValue - axis.dragValueRange;
1066 if (axis.logscale) {
1067 axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue),
1068 Math.pow(Dygraph.LOG_SCALE, maxValue) ];
1069 } else {
1070 axis.valueWindow = [ minValue, maxValue ];
1071 }
1072 }
1073 }
1074
1075 g.drawGraph_();
1076 }
1077
1078 // Called in response to an interaction model operation that
1079 // responds to an event that ends panning.
1080 //
1081 // It's used in the default callback for "mouseup" operations.
1082 // Custom interaction model builders can use it to provide the default
1083 // panning behavior.
1084 //
1085 Dygraph.endPan = function(event, g, context) {
1086 // TODO(konigsberg): Clear the context data from the axis.
1087 // TODO(konigsberg): mouseup should just delete the
1088 // context object, and mousedown should create a new one.
1089 context.isPanning = false;
1090 context.is2DPan = false;
1091 context.initialLeftmostDate = null;
1092 context.dateRange = null;
1093 context.valueRange = null;
1094 }
1095
1096 // Called in response to an interaction model operation that
1097 // responds to an event that starts zooming.
1098 //
1099 // It's used in the default callback for "mousedown" operations.
1100 // Custom interaction model builders can use it to provide the default
1101 // zooming behavior.
1102 //
1103 Dygraph.startZoom = function(event, g, context) {
1104 context.isZooming = true;
1105 }
1106
1107 // Called in response to an interaction model operation that
1108 // responds to an event that defines zoom boundaries.
1109 //
1110 // It's used in the default callback for "mousemove" operations.
1111 // Custom interaction model builders can use it to provide the default
1112 // zooming behavior.
1113 //
1114 Dygraph.moveZoom = function(event, g, context) {
1115 context.dragEndX = g.dragGetX_(event, context);
1116 context.dragEndY = g.dragGetY_(event, context);
1117
1118 var xDelta = Math.abs(context.dragStartX - context.dragEndX);
1119 var yDelta = Math.abs(context.dragStartY - context.dragEndY);
1120
1121 // drag direction threshold for y axis is twice as large as x axis
1122 context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL;
1123
1124 g.drawZoomRect_(
1125 context.dragDirection,
1126 context.dragStartX,
1127 context.dragEndX,
1128 context.dragStartY,
1129 context.dragEndY,
1130 context.prevDragDirection,
1131 context.prevEndX,
1132 context.prevEndY);
1133
1134 context.prevEndX = context.dragEndX;
1135 context.prevEndY = context.dragEndY;
1136 context.prevDragDirection = context.dragDirection;
1137 }
1138
1139 // Called in response to an interaction model operation that
1140 // responds to an event that performs a zoom based on previously defined
1141 // bounds..
1142 //
1143 // It's used in the default callback for "mouseup" operations.
1144 // Custom interaction model builders can use it to provide the default
1145 // zooming behavior.
1146 //
1147 Dygraph.endZoom = function(event, g, context) {
1148 context.isZooming = false;
1149 context.dragEndX = g.dragGetX_(event, context);
1150 context.dragEndY = g.dragGetY_(event, context);
1151 var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
1152 var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
1153
1154 if (regionWidth < 2 && regionHeight < 2 &&
1155 g.lastx_ != undefined && g.lastx_ != -1) {
1156 // TODO(danvk): pass along more info about the points, e.g. 'x'
1157 if (g.attr_('clickCallback') != null) {
1158 g.attr_('clickCallback')(event, g.lastx_, g.selPoints_);
1159 }
1160 if (g.attr_('pointClickCallback')) {
1161 // check if the click was on a particular point.
1162 var closestIdx = -1;
1163 var closestDistance = 0;
1164 for (var i = 0; i < g.selPoints_.length; i++) {
1165 var p = g.selPoints_[i];
1166 var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
1167 Math.pow(p.canvasy - context.dragEndY, 2);
1168 if (closestIdx == -1 || distance < closestDistance) {
1169 closestDistance = distance;
1170 closestIdx = i;
1171 }
1172 }
1173
1174 // Allow any click within two pixels of the dot.
1175 var radius = g.attr_('highlightCircleSize') + 2;
1176 if (closestDistance <= 5 * 5) {
1177 g.attr_('pointClickCallback')(event, g.selPoints_[closestIdx]);
1178 }
1179 }
1180 }
1181
1182 if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) {
1183 g.doZoomX_(Math.min(context.dragStartX, context.dragEndX),
1184 Math.max(context.dragStartX, context.dragEndX));
1185 } else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) {
1186 g.doZoomY_(Math.min(context.dragStartY, context.dragEndY),
1187 Math.max(context.dragStartY, context.dragEndY));
1188 } else {
1189 g.canvas_.getContext("2d").clearRect(0, 0,
1190 g.canvas_.width,
1191 g.canvas_.height);
1192 }
1193 context.dragStartX = null;
1194 context.dragStartY = null;
1195 }
1196
1197 Dygraph.defaultInteractionModel = {
1198 // Track the beginning of drag events
1199 mousedown: function(event, g, context) {
1200 context.initializeMouseDown(event, g, context);
1201
1202 if (event.altKey || event.shiftKey) {
1203 Dygraph.startPan(event, g, context);
1204 } else {
1205 Dygraph.startZoom(event, g, context);
1206 }
1207 },
1208
1209 // Draw zoom rectangles when the mouse is down and the user moves around
1210 mousemove: function(event, g, context) {
1211 if (context.isZooming) {
1212 Dygraph.moveZoom(event, g, context);
1213 } else if (context.isPanning) {
1214 Dygraph.movePan(event, g, context);
1215 }
1216 },
1217
1218 mouseup: function(event, g, context) {
1219 if (context.isZooming) {
1220 Dygraph.endZoom(event, g, context);
1221 } else if (context.isPanning) {
1222 Dygraph.endPan(event, g, context);
1223 }
1224 },
1225
1226 // Temporarily cancel the dragging event when the mouse leaves the graph
1227 mouseout: function(event, g, context) {
1228 if (context.isZooming) {
1229 context.dragEndX = null;
1230 context.dragEndY = null;
1231 }
1232 },
1233
1234 // Disable zooming out if panning.
1235 dblclick: function(event, g, context) {
1236 if (event.altKey || event.shiftKey) {
1237 return;
1238 }
1239 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1240 // friendlier to public use.
1241 g.doUnzoom_();
1242 }
1243 };
1244
1245 Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.defaultInteractionModel;
1246
1247 /**
1248 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1249 * events.
1250 * @private
1251 */
1252 Dygraph.prototype.createDragInterface_ = function() {
1253 var context = {
1254 // Tracks whether the mouse is down right now
1255 isZooming: false,
1256 isPanning: false, // is this drag part of a pan?
1257 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
1258 dragStartX: null,
1259 dragStartY: null,
1260 dragEndX: null,
1261 dragEndY: null,
1262 dragDirection: null,
1263 prevEndX: null,
1264 prevEndY: null,
1265 prevDragDirection: null,
1266
1267 // The value on the left side of the graph when a pan operation starts.
1268 initialLeftmostDate: null,
1269
1270 // The number of units each pixel spans. (This won't be valid for log
1271 // scales)
1272 xUnitsPerPixel: null,
1273
1274 // TODO(danvk): update this comment
1275 // The range in second/value units that the viewport encompasses during a
1276 // panning operation.
1277 dateRange: null,
1278
1279 // Utility function to convert page-wide coordinates to canvas coords
1280 px: 0,
1281 py: 0,
1282
1283 initializeMouseDown: function(event, g, context) {
1284 // prevents mouse drags from selecting page text.
1285 if (event.preventDefault) {
1286 event.preventDefault(); // Firefox, Chrome, etc.
1287 } else {
1288 event.returnValue = false; // IE
1289 event.cancelBubble = true;
1290 }
1291
1292 context.px = Dygraph.findPosX(g.canvas_);
1293 context.py = Dygraph.findPosY(g.canvas_);
1294 context.dragStartX = g.dragGetX_(event, context);
1295 context.dragStartY = g.dragGetY_(event, context);
1296 }
1297 };
1298
1299 var interactionModel = this.attr_("interactionModel");
1300
1301 // Self is the graph.
1302 var self = this;
1303
1304 // Function that binds the graph and context to the handler.
1305 var bindHandler = function(handler) {
1306 return function(event) {
1307 handler(event, self, context);
1308 };
1309 };
1310
1311 for (var eventName in interactionModel) {
1312 if (!interactionModel.hasOwnProperty(eventName)) continue;
1313 Dygraph.addEvent(this.mouseEventElement_, eventName,
1314 bindHandler(interactionModel[eventName]));
1315 }
1316
1317 // If the user releases the mouse button during a drag, but not over the
1318 // canvas, then it doesn't count as a zooming action.
1319 Dygraph.addEvent(document, 'mouseup', function(event) {
1320 if (context.isZooming || context.isPanning) {
1321 context.isZooming = false;
1322 context.dragStartX = null;
1323 context.dragStartY = null;
1324 }
1325
1326 if (context.isPanning) {
1327 context.isPanning = false;
1328 context.draggingDate = null;
1329 context.dateRange = null;
1330 for (var i = 0; i < self.axes_.length; i++) {
1331 delete self.axes_[i].draggingValue;
1332 delete self.axes_[i].dragValueRange;
1333 }
1334 }
1335 });
1336 };
1337
1338
1339 /**
1340 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1341 * up any previous zoom rectangles that were drawn. This could be optimized to
1342 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1343 * dots.
1344 *
1345 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1346 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1347 * @param {Number} startX The X position where the drag started, in canvas
1348 * coordinates.
1349 * @param {Number} endX The current X position of the drag, in canvas coords.
1350 * @param {Number} startY The Y position where the drag started, in canvas
1351 * coordinates.
1352 * @param {Number} endY The current Y position of the drag, in canvas coords.
1353 * @param {Number} prevDirection the value of direction on the previous call to
1354 * this function. Used to avoid excess redrawing
1355 * @param {Number} prevEndX The value of endX on the previous call to this
1356 * function. Used to avoid excess redrawing
1357 * @param {Number} prevEndY The value of endY on the previous call to this
1358 * function. Used to avoid excess redrawing
1359 * @private
1360 */
1361 Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1362 endY, prevDirection, prevEndX,
1363 prevEndY) {
1364 var ctx = this.canvas_.getContext("2d");
1365
1366 // Clean up from the previous rect if necessary
1367 if (prevDirection == Dygraph.HORIZONTAL) {
1368 ctx.clearRect(Math.min(startX, prevEndX), 0,
1369 Math.abs(startX - prevEndX), this.height_);
1370 } else if (prevDirection == Dygraph.VERTICAL){
1371 ctx.clearRect(0, Math.min(startY, prevEndY),
1372 this.width_, Math.abs(startY - prevEndY));
1373 }
1374
1375 // Draw a light-grey rectangle to show the new viewing area
1376 if (direction == Dygraph.HORIZONTAL) {
1377 if (endX && startX) {
1378 ctx.fillStyle = "rgba(128,128,128,0.33)";
1379 ctx.fillRect(Math.min(startX, endX), 0,
1380 Math.abs(endX - startX), this.height_);
1381 }
1382 }
1383 if (direction == Dygraph.VERTICAL) {
1384 if (endY && startY) {
1385 ctx.fillStyle = "rgba(128,128,128,0.33)";
1386 ctx.fillRect(0, Math.min(startY, endY),
1387 this.width_, Math.abs(endY - startY));
1388 }
1389 }
1390 };
1391
1392 /**
1393 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1394 * the canvas. The exact zoom window may be slightly larger if there are no data
1395 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1396 * which accepts dates that match the raw data. This function redraws the graph.
1397 *
1398 * @param {Number} lowX The leftmost pixel value that should be visible.
1399 * @param {Number} highX The rightmost pixel value that should be visible.
1400 * @private
1401 */
1402 Dygraph.prototype.doZoomX_ = function(lowX, highX) {
1403 // Find the earliest and latest dates contained in this canvasx range.
1404 // Convert the call to date ranges of the raw data.
1405 var minDate = this.toDataXCoord(lowX);
1406 var maxDate = this.toDataXCoord(highX);
1407 this.doZoomXDates_(minDate, maxDate);
1408 };
1409
1410 /**
1411 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1412 * method with doZoomX which accepts pixel coordinates. This function redraws
1413 * the graph.
1414 *
1415 * @param {Number} minDate The minimum date that should be visible.
1416 * @param {Number} maxDate The maximum date that should be visible.
1417 * @private
1418 */
1419 Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
1420 this.dateWindow_ = [minDate, maxDate];
1421 this.drawGraph_();
1422 if (this.attr_("zoomCallback")) {
1423 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
1424 }
1425 };
1426
1427 /**
1428 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1429 * the canvas. This function redraws the graph.
1430 *
1431 * @param {Number} lowY The topmost pixel value that should be visible.
1432 * @param {Number} highY The lowest pixel value that should be visible.
1433 * @private
1434 */
1435 Dygraph.prototype.doZoomY_ = function(lowY, highY) {
1436 // Find the highest and lowest values in pixel range for each axis.
1437 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1438 // This is because pixels increase as you go down on the screen, whereas data
1439 // coordinates increase as you go up the screen.
1440 var valueRanges = [];
1441 for (var i = 0; i < this.axes_.length; i++) {
1442 var hi = this.toDataYCoord(lowY, i);
1443 var low = this.toDataYCoord(highY, i);
1444 this.axes_[i].valueWindow = [low, hi];
1445 valueRanges.push([low, hi]);
1446 }
1447
1448 this.drawGraph_();
1449 if (this.attr_("zoomCallback")) {
1450 var xRange = this.xAxisRange();
1451 this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges());
1452 }
1453 };
1454
1455 /**
1456 * Reset the zoom to the original view coordinates. This is the same as
1457 * double-clicking on the graph.
1458 *
1459 * @private
1460 */
1461 Dygraph.prototype.doUnzoom_ = function() {
1462 var dirty = false;
1463 if (this.dateWindow_ != null) {
1464 dirty = true;
1465 this.dateWindow_ = null;
1466 }
1467
1468 for (var i = 0; i < this.axes_.length; i++) {
1469 if (this.axes_[i].valueWindow != null) {
1470 dirty = true;
1471 delete this.axes_[i].valueWindow;
1472 }
1473 }
1474
1475 if (dirty) {
1476 // Putting the drawing operation before the callback because it resets
1477 // yAxisRange.
1478 this.drawGraph_();
1479 if (this.attr_("zoomCallback")) {
1480 var minDate = this.rawData_[0][0];
1481 var maxDate = this.rawData_[this.rawData_.length - 1][0];
1482 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
1483 }
1484 }
1485 };
1486
1487 /**
1488 * When the mouse moves in the canvas, display information about a nearby data
1489 * point and draw dots over those points in the data series. This function
1490 * takes care of cleanup of previously-drawn dots.
1491 * @param {Object} event The mousemove event from the browser.
1492 * @private
1493 */
1494 Dygraph.prototype.mouseMove_ = function(event) {
1495 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
1496 var points = this.layout_.points;
1497
1498 // This prevents JS errors when mousing over the canvas before data loads.
1499 if (points === undefined) return;
1500
1501 var lastx = -1;
1502 var lasty = -1;
1503
1504 // Loop through all the points and find the date nearest to our current
1505 // location.
1506 var minDist = 1e+100;
1507 var idx = -1;
1508 for (var i = 0; i < points.length; i++) {
1509 var point = points[i];
1510 if (point == null) continue;
1511 var dist = Math.abs(point.canvasx - canvasx);
1512 if (dist > minDist) continue;
1513 minDist = dist;
1514 idx = i;
1515 }
1516 if (idx >= 0) lastx = points[idx].xval;
1517
1518 // Extract the points we've selected
1519 this.selPoints_ = [];
1520 var l = points.length;
1521 if (!this.attr_("stackedGraph")) {
1522 for (var i = 0; i < l; i++) {
1523 if (points[i].xval == lastx) {
1524 this.selPoints_.push(points[i]);
1525 }
1526 }
1527 } else {
1528 // Need to 'unstack' points starting from the bottom
1529 var cumulative_sum = 0;
1530 for (var i = l - 1; i >= 0; i--) {
1531 if (points[i].xval == lastx) {
1532 var p = {}; // Clone the point since we modify it
1533 for (var k in points[i]) {
1534 p[k] = points[i][k];
1535 }
1536 p.yval -= cumulative_sum;
1537 cumulative_sum += p.yval;
1538 this.selPoints_.push(p);
1539 }
1540 }
1541 this.selPoints_.reverse();
1542 }
1543
1544 if (this.attr_("highlightCallback")) {
1545 var px = this.lastx_;
1546 if (px !== null && lastx != px) {
1547 // only fire if the selected point has changed.
1548 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
1549 }
1550 }
1551
1552 // Save last x position for callbacks.
1553 this.lastx_ = lastx;
1554
1555 this.updateSelection_();
1556 };
1557
1558 /**
1559 * Transforms layout_.points index into data row number.
1560 * @param int layout_.points index
1561 * @return int row number, or -1 if none could be found.
1562 * @private
1563 */
1564 Dygraph.prototype.idxToRow_ = function(idx) {
1565 if (idx < 0) return -1;
1566
1567 for (var i in this.layout_.datasets) {
1568 if (idx < this.layout_.datasets[i].length) {
1569 return this.boundaryIds_[0][0]+idx;
1570 }
1571 idx -= this.layout_.datasets[i].length;
1572 }
1573 return -1;
1574 };
1575
1576 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
1577 Dygraph.isOK = function(x) {
1578 return x && !isNaN(x);
1579 };
1580
1581 Dygraph.prototype.generateLegendHTML_ = function(x, sel_points) {
1582 // If no points are selected, we display a default legend. Traditionally,
1583 // this has been blank. But a better default would be a conventional legend,
1584 // which provides essential information for a non-interactive chart.
1585 if (typeof(x) === 'undefined') {
1586 if (this.attr_('legend') != 'always') return '';
1587
1588 var sepLines = this.attr_('labelsSeparateLines');
1589 var labels = this.attr_('labels');
1590 var html = '';
1591 for (var i = 1; i < labels.length; i++) {
1592 var c = new RGBColor(this.plotter_.colors[labels[i]]);
1593 if (i > 1) html += (sepLines ? '<br/>' : ' ');
1594 html += "<b><font color='" + c.toHex() + "'>&mdash;" + labels[i] +
1595 "</font></b>";
1596 }
1597 return html;
1598 }
1599
1600 var displayDigits = this.numXDigits_ + this.numExtraDigits_;
1601 var html = this.attr_('xValueFormatter')(x, displayDigits) + ":";
1602
1603 var fmtFunc = this.attr_('yValueFormatter');
1604 var showZeros = this.attr_("labelsShowZeroValues");
1605 var sepLines = this.attr_("labelsSeparateLines");
1606 for (var i = 0; i < this.selPoints_.length; i++) {
1607 var pt = this.selPoints_[i];
1608 if (pt.yval == 0 && !showZeros) continue;
1609 if (!Dygraph.isOK(pt.canvasy)) continue;
1610 if (sepLines) html += "<br/>";
1611
1612 var c = new RGBColor(this.plotter_.colors[pt.name]);
1613 var yval = fmtFunc(pt.yval, displayDigits);
1614 // TODO(danvk): use a template string here and make it an attribute.
1615 html += " <b><font color='" + c.toHex() + "'>"
1616 + pt.name + "</font></b>:"
1617 + yval;
1618 }
1619 return html;
1620 };
1621
1622 /**
1623 * Draw dots over the selectied points in the data series. This function
1624 * takes care of cleanup of previously-drawn dots.
1625 * @private
1626 */
1627 Dygraph.prototype.updateSelection_ = function() {
1628 // Clear the previously drawn vertical, if there is one
1629 var ctx = this.canvas_.getContext("2d");
1630 if (this.previousVerticalX_ >= 0) {
1631 // Determine the maximum highlight circle size.
1632 var maxCircleSize = 0;
1633 var labels = this.attr_('labels');
1634 for (var i = 1; i < labels.length; i++) {
1635 var r = this.attr_('highlightCircleSize', labels[i]);
1636 if (r > maxCircleSize) maxCircleSize = r;
1637 }
1638 var px = this.previousVerticalX_;
1639 ctx.clearRect(px - maxCircleSize - 1, 0,
1640 2 * maxCircleSize + 2, this.height_);
1641 }
1642
1643 if (this.selPoints_.length > 0) {
1644 // Set the status message to indicate the selected point(s)
1645 if (this.attr_('showLabelsOnHighlight')) {
1646 var html = this.generateLegendHTML_(this.lastx_, this.selPoints_);
1647 this.attr_("labelsDiv").innerHTML = html;
1648 }
1649
1650 // Draw colored circles over the center of each selected point
1651 var canvasx = this.selPoints_[0].canvasx;
1652 ctx.save();
1653 for (var i = 0; i < this.selPoints_.length; i++) {
1654 var pt = this.selPoints_[i];
1655 if (!Dygraph.isOK(pt.canvasy)) continue;
1656
1657 var circleSize = this.attr_('highlightCircleSize', pt.name);
1658 ctx.beginPath();
1659 ctx.fillStyle = this.plotter_.colors[pt.name];
1660 ctx.arc(canvasx, pt.canvasy, circleSize, 0, 2 * Math.PI, false);
1661 ctx.fill();
1662 }
1663 ctx.restore();
1664
1665 this.previousVerticalX_ = canvasx;
1666 }
1667 };
1668
1669 /**
1670 * Set manually set selected dots, and display information about them
1671 * @param int row number that should by highlighted
1672 * false value clears the selection
1673 * @public
1674 */
1675 Dygraph.prototype.setSelection = function(row) {
1676 // Extract the points we've selected
1677 this.selPoints_ = [];
1678 var pos = 0;
1679
1680 if (row !== false) {
1681 row = row-this.boundaryIds_[0][0];
1682 }
1683
1684 if (row !== false && row >= 0) {
1685 for (var i in this.layout_.datasets) {
1686 if (row < this.layout_.datasets[i].length) {
1687 var point = this.layout_.points[pos+row];
1688
1689 if (this.attr_("stackedGraph")) {
1690 point = this.layout_.unstackPointAtIndex(pos+row);
1691 }
1692
1693 this.selPoints_.push(point);
1694 }
1695 pos += this.layout_.datasets[i].length;
1696 }
1697 }
1698
1699 if (this.selPoints_.length) {
1700 this.lastx_ = this.selPoints_[0].xval;
1701 this.updateSelection_();
1702 } else {
1703 this.lastx_ = -1;
1704 this.clearSelection();
1705 }
1706
1707 };
1708
1709 /**
1710 * The mouse has left the canvas. Clear out whatever artifacts remain
1711 * @param {Object} event the mouseout event from the browser.
1712 * @private
1713 */
1714 Dygraph.prototype.mouseOut_ = function(event) {
1715 if (this.attr_("unhighlightCallback")) {
1716 this.attr_("unhighlightCallback")(event);
1717 }
1718
1719 if (this.attr_("hideOverlayOnMouseOut")) {
1720 this.clearSelection();
1721 }
1722 };
1723
1724 /**
1725 * Remove all selection from the canvas
1726 * @public
1727 */
1728 Dygraph.prototype.clearSelection = function() {
1729 // Get rid of the overlay data
1730 var ctx = this.canvas_.getContext("2d");
1731 ctx.clearRect(0, 0, this.width_, this.height_);
1732 this.attr_('labelsDiv').innerHTML = this.generateLegendHTML_();
1733 this.selPoints_ = [];
1734 this.lastx_ = -1;
1735 }
1736
1737 /**
1738 * Returns the number of the currently selected row
1739 * @return int row number, of -1 if nothing is selected
1740 * @public
1741 */
1742 Dygraph.prototype.getSelection = function() {
1743 if (!this.selPoints_ || this.selPoints_.length < 1) {
1744 return -1;
1745 }
1746
1747 for (var row=0; row<this.layout_.points.length; row++ ) {
1748 if (this.layout_.points[row].x == this.selPoints_[0].x) {
1749 return row + this.boundaryIds_[0][0];
1750 }
1751 }
1752 return -1;
1753 }
1754
1755 Dygraph.zeropad = function(x) {
1756 if (x < 10) return "0" + x; else return "" + x;
1757 }
1758
1759 /**
1760 * Return a string version of the hours, minutes and seconds portion of a date.
1761 * @param {Number} date The JavaScript date (ms since epoch)
1762 * @return {String} A time of the form "HH:MM:SS"
1763 * @private
1764 */
1765 Dygraph.hmsString_ = function(date) {
1766 var zeropad = Dygraph.zeropad;
1767 var d = new Date(date);
1768 if (d.getSeconds()) {
1769 return zeropad(d.getHours()) + ":" +
1770 zeropad(d.getMinutes()) + ":" +
1771 zeropad(d.getSeconds());
1772 } else {
1773 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
1774 }
1775 }
1776
1777 /**
1778 * Convert a JS date to a string appropriate to display on an axis that
1779 * is displaying values at the stated granularity.
1780 * @param {Date} date The date to format
1781 * @param {Number} granularity One of the Dygraph granularity constants
1782 * @return {String} The formatted date
1783 * @private
1784 */
1785 Dygraph.dateAxisFormatter = function(date, granularity) {
1786 if (granularity >= Dygraph.DECADAL) {
1787 return date.strftime('%Y');
1788 } else if (granularity >= Dygraph.MONTHLY) {
1789 return date.strftime('%b %y');
1790 } else {
1791 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
1792 if (frac == 0 || granularity >= Dygraph.DAILY) {
1793 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
1794 } else {
1795 return Dygraph.hmsString_(date.getTime());
1796 }
1797 }
1798 }
1799
1800 /**
1801 * Convert a JS date (millis since epoch) to YYYY/MM/DD
1802 * @param {Number} date The JavaScript date (ms since epoch)
1803 * @return {String} A date of the form "YYYY/MM/DD"
1804 * @private
1805 */
1806 Dygraph.dateString_ = function(date) {
1807 var zeropad = Dygraph.zeropad;
1808 var d = new Date(date);
1809
1810 // Get the year:
1811 var year = "" + d.getFullYear();
1812 // Get a 0 padded month string
1813 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
1814 // Get a 0 padded day string
1815 var day = zeropad(d.getDate());
1816
1817 var ret = "";
1818 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
1819 if (frac) ret = " " + Dygraph.hmsString_(date);
1820
1821 return year + "/" + month + "/" + day + ret;
1822 };
1823
1824 /**
1825 * Fires when there's data available to be graphed.
1826 * @param {String} data Raw CSV data to be plotted
1827 * @private
1828 */
1829 Dygraph.prototype.loadedEvent_ = function(data) {
1830 this.rawData_ = this.parseCSV_(data);
1831 this.predraw_();
1832 };
1833
1834 Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
1835 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1836 Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
1837
1838 /**
1839 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1840 * @private
1841 */
1842 Dygraph.prototype.addXTicks_ = function() {
1843 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1844 var range;
1845 if (this.dateWindow_) {
1846 range = [this.dateWindow_[0], this.dateWindow_[1]];
1847 } else {
1848 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
1849 }
1850
1851 var formatter = this.attr_('xTicker');
1852 var ret = formatter(range[0], range[1], this);
1853 var xTicks = [];
1854
1855 // Note: numericTicks() returns a {ticks: [...], numDigits: yy} dictionary,
1856 // whereas dateTicker and user-defined tickers typically just return a ticks
1857 // array.
1858 if (ret.ticks !== undefined) {
1859 xTicks = ret.ticks;
1860 this.numXDigits_ = ret.numDigits;
1861 } else {
1862 xTicks = ret;
1863 }
1864
1865 this.layout_.updateOptions({xTicks: xTicks});
1866 };
1867
1868 // Time granularity enumeration
1869 Dygraph.SECONDLY = 0;
1870 Dygraph.TWO_SECONDLY = 1;
1871 Dygraph.FIVE_SECONDLY = 2;
1872 Dygraph.TEN_SECONDLY = 3;
1873 Dygraph.THIRTY_SECONDLY = 4;
1874 Dygraph.MINUTELY = 5;
1875 Dygraph.TWO_MINUTELY = 6;
1876 Dygraph.FIVE_MINUTELY = 7;
1877 Dygraph.TEN_MINUTELY = 8;
1878 Dygraph.THIRTY_MINUTELY = 9;
1879 Dygraph.HOURLY = 10;
1880 Dygraph.TWO_HOURLY = 11;
1881 Dygraph.SIX_HOURLY = 12;
1882 Dygraph.DAILY = 13;
1883 Dygraph.WEEKLY = 14;
1884 Dygraph.MONTHLY = 15;
1885 Dygraph.QUARTERLY = 16;
1886 Dygraph.BIANNUAL = 17;
1887 Dygraph.ANNUAL = 18;
1888 Dygraph.DECADAL = 19;
1889 Dygraph.CENTENNIAL = 20;
1890 Dygraph.NUM_GRANULARITIES = 21;
1891
1892 Dygraph.SHORT_SPACINGS = [];
1893 Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
1894 Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
1895 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
1896 Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
1897 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
1898 Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
1899 Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
1900 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
1901 Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
1902 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
1903 Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
1904 Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
1905 Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
1906 Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
1907 Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
1908
1909 // NumXTicks()
1910 //
1911 // If we used this time granularity, how many ticks would there be?
1912 // This is only an approximation, but it's generally good enough.
1913 //
1914 Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
1915 if (granularity < Dygraph.MONTHLY) {
1916 // Generate one tick mark for every fixed interval of time.
1917 var spacing = Dygraph.SHORT_SPACINGS[granularity];
1918 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
1919 } else {
1920 var year_mod = 1; // e.g. to only print one point every 10 years.
1921 var num_months = 12;
1922 if (granularity == Dygraph.QUARTERLY) num_months = 3;
1923 if (granularity == Dygraph.BIANNUAL) num_months = 2;
1924 if (granularity == Dygraph.ANNUAL) num_months = 1;
1925 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
1926 if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
1927
1928 var msInYear = 365.2524 * 24 * 3600 * 1000;
1929 var num_years = 1.0 * (end_time - start_time) / msInYear;
1930 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
1931 }
1932 };
1933
1934 // GetXAxis()
1935 //
1936 // Construct an x-axis of nicely-formatted times on meaningful boundaries
1937 // (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1938 //
1939 // Returns an array containing {v: millis, label: label} dictionaries.
1940 //
1941 Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
1942 var formatter = this.attr_("xAxisLabelFormatter");
1943 var ticks = [];
1944 if (granularity < Dygraph.MONTHLY) {
1945 // Generate one tick mark for every fixed interval of time.
1946 var spacing = Dygraph.SHORT_SPACINGS[granularity];
1947 var format = '%d%b'; // e.g. "1Jan"
1948
1949 // Find a time less than start_time which occurs on a "nice" time boundary
1950 // for this granularity.
1951 var g = spacing / 1000;
1952 var d = new Date(start_time);
1953 if (g <= 60) { // seconds
1954 var x = d.getSeconds(); d.setSeconds(x - x % g);
1955 } else {
1956 d.setSeconds(0);
1957 g /= 60;
1958 if (g <= 60) { // minutes
1959 var x = d.getMinutes(); d.setMinutes(x - x % g);
1960 } else {
1961 d.setMinutes(0);
1962 g /= 60;
1963
1964 if (g <= 24) { // days
1965 var x = d.getHours(); d.setHours(x - x % g);
1966 } else {
1967 d.setHours(0);
1968 g /= 24;
1969
1970 if (g == 7) { // one week
1971 d.setDate(d.getDate() - d.getDay());
1972 }
1973 }
1974 }
1975 }
1976 start_time = d.getTime();
1977
1978 for (var t = start_time; t <= end_time; t += spacing) {
1979 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
1980 }
1981 } else {
1982 // Display a tick mark on the first of a set of months of each year.
1983 // Years get a tick mark iff y % year_mod == 0. This is useful for
1984 // displaying a tick mark once every 10 years, say, on long time scales.
1985 var months;
1986 var year_mod = 1; // e.g. to only print one point every 10 years.
1987
1988 if (granularity == Dygraph.MONTHLY) {
1989 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
1990 } else if (granularity == Dygraph.QUARTERLY) {
1991 months = [ 0, 3, 6, 9 ];
1992 } else if (granularity == Dygraph.BIANNUAL) {
1993 months = [ 0, 6 ];
1994 } else if (granularity == Dygraph.ANNUAL) {
1995 months = [ 0 ];
1996 } else if (granularity == Dygraph.DECADAL) {
1997 months = [ 0 ];
1998 year_mod = 10;
1999 } else if (granularity == Dygraph.CENTENNIAL) {
2000 months = [ 0 ];
2001 year_mod = 100;
2002 } else {
2003 this.warn("Span of dates is too long");
2004 }
2005
2006 var start_year = new Date(start_time).getFullYear();
2007 var end_year = new Date(end_time).getFullYear();
2008 var zeropad = Dygraph.zeropad;
2009 for (var i = start_year; i <= end_year; i++) {
2010 if (i % year_mod != 0) continue;
2011 for (var j = 0; j < months.length; j++) {
2012 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
2013 var t = Date.parse(date_str);
2014 if (t < start_time || t > end_time) continue;
2015 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
2016 }
2017 }
2018 }
2019
2020 return ticks;
2021 };
2022
2023
2024 /**
2025 * Add ticks to the x-axis based on a date range.
2026 * @param {Number} startDate Start of the date window (millis since epoch)
2027 * @param {Number} endDate End of the date window (millis since epoch)
2028 * @return {Array.<Object>} Array of {label, value} tuples.
2029 * @public
2030 */
2031 Dygraph.dateTicker = function(startDate, endDate, self) {
2032 var chosen = -1;
2033 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
2034 var num_ticks = self.NumXTicks(startDate, endDate, i);
2035 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
2036 chosen = i;
2037 break;
2038 }
2039 }
2040
2041 if (chosen >= 0) {
2042 return self.GetXAxis(startDate, endDate, chosen);
2043 } else {
2044 // TODO(danvk): signal error.
2045 }
2046 };
2047
2048 // This is a list of human-friendly values at which to show tick marks on a log
2049 // scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
2050 // ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
2051 // NOTE: this assumes that Dygraph.LOG_SCALE = 10.
2052 Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
2053 var vals = [];
2054 for (var power = -39; power <= 39; power++) {
2055 var range = Math.pow(10, power);
2056 for (var mult = 1; mult <= 9; mult++) {
2057 var val = range * mult;
2058 vals.push(val);
2059 }
2060 }
2061 return vals;
2062 }();
2063
2064 // val is the value to search for
2065 // arry is the value over which to search
2066 // if abs > 0, find the lowest entry greater than val
2067 // if abs < 0, find the highest entry less than val
2068 // if abs == 0, find the entry that equals val.
2069 // Currently does not work when val is outside the range of arry's values.
2070 Dygraph.binarySearch = function(val, arry, abs, low, high) {
2071 if (low == null || high == null) {
2072 low = 0;
2073 high = arry.length - 1;
2074 }
2075 if (low > high) {
2076 return -1;
2077 }
2078 if (abs == null) {
2079 abs = 0;
2080 }
2081 var validIndex = function(idx) {
2082 return idx >= 0 && idx < arry.length;
2083 }
2084 var mid = parseInt((low + high) / 2);
2085 var element = arry[mid];
2086 if (element == val) {
2087 return mid;
2088 }
2089 if (element > val) {
2090 if (abs > 0) {
2091 // Accept if element > val, but also if prior element < val.
2092 var idx = mid - 1;
2093 if (validIndex(idx) && arry[idx] < val) {
2094 return mid;
2095 }
2096 }
2097 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
2098 }
2099 if (element < val) {
2100 if (abs < 0) {
2101 // Accept if element < val, but also if prior element > val.
2102 var idx = mid + 1;
2103 if (validIndex(idx) && arry[idx] > val) {
2104 return mid;
2105 }
2106 }
2107 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
2108 }
2109 };
2110
2111 /**
2112 * Determine the number of significant figures in a Number up to the specified
2113 * precision. Note that there is no way to determine if a trailing '0' is
2114 * significant or not, so by convention we return 1 for all of the following
2115 * inputs: 1, 1.0, 1.00, 1.000 etc.
2116 * @param {Number} x The input value.
2117 * @param {Number} opt_maxPrecision Optional maximum precision to consider.
2118 * Default and maximum allowed value is 13.
2119 * @return {Number} The number of significant figures which is >= 1.
2120 */
2121 Dygraph.significantFigures = function(x, opt_maxPrecision) {
2122 var precision = Math.max(opt_maxPrecision || 13, 13);
2123
2124 // Convert the number to its exponential notation form and work backwards,
2125 // ignoring the 'e+xx' bit. This may seem like a hack, but doing a loop and
2126 // dividing by 10 leads to roundoff errors. By using toExponential(), we let
2127 // the JavaScript interpreter handle the low level bits of the Number for us.
2128 var s = x.toExponential(precision);
2129 var ePos = s.lastIndexOf('e'); // -1 case handled by return below.
2130
2131 for (var i = ePos - 1; i >= 0; i--) {
2132 if (s[i] == '.') {
2133 // Got to the decimal place. We'll call this 1 digit of precision because
2134 // we can't know for sure how many trailing 0s are significant.
2135 return 1;
2136 } else if (s[i] != '0') {
2137 // Found the first non-zero digit. Return the number of characters
2138 // except for the '.'.
2139 return i; // This is i - 1 + 1 (-1 is for '.', +1 is for 0 based index).
2140 }
2141 }
2142
2143 // Occurs if toExponential() doesn't return a string containing 'e', which
2144 // should never happen.
2145 return 1;
2146 };
2147
2148 /**
2149 * Add ticks when the x axis has numbers on it (instead of dates)
2150 * TODO(konigsberg): Update comment.
2151 *
2152 * @param {Number} minV minimum value
2153 * @param {Number} maxV maximum value
2154 * @param self
2155 * @param {function} attribute accessor function.
2156 * @return {Array.<Object>} Array of {label, value} tuples.
2157 * @public
2158 */
2159 Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
2160 var attr = function(k) {
2161 if (axis_props && axis_props.hasOwnProperty(k)) return axis_props[k];
2162 return self.attr_(k);
2163 };
2164
2165 var ticks = [];
2166 if (vals) {
2167 for (var i = 0; i < vals.length; i++) {
2168 ticks.push({v: vals[i]});
2169 }
2170 } else {
2171 if (axis_props && attr("logscale")) {
2172 var pixelsPerTick = attr('pixelsPerYLabel');
2173 // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
2174 var nTicks = Math.floor(self.height_ / pixelsPerTick);
2175 var minIdx = Dygraph.binarySearch(minV, Dygraph.PREFERRED_LOG_TICK_VALUES, 1);
2176 var maxIdx = Dygraph.binarySearch(maxV, Dygraph.PREFERRED_LOG_TICK_VALUES, -1);
2177 if (minIdx == -1) {
2178 minIdx = 0;
2179 }
2180 if (maxIdx == -1) {
2181 maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1;
2182 }
2183 // Count the number of tick values would appear, if we can get at least
2184 // nTicks / 4 accept them.
2185 var lastDisplayed = null;
2186 if (maxIdx - minIdx >= nTicks / 4) {
2187 var axisId = axis_props.yAxisId;
2188 for (var idx = maxIdx; idx >= minIdx; idx--) {
2189 var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx];
2190 var domCoord = axis_props.g.toDomYCoord(tickValue, axisId);
2191 var tick = { v: tickValue };
2192 if (lastDisplayed == null) {
2193 lastDisplayed = {
2194 tickValue : tickValue,
2195 domCoord : domCoord
2196 };
2197 } else {
2198 if (domCoord - lastDisplayed.domCoord >= pixelsPerTick) {
2199 lastDisplayed = {
2200 tickValue : tickValue,
2201 domCoord : domCoord
2202 };
2203 } else {
2204 tick.label = "";
2205 }
2206 }
2207 ticks.push(tick);
2208 }
2209 // Since we went in backwards order.
2210 ticks.reverse();
2211 }
2212 }
2213
2214 // ticks.length won't be 0 if the log scale function finds values to insert.
2215 if (ticks.length == 0) {
2216 // Basic idea:
2217 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
2218 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
2219 // The first spacing greater than pixelsPerYLabel is what we use.
2220 // TODO(danvk): version that works on a log scale.
2221 if (attr("labelsKMG2")) {
2222 var mults = [1, 2, 4, 8];
2223 } else {
2224 var mults = [1, 2, 5];
2225 }
2226 var scale, low_val, high_val, nTicks;
2227 // TODO(danvk): make it possible to set this for x- and y-axes independently.
2228 var pixelsPerTick = attr('pixelsPerYLabel');
2229 for (var i = -10; i < 50; i++) {
2230 if (attr("labelsKMG2")) {
2231 var base_scale = Math.pow(16, i);
2232 } else {
2233 var base_scale = Math.pow(10, i);
2234 }
2235 for (var j = 0; j < mults.length; j++) {
2236 scale = base_scale * mults[j];
2237 low_val = Math.floor(minV / scale) * scale;
2238 high_val = Math.ceil(maxV / scale) * scale;
2239 nTicks = Math.abs(high_val - low_val) / scale;
2240 var spacing = self.height_ / nTicks;
2241 // wish I could break out of both loops at once...
2242 if (spacing > pixelsPerTick) break;
2243 }
2244 if (spacing > pixelsPerTick) break;
2245 }
2246
2247 // Construct the set of ticks.
2248 // Allow reverse y-axis if it's explicitly requested.
2249 if (low_val > high_val) scale *= -1;
2250 for (var i = 0; i < nTicks; i++) {
2251 var tickV = low_val + i * scale;
2252 ticks.push( {v: tickV} );
2253 }
2254 }
2255 }
2256
2257 // Add formatted labels to the ticks.
2258 var k;
2259 var k_labels = [];
2260 if (attr("labelsKMB")) {
2261 k = 1000;
2262 k_labels = [ "K", "M", "B", "T" ];
2263 }
2264 if (attr("labelsKMG2")) {
2265 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
2266 k = 1024;
2267 k_labels = [ "k", "M", "G", "T" ];
2268 }
2269 var formatter = attr('yAxisLabelFormatter') ?
2270 attr('yAxisLabelFormatter') : attr('yValueFormatter');
2271
2272 // Determine the number of decimal places needed for the labels below by
2273 // taking the maximum number of significant figures for any label. We must
2274 // take the max because we can't tell if trailing 0s are significant.
2275 var numDigits = 0;
2276 for (var i = 0; i < ticks.length; i++) {
2277 numDigits = Math.max(Dygraph.significantFigures(ticks[i].v), numDigits);
2278 }
2279
2280 // Add labels to the ticks.
2281 for (var i = 0; i < ticks.length; i++) {
2282 if (ticks[i].label !== undefined) continue; // Use current label.
2283 var tickV = ticks[i].v;
2284 var absTickV = Math.abs(tickV);
2285 var label = (formatter !== undefined) ?
2286 formatter(tickV, numDigits) : tickV.toPrecision(numDigits);
2287 if (k_labels.length > 0) {
2288 // Round up to an appropriate unit.
2289 var n = k*k*k*k;
2290 for (var j = 3; j >= 0; j--, n /= k) {
2291 if (absTickV >= n) {
2292 label = formatter(tickV / n, numDigits) + k_labels[j];
2293 break;
2294 }
2295 }
2296 }
2297 ticks[i].label = label;
2298 }
2299
2300 return {ticks: ticks, numDigits: numDigits};
2301 };
2302
2303 // Computes the range of the data series (including confidence intervals).
2304 // series is either [ [x1, y1], [x2, y2], ... ] or
2305 // [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2306 // Returns [low, high]
2307 Dygraph.prototype.extremeValues_ = function(series) {
2308 var minY = null, maxY = null;
2309
2310 var bars = this.attr_("errorBars") || this.attr_("customBars");
2311 if (bars) {
2312 // With custom bars, maxY is the max of the high values.
2313 for (var j = 0; j < series.length; j++) {
2314 var y = series[j][1][0];
2315 if (!y) continue;
2316 var low = y - series[j][1][1];
2317 var high = y + series[j][1][2];
2318 if (low > y) low = y; // this can happen with custom bars,
2319 if (high < y) high = y; // e.g. in tests/custom-bars.html
2320 if (maxY == null || high > maxY) {
2321 maxY = high;
2322 }
2323 if (minY == null || low < minY) {
2324 minY = low;
2325 }
2326 }
2327 } else {
2328 for (var j = 0; j < series.length; j++) {
2329 var y = series[j][1];
2330 if (y === null || isNaN(y)) continue;
2331 if (maxY == null || y > maxY) {
2332 maxY = y;
2333 }
2334 if (minY == null || y < minY) {
2335 minY = y;
2336 }
2337 }
2338 }
2339
2340 return [minY, maxY];
2341 };
2342
2343 /**
2344 * This function is called once when the chart's data is changed or the options
2345 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2346 * idea is that values derived from the chart's data can be computed here,
2347 * rather than every time the chart is drawn. This includes things like the
2348 * number of axes, rolling averages, etc.
2349 */
2350 Dygraph.prototype.predraw_ = function() {
2351 // TODO(danvk): move more computations out of drawGraph_ and into here.
2352 this.computeYAxes_();
2353
2354 // Create a new plotter.
2355 if (this.plotter_) this.plotter_.clear();
2356 this.plotter_ = new DygraphCanvasRenderer(this,
2357 this.hidden_, this.layout_,
2358 this.renderOptions_);
2359
2360 // The roller sits in the bottom left corner of the chart. We don't know where
2361 // this will be until the options are available, so it's positioned here.
2362 this.createRollInterface_();
2363
2364 // Same thing applies for the labelsDiv. It's right edge should be flush with
2365 // the right edge of the charting area (which may not be the same as the right
2366 // edge of the div, if we have two y-axes.
2367 this.positionLabelsDiv_();
2368
2369 // If the data or options have changed, then we'd better redraw.
2370 this.drawGraph_();
2371 };
2372
2373 /**
2374 * Update the graph with new data. This method is called when the viewing area
2375 * has changed. If the underlying data or options have changed, predraw_ will
2376 * be called before drawGraph_ is called.
2377 * @private
2378 */
2379 Dygraph.prototype.drawGraph_ = function() {
2380 var data = this.rawData_;
2381
2382 // This is used to set the second parameter to drawCallback, below.
2383 var is_initial_draw = this.is_initial_draw_;
2384 this.is_initial_draw_ = false;
2385
2386 var minY = null, maxY = null;
2387 this.layout_.removeAllDatasets();
2388 this.setColors_();
2389 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
2390
2391 // Loop over the fields (series). Go from the last to the first,
2392 // because if they're stacked that's how we accumulate the values.
2393
2394 var cumulative_y = []; // For stacked series.
2395 var datasets = [];
2396
2397 var extremes = {}; // series name -> [low, high]
2398
2399 // Loop over all fields and create datasets
2400 for (var i = data[0].length - 1; i >= 1; i--) {
2401 if (!this.visibility()[i - 1]) continue;
2402
2403 var seriesName = this.attr_("labels")[i];
2404 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
2405 var logScale = this.attr_('logscale', i);
2406
2407 var series = [];
2408 for (var j = 0; j < data.length; j++) {
2409 var date = data[j][0];
2410 var point = data[j][i];
2411 if (logScale) {
2412 // On the log scale, points less than zero do not exist.
2413 // This will create a gap in the chart. Note that this ignores
2414 // connectSeparatedPoints.
2415 if (point <= 0) {
2416 point = null;
2417 }
2418 series.push([date, point]);
2419 } else {
2420 if (point != null || !connectSeparatedPoints) {
2421 series.push([date, point]);
2422 }
2423 }
2424 }
2425
2426 // TODO(danvk): move this into predraw_. It's insane to do it here.
2427 series = this.rollingAverage(series, this.rollPeriod_);
2428
2429 // Prune down to the desired range, if necessary (for zooming)
2430 // Because there can be lines going to points outside of the visible area,
2431 // we actually prune to visible points, plus one on either side.
2432 var bars = this.attr_("errorBars") || this.attr_("customBars");
2433 if (this.dateWindow_) {
2434 var low = this.dateWindow_[0];
2435 var high= this.dateWindow_[1];
2436 var pruned = [];
2437 // TODO(danvk): do binary search instead of linear search.
2438 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2439 var firstIdx = null, lastIdx = null;
2440 for (var k = 0; k < series.length; k++) {
2441 if (series[k][0] >= low && firstIdx === null) {
2442 firstIdx = k;
2443 }
2444 if (series[k][0] <= high) {
2445 lastIdx = k;
2446 }
2447 }
2448 if (firstIdx === null) firstIdx = 0;
2449 if (firstIdx > 0) firstIdx--;
2450 if (lastIdx === null) lastIdx = series.length - 1;
2451 if (lastIdx < series.length - 1) lastIdx++;
2452 this.boundaryIds_[i-1] = [firstIdx, lastIdx];
2453 for (var k = firstIdx; k <= lastIdx; k++) {
2454 pruned.push(series[k]);
2455 }
2456 series = pruned;
2457 } else {
2458 this.boundaryIds_[i-1] = [0, series.length-1];
2459 }
2460
2461 var seriesExtremes = this.extremeValues_(series);
2462
2463 if (bars) {
2464 for (var j=0; j<series.length; j++) {
2465 val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]];
2466 series[j] = val;
2467 }
2468 } else if (this.attr_("stackedGraph")) {
2469 var l = series.length;
2470 var actual_y;
2471 for (var j = 0; j < l; j++) {
2472 // If one data set has a NaN, let all subsequent stacked
2473 // sets inherit the NaN -- only start at 0 for the first set.
2474 var x = series[j][0];
2475 if (cumulative_y[x] === undefined) {
2476 cumulative_y[x] = 0;
2477 }
2478
2479 actual_y = series[j][1];
2480 cumulative_y[x] += actual_y;
2481
2482 series[j] = [x, cumulative_y[x]]
2483
2484 if (cumulative_y[x] > seriesExtremes[1]) {
2485 seriesExtremes[1] = cumulative_y[x];
2486 }
2487 if (cumulative_y[x] < seriesExtremes[0]) {
2488 seriesExtremes[0] = cumulative_y[x];
2489 }
2490 }
2491 }
2492 extremes[seriesName] = seriesExtremes;
2493
2494 datasets[i] = series;
2495 }
2496
2497 for (var i = 1; i < datasets.length; i++) {
2498 if (!this.visibility()[i - 1]) continue;
2499 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
2500 }
2501
2502 this.computeYAxisRanges_(extremes);
2503 this.layout_.updateOptions( { yAxes: this.axes_,
2504 seriesToAxisMap: this.seriesToAxisMap_
2505 } );
2506
2507 this.addXTicks_();
2508
2509 // Tell PlotKit to use this new data and render itself
2510 this.layout_.updateOptions({dateWindow: this.dateWindow_});
2511 this.layout_.evaluateWithError();
2512 this.plotter_.clear();
2513 this.plotter_.render();
2514 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2515 this.canvas_.height);
2516
2517 if (is_initial_draw) {
2518 // Generate a static legend before any particular point is selected.
2519 this.attr_('labelsDiv').innerHTML = this.generateLegendHTML_();
2520 }
2521
2522 if (this.attr_("drawCallback") !== null) {
2523 this.attr_("drawCallback")(this, is_initial_draw);
2524 }
2525 };
2526
2527 /**
2528 * Determine properties of the y-axes which are independent of the data
2529 * currently being displayed. This includes things like the number of axes and
2530 * the style of the axes. It does not include the range of each axis and its
2531 * tick marks.
2532 * This fills in this.axes_ and this.seriesToAxisMap_.
2533 * axes_ = [ { options } ]
2534 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2535 * indices are into the axes_ array.
2536 */
2537 Dygraph.prototype.computeYAxes_ = function() {
2538 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
2539 this.seriesToAxisMap_ = {};
2540
2541 // Get a list of series names.
2542 var labels = this.attr_("labels");
2543 var series = {};
2544 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
2545
2546 // all options which could be applied per-axis:
2547 var axisOptions = [
2548 'includeZero',
2549 'valueRange',
2550 'labelsKMB',
2551 'labelsKMG2',
2552 'pixelsPerYLabel',
2553 'yAxisLabelWidth',
2554 'axisLabelFontSize',
2555 'axisTickSize',
2556 'logscale'
2557 ];
2558
2559 // Copy global axis options over to the first axis.
2560 for (var i = 0; i < axisOptions.length; i++) {
2561 var k = axisOptions[i];
2562 var v = this.attr_(k);
2563 if (v) this.axes_[0][k] = v;
2564 }
2565
2566 // Go through once and add all the axes.
2567 for (var seriesName in series) {
2568 if (!series.hasOwnProperty(seriesName)) continue;
2569 var axis = this.attr_("axis", seriesName);
2570 if (axis == null) {
2571 this.seriesToAxisMap_[seriesName] = 0;
2572 continue;
2573 }
2574 if (typeof(axis) == 'object') {
2575 // Add a new axis, making a copy of its per-axis options.
2576 var opts = {};
2577 Dygraph.update(opts, this.axes_[0]);
2578 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
2579 var yAxisId = this.axes_.length;
2580 opts.yAxisId = yAxisId;
2581 opts.g = this;
2582 Dygraph.update(opts, axis);
2583 this.axes_.push(opts);
2584 this.seriesToAxisMap_[seriesName] = yAxisId;
2585 }
2586 }
2587
2588 // Go through one more time and assign series to an axis defined by another
2589 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2590 for (var seriesName in series) {
2591 if (!series.hasOwnProperty(seriesName)) continue;
2592 var axis = this.attr_("axis", seriesName);
2593 if (typeof(axis) == 'string') {
2594 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
2595 this.error("Series " + seriesName + " wants to share a y-axis with " +
2596 "series " + axis + ", which does not define its own axis.");
2597 return null;
2598 }
2599 var idx = this.seriesToAxisMap_[axis];
2600 this.seriesToAxisMap_[seriesName] = idx;
2601 }
2602 }
2603
2604 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2605 // this last so that hiding the first series doesn't destroy the axis
2606 // properties of the primary axis.
2607 var seriesToAxisFiltered = {};
2608 var vis = this.visibility();
2609 for (var i = 1; i < labels.length; i++) {
2610 var s = labels[i];
2611 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2612 }
2613 this.seriesToAxisMap_ = seriesToAxisFiltered;
2614 };
2615
2616 /**
2617 * Returns the number of y-axes on the chart.
2618 * @return {Number} the number of axes.
2619 */
2620 Dygraph.prototype.numAxes = function() {
2621 var last_axis = 0;
2622 for (var series in this.seriesToAxisMap_) {
2623 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2624 var idx = this.seriesToAxisMap_[series];
2625 if (idx > last_axis) last_axis = idx;
2626 }
2627 return 1 + last_axis;
2628 };
2629
2630 /**
2631 * Determine the value range and tick marks for each axis.
2632 * @param {Object} extremes A mapping from seriesName -> [low, high]
2633 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2634 */
2635 Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2636 // Build a map from axis number -> [list of series names]
2637 var seriesForAxis = [];
2638 for (var series in this.seriesToAxisMap_) {
2639 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2640 var idx = this.seriesToAxisMap_[series];
2641 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2642 seriesForAxis[idx].push(series);
2643 }
2644
2645 // If no series are defined or visible then fill in some reasonable defaults.
2646 if (seriesForAxis.length == 0) {
2647 var axis = this.axes_[0];
2648 axis.computedValueRange = [0, 1];
2649 var ret =
2650 Dygraph.numericTicks(axis.computedValueRange[0],
2651 axis.computedValueRange[1],
2652 this,
2653 axis);
2654 axis.ticks = ret.ticks;
2655 this.numYDigits_ = ret.numDigits;
2656 return;
2657 }
2658
2659 // Compute extreme values, a span and tick marks for each axis.
2660 for (var i = 0; i < this.axes_.length; i++) {
2661 var axis = this.axes_[i];
2662 if (axis.valueWindow) {
2663 // This is only set if the user has zoomed on the y-axis. It is never set
2664 // by a user. It takes precedence over axis.valueRange because, if you set
2665 // valueRange, you'd still expect to be able to pan.
2666 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2667 } else if (axis.valueRange) {
2668 // This is a user-set value range for this axis.
2669 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
2670 } else {
2671 // Calculate the extremes of extremes.
2672 var series = seriesForAxis[i];
2673 var minY = Infinity; // extremes[series[0]][0];
2674 var maxY = -Infinity; // extremes[series[0]][1];
2675 for (var j = 0; j < series.length; j++) {
2676 minY = Math.min(extremes[series[j]][0], minY);
2677 maxY = Math.max(extremes[series[j]][1], maxY);
2678 }
2679 if (axis.includeZero && minY > 0) minY = 0;
2680
2681 // Add some padding and round up to an integer to be human-friendly.
2682 var span = maxY - minY;
2683 // special case: if we have no sense of scale, use +/-10% of the sole value.
2684 if (span == 0) { span = maxY; }
2685
2686 var maxAxisY;
2687 var minAxisY;
2688 if (axis.logscale) {
2689 var maxAxisY = maxY + 0.1 * span;
2690 var minAxisY = minY;
2691 } else {
2692 var maxAxisY = maxY + 0.1 * span;
2693 var minAxisY = minY - 0.1 * span;
2694
2695 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2696 if (!this.attr_("avoidMinZero")) {
2697 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2698 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2699 }
2700
2701 if (this.attr_("includeZero")) {
2702 if (maxY < 0) maxAxisY = 0;
2703 if (minY > 0) minAxisY = 0;
2704 }
2705 }
2706
2707 axis.computedValueRange = [minAxisY, maxAxisY];
2708 }
2709
2710 // Add ticks. By default, all axes inherit the tick positions of the
2711 // primary axis. However, if an axis is specifically marked as having
2712 // independent ticks, then that is permissible as well.
2713 if (i == 0 || axis.independentTicks) {
2714 var ret =
2715 Dygraph.numericTicks(axis.computedValueRange[0],
2716 axis.computedValueRange[1],
2717 this,
2718 axis);
2719 axis.ticks = ret.ticks;
2720 this.numYDigits_ = ret.numDigits;
2721 } else {
2722 var p_axis = this.axes_[0];
2723 var p_ticks = p_axis.ticks;
2724 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2725 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2726 var tick_values = [];
2727 for (var i = 0; i < p_ticks.length; i++) {
2728 var y_frac = (p_ticks[i].v - p_axis.computedValueRange[0]) / p_scale;
2729 var y_val = axis.computedValueRange[0] + y_frac * scale;
2730 tick_values.push(y_val);
2731 }
2732
2733 var ret =
2734 Dygraph.numericTicks(axis.computedValueRange[0],
2735 axis.computedValueRange[1],
2736 this, axis, tick_values);
2737 axis.ticks = ret.ticks;
2738 this.numYDigits_ = ret.numDigits;
2739 }
2740 }
2741 };
2742
2743 /**
2744 * Calculates the rolling average of a data set.
2745 * If originalData is [label, val], rolls the average of those.
2746 * If originalData is [label, [, it's interpreted as [value, stddev]
2747 * and the roll is returned in the same form, with appropriately reduced
2748 * stddev for each value.
2749 * Note that this is where fractional input (i.e. '5/10') is converted into
2750 * decimal values.
2751 * @param {Array} originalData The data in the appropriate format (see above)
2752 * @param {Number} rollPeriod The number of points over which to average the
2753 * data
2754 */
2755 Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
2756 if (originalData.length < 2)
2757 return originalData;
2758 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
2759 var rollingData = [];
2760 var sigma = this.attr_("sigma");
2761
2762 if (this.fractions_) {
2763 var num = 0;
2764 var den = 0; // numerator/denominator
2765 var mult = 100.0;
2766 for (var i = 0; i < originalData.length; i++) {
2767 num += originalData[i][1][0];
2768 den += originalData[i][1][1];
2769 if (i - rollPeriod >= 0) {
2770 num -= originalData[i - rollPeriod][1][0];
2771 den -= originalData[i - rollPeriod][1][1];
2772 }
2773
2774 var date = originalData[i][0];
2775 var value = den ? num / den : 0.0;
2776 if (this.attr_("errorBars")) {
2777 if (this.wilsonInterval_) {
2778 // For more details on this confidence interval, see:
2779 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
2780 if (den) {
2781 var p = value < 0 ? 0 : value, n = den;
2782 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
2783 var denom = 1 + sigma * sigma / den;
2784 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
2785 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
2786 rollingData[i] = [date,
2787 [p * mult, (p - low) * mult, (high - p) * mult]];
2788 } else {
2789 rollingData[i] = [date, [0, 0, 0]];
2790 }
2791 } else {
2792 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
2793 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
2794 }
2795 } else {
2796 rollingData[i] = [date, mult * value];
2797 }
2798 }
2799 } else if (this.attr_("customBars")) {
2800 var low = 0;
2801 var mid = 0;
2802 var high = 0;
2803 var count = 0;
2804 for (var i = 0; i < originalData.length; i++) {
2805 var data = originalData[i][1];
2806 var y = data[1];
2807 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
2808
2809 if (y != null && !isNaN(y)) {
2810 low += data[0];
2811 mid += y;
2812 high += data[2];
2813 count += 1;
2814 }
2815 if (i - rollPeriod >= 0) {
2816 var prev = originalData[i - rollPeriod];
2817 if (prev[1][1] != null && !isNaN(prev[1][1])) {
2818 low -= prev[1][0];
2819 mid -= prev[1][1];
2820 high -= prev[1][2];
2821 count -= 1;
2822 }
2823 }
2824 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
2825 1.0 * (mid - low) / count,
2826 1.0 * (high - mid) / count ]];
2827 }
2828 } else {
2829 // Calculate the rolling average for the first rollPeriod - 1 points where
2830 // there is not enough data to roll over the full number of points
2831 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
2832 if (!this.attr_("errorBars")){
2833 if (rollPeriod == 1) {
2834 return originalData;
2835 }
2836
2837 for (var i = 0; i < originalData.length; i++) {
2838 var sum = 0;
2839 var num_ok = 0;
2840 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2841 var y = originalData[j][1];
2842 if (y == null || isNaN(y)) continue;
2843 num_ok++;
2844 sum += originalData[j][1];
2845 }
2846 if (num_ok) {
2847 rollingData[i] = [originalData[i][0], sum / num_ok];
2848 } else {
2849 rollingData[i] = [originalData[i][0], null];
2850 }
2851 }
2852
2853 } else {
2854 for (var i = 0; i < originalData.length; i++) {
2855 var sum = 0;
2856 var variance = 0;
2857 var num_ok = 0;
2858 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2859 var y = originalData[j][1][0];
2860 if (y == null || isNaN(y)) continue;
2861 num_ok++;
2862 sum += originalData[j][1][0];
2863 variance += Math.pow(originalData[j][1][1], 2);
2864 }
2865 if (num_ok) {
2866 var stddev = Math.sqrt(variance) / num_ok;
2867 rollingData[i] = [originalData[i][0],
2868 [sum / num_ok, sigma * stddev, sigma * stddev]];
2869 } else {
2870 rollingData[i] = [originalData[i][0], [null, null, null]];
2871 }
2872 }
2873 }
2874 }
2875
2876 return rollingData;
2877 };
2878
2879 /**
2880 * Parses a date, returning the number of milliseconds since epoch. This can be
2881 * passed in as an xValueParser in the Dygraph constructor.
2882 * TODO(danvk): enumerate formats that this understands.
2883 * @param {String} A date in YYYYMMDD format.
2884 * @return {Number} Milliseconds since epoch.
2885 * @public
2886 */
2887 Dygraph.dateParser = function(dateStr, self) {
2888 var dateStrSlashed;
2889 var d;
2890 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
2891 dateStrSlashed = dateStr.replace("-", "/", "g");
2892 while (dateStrSlashed.search("-") != -1) {
2893 dateStrSlashed = dateStrSlashed.replace("-", "/");
2894 }
2895 d = Date.parse(dateStrSlashed);
2896 } else if (dateStr.length == 8) { // e.g. '20090712'
2897 // TODO(danvk): remove support for this format. It's confusing.
2898 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
2899 + "/" + dateStr.substr(6,2);
2900 d = Date.parse(dateStrSlashed);
2901 } else {
2902 // Any format that Date.parse will accept, e.g. "2009/07/12" or
2903 // "2009/07/12 12:34:56"
2904 d = Date.parse(dateStr);
2905 }
2906
2907 if (!d || isNaN(d)) {
2908 self.error("Couldn't parse " + dateStr + " as a date");
2909 }
2910 return d;
2911 };
2912
2913 /**
2914 * Detects the type of the str (date or numeric) and sets the various
2915 * formatting attributes in this.attrs_ based on this type.
2916 * @param {String} str An x value.
2917 * @private
2918 */
2919 Dygraph.prototype.detectTypeFromString_ = function(str) {
2920 var isDate = false;
2921 if (str.indexOf('-') > 0 ||
2922 str.indexOf('/') >= 0 ||
2923 isNaN(parseFloat(str))) {
2924 isDate = true;
2925 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2926 // TODO(danvk): remove support for this format.
2927 isDate = true;
2928 }
2929
2930 if (isDate) {
2931 this.attrs_.xValueFormatter = Dygraph.dateString_;
2932 this.attrs_.xValueParser = Dygraph.dateParser;
2933 this.attrs_.xTicker = Dygraph.dateTicker;
2934 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
2935 } else {
2936 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
2937 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2938 this.attrs_.xTicker = Dygraph.numericTicks;
2939 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
2940 }
2941 };
2942
2943 /**
2944 * Parses the value as a floating point number. This is like the parseFloat()
2945 * built-in, but with a few differences:
2946 * - the empty string is parsed as null, rather than NaN.
2947 * - if the string cannot be parsed at all, an error is logged.
2948 * If the string can't be parsed, this method returns null.
2949 * @param {String} x The string to be parsed
2950 * @param {Number} opt_line_no The line number from which the string comes.
2951 * @param {String} opt_line The text of the line from which the string comes.
2952 * @private
2953 */
2954
2955 // Parse the x as a float or return null if it's not a number.
2956 Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
2957 var val = parseFloat(x);
2958 if (!isNaN(val)) return val;
2959
2960 // Try to figure out what happeend.
2961 // If the value is the empty string, parse it as null.
2962 if (/^ *$/.test(x)) return null;
2963
2964 // If it was actually "NaN", return it as NaN.
2965 if (/^ *nan *$/i.test(x)) return NaN;
2966
2967 // Looks like a parsing error.
2968 var msg = "Unable to parse '" + x + "' as a number";
2969 if (opt_line !== null && opt_line_no !== null) {
2970 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
2971 }
2972 this.error(msg);
2973
2974 return null;
2975 };
2976
2977 /**
2978 * Parses a string in a special csv format. We expect a csv file where each
2979 * line is a date point, and the first field in each line is the date string.
2980 * We also expect that all remaining fields represent series.
2981 * if the errorBars attribute is set, then interpret the fields as:
2982 * date, series1, stddev1, series2, stddev2, ...
2983 * @param {Array.<Object>} data See above.
2984 * @private
2985 *
2986 * @return Array.<Object> An array with one entry for each row. These entries
2987 * are an array of cells in that row. The first entry is the parsed x-value for
2988 * the row. The second, third, etc. are the y-values. These can take on one of
2989 * three forms, depending on the CSV and constructor parameters:
2990 * 1. numeric value
2991 * 2. [ value, stddev ]
2992 * 3. [ low value, center value, high value ]
2993 */
2994 Dygraph.prototype.parseCSV_ = function(data) {
2995 var ret = [];
2996 var lines = data.split("\n");
2997
2998 // Use the default delimiter or fall back to a tab if that makes sense.
2999 var delim = this.attr_('delimiter');
3000 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
3001 delim = '\t';
3002 }
3003
3004 var start = 0;
3005 if (this.labelsFromCSV_) {
3006 start = 1;
3007 this.attrs_.labels = lines[0].split(delim);
3008 }
3009 var line_no = 0;
3010
3011 var xParser;
3012 var defaultParserSet = false; // attempt to auto-detect x value type
3013 var expectedCols = this.attr_("labels").length;
3014 var outOfOrder = false;
3015 for (var i = start; i < lines.length; i++) {
3016 var line = lines[i];
3017 line_no = i;
3018 if (line.length == 0) continue; // skip blank lines
3019 if (line[0] == '#') continue; // skip comment lines
3020 var inFields = line.split(delim);
3021 if (inFields.length < 2) continue;
3022
3023 var fields = [];
3024 if (!defaultParserSet) {
3025 this.detectTypeFromString_(inFields[0]);
3026 xParser = this.attr_("xValueParser");
3027 defaultParserSet = true;
3028 }
3029 fields[0] = xParser(inFields[0], this);
3030
3031 // If fractions are expected, parse the numbers as "A/B"
3032 if (this.fractions_) {
3033 for (var j = 1; j < inFields.length; j++) {
3034 // TODO(danvk): figure out an appropriate way to flag parse errors.
3035 var vals = inFields[j].split("/");
3036 if (vals.length != 2) {
3037 this.error('Expected fractional "num/den" values in CSV data ' +
3038 "but found a value '" + inFields[j] + "' on line " +
3039 (1 + i) + " ('" + line + "') which is not of this form.");
3040 fields[j] = [0, 0];
3041 } else {
3042 fields[j] = [this.parseFloat_(vals[0], i, line),
3043 this.parseFloat_(vals[1], i, line)];
3044 }
3045 }
3046 } else if (this.attr_("errorBars")) {
3047 // If there are error bars, values are (value, stddev) pairs
3048 if (inFields.length % 2 != 1) {
3049 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3050 'but line ' + (1 + i) + ' has an odd number of values (' +
3051 (inFields.length - 1) + "): '" + line + "'");
3052 }
3053 for (var j = 1; j < inFields.length; j += 2) {
3054 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3055 this.parseFloat_(inFields[j + 1], i, line)];
3056 }
3057 } else if (this.attr_("customBars")) {
3058 // Bars are a low;center;high tuple
3059 for (var j = 1; j < inFields.length; j++) {
3060 var vals = inFields[j].split(";");
3061 fields[j] = [ this.parseFloat_(vals[0], i, line),
3062 this.parseFloat_(vals[1], i, line),
3063 this.parseFloat_(vals[2], i, line) ];
3064 }
3065 } else {
3066 // Values are just numbers
3067 for (var j = 1; j < inFields.length; j++) {
3068 fields[j] = this.parseFloat_(inFields[j], i, line);
3069 }
3070 }
3071 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3072 outOfOrder = true;
3073 }
3074
3075 if (fields.length != expectedCols) {
3076 this.error("Number of columns in line " + i + " (" + fields.length +
3077 ") does not agree with number of labels (" + expectedCols +
3078 ") " + line);
3079 }
3080
3081 // If the user specified the 'labels' option and none of the cells of the
3082 // first row parsed correctly, then they probably double-specified the
3083 // labels. We go with the values set in the option, discard this row and
3084 // log a warning to the JS console.
3085 if (i == 0 && this.attr_('labels')) {
3086 var all_null = true;
3087 for (var j = 0; all_null && j < fields.length; j++) {
3088 if (fields[j]) all_null = false;
3089 }
3090 if (all_null) {
3091 this.warn("The dygraphs 'labels' option is set, but the first row of " +
3092 "CSV data ('" + line + "') appears to also contain labels. " +
3093 "Will drop the CSV labels and use the option labels.");
3094 continue;
3095 }
3096 }
3097 ret.push(fields);
3098 }
3099
3100 if (outOfOrder) {
3101 this.warn("CSV is out of order; order it correctly to speed loading.");
3102 ret.sort(function(a,b) { return a[0] - b[0] });
3103 }
3104
3105 return ret;
3106 };
3107
3108 /**
3109 * The user has provided their data as a pre-packaged JS array. If the x values
3110 * are numeric, this is the same as dygraphs' internal format. If the x values
3111 * are dates, we need to convert them from Date objects to ms since epoch.
3112 * @param {Array.<Object>} data
3113 * @return {Array.<Object>} data with numeric x values.
3114 */
3115 Dygraph.prototype.parseArray_ = function(data) {
3116 // Peek at the first x value to see if it's numeric.
3117 if (data.length == 0) {
3118 this.error("Can't plot empty data set");
3119 return null;
3120 }
3121 if (data[0].length == 0) {
3122 this.error("Data set cannot contain an empty row");
3123 return null;
3124 }
3125
3126 if (this.attr_("labels") == null) {
3127 this.warn("Using default labels. Set labels explicitly via 'labels' " +
3128 "in the options parameter");
3129 this.attrs_.labels = [ "X" ];
3130 for (var i = 1; i < data[0].length; i++) {
3131 this.attrs_.labels.push("Y" + i);
3132 }
3133 }
3134
3135 if (Dygraph.isDateLike(data[0][0])) {
3136 // Some intelligent defaults for a date x-axis.
3137 this.attrs_.xValueFormatter = Dygraph.dateString_;
3138 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
3139 this.attrs_.xTicker = Dygraph.dateTicker;
3140
3141 // Assume they're all dates.
3142 var parsedData = Dygraph.clone(data);
3143 for (var i = 0; i < data.length; i++) {
3144 if (parsedData[i].length == 0) {
3145 this.error("Row " + (1 + i) + " of data is empty");
3146 return null;
3147 }
3148 if (parsedData[i][0] == null
3149 || typeof(parsedData[i][0].getTime) != 'function'
3150 || isNaN(parsedData[i][0].getTime())) {
3151 this.error("x value in row " + (1 + i) + " is not a Date");
3152 return null;
3153 }
3154 parsedData[i][0] = parsedData[i][0].getTime();
3155 }
3156 return parsedData;
3157 } else {
3158 // Some intelligent defaults for a numeric x-axis.
3159 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
3160 this.attrs_.xTicker = Dygraph.numericTicks;
3161 return data;
3162 }
3163 };
3164
3165 /**
3166 * Parses a DataTable object from gviz.
3167 * The data is expected to have a first column that is either a date or a
3168 * number. All subsequent columns must be numbers. If there is a clear mismatch
3169 * between this.xValueParser_ and the type of the first column, it will be
3170 * fixed. Fills out rawData_.
3171 * @param {Array.<Object>} data See above.
3172 * @private
3173 */
3174 Dygraph.prototype.parseDataTable_ = function(data) {
3175 var cols = data.getNumberOfColumns();
3176 var rows = data.getNumberOfRows();
3177
3178 var indepType = data.getColumnType(0);
3179 if (indepType == 'date' || indepType == 'datetime') {
3180 this.attrs_.xValueFormatter = Dygraph.dateString_;
3181 this.attrs_.xValueParser = Dygraph.dateParser;
3182 this.attrs_.xTicker = Dygraph.dateTicker;
3183 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
3184 } else if (indepType == 'number') {
3185 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
3186 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
3187 this.attrs_.xTicker = Dygraph.numericTicks;
3188 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
3189 } else {
3190 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3191 "column 1 of DataTable input (Got '" + indepType + "')");
3192 return null;
3193 }
3194
3195 // Array of the column indices which contain data (and not annotations).
3196 var colIdx = [];
3197 var annotationCols = {}; // data index -> [annotation cols]
3198 var hasAnnotations = false;
3199 for (var i = 1; i < cols; i++) {
3200 var type = data.getColumnType(i);
3201 if (type == 'number') {
3202 colIdx.push(i);
3203 } else if (type == 'string' && this.attr_('displayAnnotations')) {
3204 // This is OK -- it's an annotation column.
3205 var dataIdx = colIdx[colIdx.length - 1];
3206 if (!annotationCols.hasOwnProperty(dataIdx)) {
3207 annotationCols[dataIdx] = [i];
3208 } else {
3209 annotationCols[dataIdx].push(i);
3210 }
3211 hasAnnotations = true;
3212 } else {
3213 this.error("Only 'number' is supported as a dependent type with Gviz." +
3214 " 'string' is only supported if displayAnnotations is true");
3215 }
3216 }
3217
3218 // Read column labels
3219 // TODO(danvk): add support back for errorBars
3220 var labels = [data.getColumnLabel(0)];
3221 for (var i = 0; i < colIdx.length; i++) {
3222 labels.push(data.getColumnLabel(colIdx[i]));
3223 if (this.attr_("errorBars")) i += 1;
3224 }
3225 this.attrs_.labels = labels;
3226 cols = labels.length;
3227
3228 var ret = [];
3229 var outOfOrder = false;
3230 var annotations = [];
3231 for (var i = 0; i < rows; i++) {
3232 var row = [];
3233 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3234 data.getValue(i, 0) === null) {
3235 this.warn("Ignoring row " + i +
3236 " of DataTable because of undefined or null first column.");
3237 continue;
3238 }
3239
3240 if (indepType == 'date' || indepType == 'datetime') {
3241 row.push(data.getValue(i, 0).getTime());
3242 } else {
3243 row.push(data.getValue(i, 0));
3244 }
3245 if (!this.attr_("errorBars")) {
3246 for (var j = 0; j < colIdx.length; j++) {
3247 var col = colIdx[j];
3248 row.push(data.getValue(i, col));
3249 if (hasAnnotations &&
3250 annotationCols.hasOwnProperty(col) &&
3251 data.getValue(i, annotationCols[col][0]) != null) {
3252 var ann = {};
3253 ann.series = data.getColumnLabel(col);
3254 ann.xval = row[0];
3255 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
3256 ann.text = '';
3257 for (var k = 0; k < annotationCols[col].length; k++) {
3258 if (k) ann.text += "\n";
3259 ann.text += data.getValue(i, annotationCols[col][k]);
3260 }
3261 annotations.push(ann);
3262 }
3263 }
3264
3265 // Strip out infinities, which give dygraphs problems later on.
3266 for (var j = 0; j < row.length; j++) {
3267 if (!isFinite(row[j])) row[j] = null;
3268 }
3269 } else {
3270 for (var j = 0; j < cols - 1; j++) {
3271 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3272 }
3273 }
3274 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3275 outOfOrder = true;
3276 }
3277 ret.push(row);
3278 }
3279
3280 if (outOfOrder) {
3281 this.warn("DataTable is out of order; order it correctly to speed loading.");
3282 ret.sort(function(a,b) { return a[0] - b[0] });
3283 }
3284 this.rawData_ = ret;
3285
3286 if (annotations.length > 0) {
3287 this.setAnnotations(annotations, true);
3288 }
3289 }
3290
3291 // These functions are all based on MochiKit.
3292 Dygraph.update = function (self, o) {
3293 if (typeof(o) != 'undefined' && o !== null) {
3294 for (var k in o) {
3295 if (o.hasOwnProperty(k)) {
3296 self[k] = o[k];
3297 }
3298 }
3299 }
3300 return self;
3301 };
3302
3303 Dygraph.isArrayLike = function (o) {
3304 var typ = typeof(o);
3305 if (
3306 (typ != 'object' && !(typ == 'function' &&
3307 typeof(o.item) == 'function')) ||
3308 o === null ||
3309 typeof(o.length) != 'number' ||
3310 o.nodeType === 3
3311 ) {
3312 return false;
3313 }
3314 return true;
3315 };
3316
3317 Dygraph.isDateLike = function (o) {
3318 if (typeof(o) != "object" || o === null ||
3319 typeof(o.getTime) != 'function') {
3320 return false;
3321 }
3322 return true;
3323 };
3324
3325 Dygraph.clone = function(o) {
3326 // TODO(danvk): figure out how MochiKit's version works
3327 var r = [];
3328 for (var i = 0; i < o.length; i++) {
3329 if (Dygraph.isArrayLike(o[i])) {
3330 r.push(Dygraph.clone(o[i]));
3331 } else {
3332 r.push(o[i]);
3333 }
3334 }
3335 return r;
3336 };
3337
3338
3339 /**
3340 * Get the CSV data. If it's in a function, call that function. If it's in a
3341 * file, do an XMLHttpRequest to get it.
3342 * @private
3343 */
3344 Dygraph.prototype.start_ = function() {
3345 if (typeof this.file_ == 'function') {
3346 // CSV string. Pretend we got it via XHR.
3347 this.loadedEvent_(this.file_());
3348 } else if (Dygraph.isArrayLike(this.file_)) {
3349 this.rawData_ = this.parseArray_(this.file_);
3350 this.predraw_();
3351 } else if (typeof this.file_ == 'object' &&
3352 typeof this.file_.getColumnRange == 'function') {
3353 // must be a DataTable from gviz.
3354 this.parseDataTable_(this.file_);
3355 this.predraw_();
3356 } else if (typeof this.file_ == 'string') {
3357 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3358 if (this.file_.indexOf('\n') >= 0) {
3359 this.loadedEvent_(this.file_);
3360 } else {
3361 var req = new XMLHttpRequest();
3362 var caller = this;
3363 req.onreadystatechange = function () {
3364 if (req.readyState == 4) {
3365 if (req.status == 200) {
3366 caller.loadedEvent_(req.responseText);
3367 }
3368 }
3369 };
3370
3371 req.open("GET", this.file_, true);
3372 req.send(null);
3373 }
3374 } else {
3375 this.error("Unknown data format: " + (typeof this.file_));
3376 }
3377 };
3378
3379 /**
3380 * Changes various properties of the graph. These can include:
3381 * <ul>
3382 * <li>file: changes the source data for the graph</li>
3383 * <li>errorBars: changes whether the data contains stddev</li>
3384 * </ul>
3385 * @param {Object} attrs The new properties and values
3386 */
3387 Dygraph.prototype.updateOptions = function(attrs) {
3388 // TODO(danvk): this is a mess. Rethink this function.
3389 if ('rollPeriod' in attrs) {
3390 this.rollPeriod_ = attrs.rollPeriod;
3391 }
3392 if ('dateWindow' in attrs) {
3393 this.dateWindow_ = attrs.dateWindow;
3394 }
3395
3396 // TODO(danvk): validate per-series options.
3397 // Supported:
3398 // strokeWidth
3399 // pointSize
3400 // drawPoints
3401 // highlightCircleSize
3402
3403 Dygraph.update(this.user_attrs_, attrs);
3404 Dygraph.update(this.renderOptions_, attrs);
3405
3406 this.labelsFromCSV_ = (this.attr_("labels") == null);
3407
3408 // TODO(danvk): this doesn't match the constructor logic
3409 this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") });
3410 if (attrs['file']) {
3411 this.file_ = attrs['file'];
3412 this.start_();
3413 } else {
3414 this.predraw_();
3415 }
3416 };
3417
3418 /**
3419 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3420 * containing div (which has presumably changed size since the dygraph was
3421 * instantiated. If the width/height are specified, the div will be resized.
3422 *
3423 * This is far more efficient than destroying and re-instantiating a
3424 * Dygraph, since it doesn't have to reparse the underlying data.
3425 *
3426 * @param {Number} width Width (in pixels)
3427 * @param {Number} height Height (in pixels)
3428 */
3429 Dygraph.prototype.resize = function(width, height) {
3430 if (this.resize_lock) {
3431 return;
3432 }
3433 this.resize_lock = true;
3434
3435 if ((width === null) != (height === null)) {
3436 this.warn("Dygraph.resize() should be called with zero parameters or " +
3437 "two non-NULL parameters. Pretending it was zero.");
3438 width = height = null;
3439 }
3440
3441 // TODO(danvk): there should be a clear() method.
3442 this.maindiv_.innerHTML = "";
3443 this.attrs_.labelsDiv = null;
3444
3445 if (width) {
3446 this.maindiv_.style.width = width + "px";
3447 this.maindiv_.style.height = height + "px";
3448 this.width_ = width;
3449 this.height_ = height;
3450 } else {
3451 this.width_ = this.maindiv_.offsetWidth;
3452 this.height_ = this.maindiv_.offsetHeight;
3453 }
3454
3455 this.createInterface_();
3456 this.predraw_();
3457
3458 this.resize_lock = false;
3459 };
3460
3461 /**
3462 * Adjusts the number of points in the rolling average. Updates the graph to
3463 * reflect the new averaging period.
3464 * @param {Number} length Number of points over which to average the data.
3465 */
3466 Dygraph.prototype.adjustRoll = function(length) {
3467 this.rollPeriod_ = length;
3468 this.predraw_();
3469 };
3470
3471 /**
3472 * Returns a boolean array of visibility statuses.
3473 */
3474 Dygraph.prototype.visibility = function() {
3475 // Do lazy-initialization, so that this happens after we know the number of
3476 // data series.
3477 if (!this.attr_("visibility")) {
3478 this.attrs_["visibility"] = [];
3479 }
3480 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
3481 this.attr_("visibility").push(true);
3482 }
3483 return this.attr_("visibility");
3484 };
3485
3486 /**
3487 * Changes the visiblity of a series.
3488 */
3489 Dygraph.prototype.setVisibility = function(num, value) {
3490 var x = this.visibility();
3491 if (num < 0 || num >= x.length) {
3492 this.warn("invalid series number in setVisibility: " + num);
3493 } else {
3494 x[num] = value;
3495 this.predraw_();
3496 }
3497 };
3498
3499 /**
3500 * Update the list of annotations and redraw the chart.
3501 */
3502 Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3503 // Only add the annotation CSS rule once we know it will be used.
3504 Dygraph.addAnnotationRule();
3505 this.annotations_ = ann;
3506 this.layout_.setAnnotations(this.annotations_);
3507 if (!suppressDraw) {
3508 this.predraw_();
3509 }
3510 };
3511
3512 /**
3513 * Return the list of annotations.
3514 */
3515 Dygraph.prototype.annotations = function() {
3516 return this.annotations_;
3517 };
3518
3519 /**
3520 * Get the index of a series (column) given its name. The first column is the
3521 * x-axis, so the data series start with index 1.
3522 */
3523 Dygraph.prototype.indexFromSetName = function(name) {
3524 var labels = this.attr_("labels");
3525 for (var i = 0; i < labels.length; i++) {
3526 if (labels[i] == name) return i;
3527 }
3528 return null;
3529 };
3530
3531 Dygraph.addAnnotationRule = function() {
3532 if (Dygraph.addedAnnotationCSS) return;
3533
3534 var rule = "border: 1px solid black; " +
3535 "background-color: white; " +
3536 "text-align: center;";
3537
3538 var styleSheetElement = document.createElement("style");
3539 styleSheetElement.type = "text/css";
3540 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3541
3542 // Find the first style sheet that we can access.
3543 // We may not add a rule to a style sheet from another domain for security
3544 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3545 // adds its own style sheets from google.com.
3546 for (var i = 0; i < document.styleSheets.length; i++) {
3547 if (document.styleSheets[i].disabled) continue;
3548 var mysheet = document.styleSheets[i];
3549 try {
3550 if (mysheet.insertRule) { // Firefox
3551 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3552 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3553 } else if (mysheet.addRule) { // IE
3554 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3555 }
3556 Dygraph.addedAnnotationCSS = true;
3557 return;
3558 } catch(err) {
3559 // Was likely a security exception.
3560 }
3561 }
3562
3563 this.warn("Unable to add default annotation CSS rule; display may be off.");
3564 }
3565
3566 /**
3567 * Create a new canvas element. This is more complex than a simple
3568 * document.createElement("canvas") because of IE and excanvas.
3569 */
3570 Dygraph.createCanvas = function() {
3571 var canvas = document.createElement("canvas");
3572
3573 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
3574 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
3575 canvas = G_vmlCanvasManager.initElement(canvas);
3576 }
3577
3578 return canvas;
3579 };
3580
3581
3582 /**
3583 * A wrapper around Dygraph that implements the gviz API.
3584 * @param {Object} container The DOM object the visualization should live in.
3585 */
3586 Dygraph.GVizChart = function(container) {
3587 this.container = container;
3588 }
3589
3590 Dygraph.GVizChart.prototype.draw = function(data, options) {
3591 // Clear out any existing dygraph.
3592 // TODO(danvk): would it make more sense to simply redraw using the current
3593 // date_graph object?
3594 this.container.innerHTML = '';
3595 if (typeof(this.date_graph) != 'undefined') {
3596 this.date_graph.destroy();
3597 }
3598
3599 this.date_graph = new Dygraph(this.container, data, options);
3600 }
3601
3602 /**
3603 * Google charts compatible setSelection
3604 * Only row selection is supported, all points in the row will be highlighted
3605 * @param {Array} array of the selected cells
3606 * @public
3607 */
3608 Dygraph.GVizChart.prototype.setSelection = function(selection_array) {
3609 var row = false;
3610 if (selection_array.length) {
3611 row = selection_array[0].row;
3612 }
3613 this.date_graph.setSelection(row);
3614 }
3615
3616 /**
3617 * Google charts compatible getSelection implementation
3618 * @return {Array} array of the selected cells
3619 * @public
3620 */
3621 Dygraph.GVizChart.prototype.getSelection = function() {
3622 var selection = [];
3623
3624 var row = this.date_graph.getSelection();
3625
3626 if (row < 0) return selection;
3627
3628 col = 1;
3629 for (var i in this.date_graph.layout_.datasets) {
3630 selection.push({row: row, column: col});
3631 col++;
3632 }
3633
3634 return selection;
3635 }
3636
3637 // Older pages may still use this name.
3638 DateGraph = Dygraph;
3639
3640 // <REMOVE_FOR_COMBINED>
3641 Dygraph.OPTIONS_REFERENCE = // <JSON>
3642 {
3643 "xValueParser": {
3644 "default": "parseFloat() or Date.parse()*",
3645 "labels": ["CSV parsing"],
3646 "type": "function(str) -> number",
3647 "description": "A function which parses x-values (i.e. the dependent series). Must return a number, even when the values are dates. In this case, millis since epoch are used. This is used primarily for parsing CSV data. *=Dygraphs is slightly more accepting in the dates which it will parse. See code for details."
3648 },
3649 "stackedGraph": {
3650 "default": "false",
3651 "labels": ["Data Line display"],
3652 "type": "boolean",
3653 "description": "If set, stack series on top of one another rather than drawing them independently."
3654 },
3655 "pointSize": {
3656 "default": "1",
3657 "labels": ["Data Line display"],
3658 "type": "integer",
3659 "description": "The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is \"isolated\", i.e. there is a missing point on either side of it. This also controls the size of those dots."
3660 },
3661 "labelsDivStyles": {
3662 "default": "null",
3663 "labels": ["Legend"],
3664 "type": "{}",
3665 "description": "Additional styles to apply to the currently-highlighted points div. For example, { 'font-weight': 'bold' } will make the labels bold."
3666 },
3667 "drawPoints": {
3668 "default": "false",
3669 "labels": ["Data Line display"],
3670 "type": "boolean",
3671 "description": "Draw a small dot at each point, in addition to a line going through the point. This makes the individual data points easier to see, but can increase visual clutter in the chart."
3672 },
3673 "height": {
3674 "default": "320",
3675 "labels": ["Overall display"],
3676 "type": "integer",
3677 "description": "Height, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored."
3678 },
3679 "zoomCallback": {
3680 "default": "null",
3681 "labels": ["Callbacks"],
3682 "type": "function(minDate, maxDate, yRanges)",
3683 "description": "A function to call when the zoom window is changed (either by zooming in or out). minDate and maxDate are milliseconds since epoch. yRanges is an array of [bottom, top] pairs, one for each y-axis."
3684 },
3685 "pointClickCallback": {
3686 "default": "",
3687 "labels": ["Callbacks", "Interactive Elements"],
3688 "type": "",
3689 "description": ""
3690 },
3691 "colors": {
3692 "default": "(see description)",
3693 "labels": ["Data Series Colors"],
3694 "type": "array<string>",
3695 "example": "['red', '#00FF00']",
3696 "description": "List of colors for the data series. These can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\", etc. If not specified, equally-spaced points around a color wheel are used."
3697 },
3698 "connectSeparatedPoints": {
3699 "default": "false",
3700 "labels": ["Data Line display"],
3701 "type": "boolean",
3702 "description": "Usually, when Dygraphs encounters a missing value in a data series, it interprets this as a gap and draws it as such. If, instead, the missing values represents an x-value for which only a different series has data, then you'll want to connect the dots by setting this to true. To explicitly include a gap with this option set, use a value of NaN."
3703 },
3704 "highlightCallback": {
3705 "default": "null",
3706 "labels": ["Callbacks"],
3707 "type": "function(event, x, points,row)",
3708 "description": "When set, this callback gets called every time a new point is highlighted. The parameters are the JavaScript mousemove event, the x-coordinate of the highlighted points and an array of highlighted points: <code>[ {name: 'series', yval: y-value}, &hellip; ]</code>"
3709 },
3710 "includeZero": {
3711 "default": "false",
3712 "labels": ["Axis display"],
3713 "type": "boolean",
3714 "description": "Usually, dygraphs will use the range of the data plus some padding to set the range of the y-axis. If this option is set, the y-axis will always include zero, typically as the lowest value. This can be used to avoid exaggerating the variance in the data"
3715 },
3716 "rollPeriod": {
3717 "default": "1",
3718 "labels": ["Error Bars", "Rolling Averages"],
3719 "type": "integer &gt;= 1",
3720 "description": "Number of days over which to average data. Discussed extensively above."
3721 },
3722 "unhighlightCallback": {
3723 "default": "null",
3724 "labels": ["Callbacks"],
3725 "type": "function(event)",
3726 "description": "When set, this callback gets called every time the user stops highlighting any point by mousing out of the graph. The parameter is the mouseout event."
3727 },
3728 "axisTickSize": {
3729 "default": "3.0",
3730 "labels": ["Axis display"],
3731 "type": "number",
3732 "description": "The size of the line to display next to each tick mark on x- or y-axes."
3733 },
3734 "labelsSeparateLines": {
3735 "default": "false",
3736 "labels": ["Legend"],
3737 "type": "boolean",
3738 "description": "Put <code>&lt;br/&gt;</code> between lines in the label string. Often used in conjunction with <strong>labelsDiv</strong>."
3739 },
3740 "xValueFormatter": {
3741 "default": "(Round to 2 decimal places)",
3742 "labels": ["Axis display"],
3743 "type": "function(x)",
3744 "description": "Function to provide a custom display format for the X value for mouseover."
3745 },
3746 "pixelsPerYLabel": {
3747 "default": "30",
3748 "labels": ["Axis display", "Grid"],
3749 "type": "integer",
3750 "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks."
3751 },
3752 "annotationMouseOverHandler": {
3753 "default": "null",
3754 "labels": ["Annotations"],
3755 "type": "function(annotation, point, dygraph, event)",
3756 "description": "If provided, this function is called whenever the user mouses over an annotation."
3757 },
3758 "annotationMouseOutHandler": {
3759 "default": "null",
3760 "labels": ["Annotations"],
3761 "type": "function(annotation, point, dygraph, event)",
3762 "description": "If provided, this function is called whenever the user mouses out of an annotation."
3763 },
3764 "annotationClickHandler": {
3765 "default": "null",
3766 "labels": ["Annotations"],
3767 "type": "function(annotation, point, dygraph, event)",
3768 "description": "If provided, this function is called whenever the user clicks on an annotation."
3769 },
3770 "annotationDblClickHandler": {
3771 "default": "null",
3772 "labels": ["Annotations"],
3773 "type": "function(annotation, point, dygraph, event)",
3774 "description": "If provided, this function is called whenever the user double-clicks on an annotation."
3775 },
3776 "drawCallback": {
3777 "default": "null",
3778 "labels": ["Callbacks"],
3779 "type": "function(dygraph, is_initial)",
3780 "description": "When set, this callback gets called every time the dygraph is drawn. This includes the initial draw, after zooming and repeatedly while panning. The first parameter is the dygraph being drawn. The second is a boolean value indicating whether this is the initial draw."
3781 },
3782 "labelsKMG2": {
3783 "default": "false",
3784 "labels": ["Value display/formatting"],
3785 "type": "boolean",
3786 "description": "Show k/M/G for kilo/Mega/Giga on y-axis. This is different than <code>labelsKMB</code> in that it uses base 2, not 10."
3787 },
3788 "delimiter": {
3789 "default": ",",
3790 "labels": ["CSV parsing"],
3791 "type": "string",
3792 "description": "The delimiter to look for when separating fields of a CSV file. Setting this to a tab is not usually necessary, since tab-delimited data is auto-detected."
3793 },
3794 "axisLabelFontSize": {
3795 "default": "14",
3796 "labels": ["Axis display"],
3797 "type": "integer",
3798 "description": "Size of the font (in pixels) to use in the axis labels, both x- and y-axis."
3799 },
3800 "underlayCallback": {
3801 "default": "null",
3802 "labels": ["Callbacks"],
3803 "type": "function(canvas, area, dygraph)",
3804 "description": "When set, this callback gets called before the chart is drawn. It details on how to use this."
3805 },
3806 "width": {
3807 "default": "480",
3808 "labels": ["Overall display"],
3809 "type": "integer",
3810 "description": "Width, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored."
3811 },
3812 "interactionModel": {
3813 "default": "...",
3814 "labels": ["Interactive Elements"],
3815 "type": "Object",
3816 "description": "TODO(konigsberg): document this"
3817 },
3818 "xTicker": {
3819 "default": "Dygraph.dateTicker or Dygraph.numericTicks",
3820 "labels": ["Axis display"],
3821 "type": "function(min, max, dygraph) -> [{v: ..., label: ...}, ...]",
3822 "description": "This lets you specify an arbitrary function to generate tick marks on an axis. The tick marks are an array of (value, label) pairs. The built-in functions go to great lengths to choose good tick marks so, if you set this option, you'll most likely want to call one of them and modify the result."
3823 },
3824 "xAxisLabelWidth": {
3825 "default": "50",
3826 "labels": ["Axis display"],
3827 "type": "integer",
3828 "description": "Width, in pixels, of the x-axis labels."
3829 },
3830 "showLabelsOnHighlight": {
3831 "default": "true",
3832 "labels": ["Interactive Elements", "Legend"],
3833 "type": "boolean",
3834 "description": "Whether to show the legend upon mouseover."
3835 },
3836 "axis": {
3837 "default": "(none)",
3838 "labels": ["Axis display"],
3839 "type": "string or object",
3840 "description": "Set to either an object ({}) filled with options for this axis or to the name of an existing data series with its own axis to re-use that axis. See tests for usage."
3841 },
3842 "pixelsPerXLabel": {
3843 "default": "60",
3844 "labels": ["Axis display", "Grid"],
3845 "type": "integer",
3846 "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks."
3847 },
3848 "labelsDiv": {
3849 "default": "null",
3850 "labels": ["Legend"],
3851 "type": "DOM element or string",
3852 "example": "<code style='font-size: small'>document.getElementById('foo')</code>or<code>'foo'",
3853 "description": "Show data labels in an external div, rather than on the graph. This value can either be a div element or a div id."
3854 },
3855 "fractions": {
3856 "default": "false",
3857 "labels": ["CSV parsing", "Error Bars"],
3858 "type": "boolean",
3859 "description": "When set, attempt to parse each cell in the CSV file as \"a/b\", where a and b are integers. The ratio will be plotted. This allows computation of Wilson confidence intervals (see below)."
3860 },
3861 "logscale": {
3862 "default": "false",
3863 "labels": ["Axis display"],
3864 "type": "boolean",
3865 "description": "When set for a y-axis, the graph shows that axis in log scale. Any values less than or equal to zero are not displayed.\n\nNot compatible with showZero, and ignores connectSeparatedPoints. Also, showing log scale with valueRanges that are less than zero will result in an unviewable graph."
3866 },
3867 "strokeWidth": {
3868 "default": "1.0",
3869 "labels": ["Data Line display"],
3870 "type": "integer",
3871 "example": "0.5, 2.0",
3872 "description": "The width of the lines connecting data points. This can be used to increase the contrast or some graphs."
3873 },
3874 "wilsonInterval": {
3875 "default": "true",
3876 "labels": ["Error Bars"],
3877 "type": "boolean",
3878 "description": "Use in conjunction with the \"fractions\" option. Instead of plotting +/- N standard deviations, dygraphs will compute a Wilson confidence interval and plot that. This has more reasonable behavior for ratios close to 0 or 1."
3879 },
3880 "fillGraph": {
3881 "default": "false",
3882 "labels": ["Data Line display"],
3883 "type": "boolean",
3884 "description": "Should the area underneath the graph be filled? This option is not compatible with error bars."
3885 },
3886 "highlightCircleSize": {
3887 "default": "3",
3888 "labels": ["Interactive Elements"],
3889 "type": "integer",
3890 "description": "The size in pixels of the dot drawn over highlighted points."
3891 },
3892 "gridLineColor": {
3893 "default": "rgb(128,128,128)",
3894 "labels": ["Grid"],
3895 "type": "red, blue",
3896 "description": "The color of the gridlines."
3897 },
3898 "visibility": {
3899 "default": "[true, true, ...]",
3900 "labels": ["Data Line display"],
3901 "type": "Array of booleans",
3902 "description": "Which series should initially be visible? Once the Dygraph has been constructed, you can access and modify the visibility of each series using the <code>visibility</code> and <code>setVisibility</code> methods."
3903 },
3904 "valueRange": {
3905 "default": "Full range of the input is shown",
3906 "labels": ["Axis display"],
3907 "type": "Array of two numbers",
3908 "example": "[10, 110]",
3909 "description": "Explicitly set the vertical range of the graph to [low, high]."
3910 },
3911 "labelsDivWidth": {
3912 "default": "250",
3913 "labels": ["Legend"],
3914 "type": "integer",
3915 "description": "Width (in pixels) of the div which shows information on the currently-highlighted points."
3916 },
3917 "colorSaturation": {
3918 "default": "1.0",
3919 "labels": ["Data Series Colors"],
3920 "type": "0.0 - 1.0",
3921 "description": "If <strong>colors</strong> is not specified, saturation of the automatically-generated data series colors."
3922 },
3923 "yAxisLabelWidth": {
3924 "default": "50",
3925 "labels": ["Axis display"],
3926 "type": "integer",
3927 "description": "Width, in pixels, of the y-axis labels."
3928 },
3929 "hideOverlayOnMouseOut": {
3930 "default": "true",
3931 "labels": ["Interactive Elements", "Legend"],
3932 "type": "boolean",
3933 "description": "Whether to hide the legend when the mouse leaves the chart area."
3934 },
3935 "yValueFormatter": {
3936 "default": "(Round to 2 decimal places)",
3937 "labels": ["Axis display"],
3938 "type": "function(x)",
3939 "description": "Function to provide a custom display format for the Y value for mouseover."
3940 },
3941 "legend": {
3942 "default": "onmouseover",
3943 "labels": ["Legend"],
3944 "type": "string",
3945 "description": "When to display the legend. By default, it only appears when a user mouses over the chart. Set it to \"always\" to always display a legend of some sort."
3946 },
3947 "labelsShowZeroValues": {
3948 "default": "true",
3949 "labels": ["Legend"],
3950 "type": "boolean",
3951 "description": "Show zero value labels in the labelsDiv."
3952 },
3953 "stepPlot": {
3954 "default": "false",
3955 "labels": ["Data Line display"],
3956 "type": "boolean",
3957 "description": "When set, display the graph as a step plot instead of a line plot."
3958 },
3959 "labelsKMB": {
3960 "default": "false",
3961 "labels": ["Value display/formatting"],
3962 "type": "boolean",
3963 "description": "Show K/M/B for thousands/millions/billions on y-axis."
3964 },
3965 "rightGap": {
3966 "default": "5",
3967 "labels": ["Overall display"],
3968 "type": "integer",
3969 "description": "Number of pixels to leave blank at the right edge of the Dygraph. This makes it easier to highlight the right-most data point."
3970 },
3971 "avoidMinZero": {
3972 "default": "false",
3973 "labels": ["Axis display"],
3974 "type": "boolean",
3975 "description": "When set, the heuristic that fixes the Y axis at zero for a data set with the minimum Y value of zero is disabled. \nThis is particularly useful for data sets that contain many zero values, especially for step plots which may otherwise have lines not visible running along the bottom axis."
3976 },
3977 "xAxisLabelFormatter": {
3978 "default": "Dygraph.dateAxisFormatter",
3979 "labels": ["Axis display", "Value display/formatting"],
3980 "type": "function(date, granularity)",
3981 "description": "Function to call to format values along the x axis."
3982 },
3983 "clickCallback": {
3984 "snippet": "function(e, date){<br>&nbsp;&nbsp;alert(date);<br>}",
3985 "default": "null",
3986 "labels": ["Callbacks"],
3987 "type": "function(e, date)",
3988 "description": "A function to call when a data point is clicked. The function should take two arguments, the event object for the click and the date that was clicked."
3989 },
3990 "yAxisLabelFormatter": {
3991 "default": "yValueFormatter",
3992 "labels": ["Axis display", "Value display/formatting"],
3993 "type": "function(x)",
3994 "description": "Function used to format values along the Y axis. By default it uses the same as the <code>yValueFormatter</code> unless specified."
3995 },
3996 "labels": {
3997 "default": "[\"X\", \"Y1\", \"Y2\", ...]*",
3998 "labels": ["Legend"],
3999 "type": "array<string>",
4000 "description": "A name for each data series, including the independent (X) series. For CSV files and DataTable objections, this is determined by context. For raw data, this must be specified. If it is not, default values are supplied and a warning is logged."
4001 },
4002 "dateWindow": {
4003 "default": "Full range of the input is shown",
4004 "labels": ["Axis display"],
4005 "type": "Array of two Dates or numbers",
4006 "example": "[<br>&nbsp;&nbsp;Date.parse('2006-01-01'),<br>&nbsp;&nbsp;(new Date()).valueOf()<br>]",
4007 "description": "Initially zoom in on a section of the graph. Is of the form [earliest, latest], where earliest/latest are milliseconds since epoch. If the data for the x-axis is numeric, the values in dateWindow must also be numbers."
4008 },
4009 "showRoller": {
4010 "default": "false",
4011 "labels": ["Interactive Elements", "Rolling Averages"],
4012 "type": "boolean",
4013 "description": "If the rolling average period text box should be shown."
4014 },
4015 "sigma": {
4016 "default": "2.0",
4017 "labels": ["Error Bars"],
4018 "type": "integer",
4019 "description": "When errorBars is set, shade this many standard deviations above/below each point."
4020 },
4021 "customBars": {
4022 "default": "false",
4023 "labels": ["CSV parsing", "Error Bars"],
4024 "type": "boolean",
4025 "description": "When set, parse each CSV cell as \"low;middle;high\". Error bars will be drawn for each point between low and high, with the series itself going through middle."
4026 },
4027 "colorValue": {
4028 "default": "1.0",
4029 "labels": ["Data Series Colors"],
4030 "type": "float (0.0 - 1.0)",
4031 "description": "If colors is not specified, value of the data series colors, as in hue/saturation/value. (0.0-1.0, default 0.5)"
4032 },
4033 "errorBars": {
4034 "default": "false",
4035 "labels": ["CSV parsing", "Error Bars"],
4036 "type": "boolean",
4037 "description": "Does the data contain standard deviations? Setting this to true alters the input format (see above)."
4038 },
4039 "displayAnnotations": {
4040 "default": "false",
4041 "labels": ["Annotations"],
4042 "type": "boolean",
4043 "description": "Only applies when Dygraphs is used as a GViz chart. Causes string columns following a data series to be interpreted as annotations on points in that series. This is the same format used by Google's AnnotatedTimeLine chart."
4044 }
4045 }
4046 ; // </JSON>
4047 // NOTE: in addition to parsing as JS, this snippet is expected to be valid
4048 // JSON. This assumption cannot be checked in JS, but it will be checked when
4049 // documentation is generated by the generate-documentation.py script.
4050
4051 // Do a quick sanity check on the options reference.
4052 (function() {
4053 var warn = function(msg) { if (console) console.warn(msg); };
4054 var flds = ['type', 'default', 'description'];
4055 var valid_cats = [
4056 'Annotations',
4057 'Axis display',
4058 'CSV parsing',
4059 'Callbacks',
4060 'Data Line display',
4061 'Data Series Colors',
4062 'Error Bars',
4063 'Grid',
4064 'Interactive Elements',
4065 'Legend',
4066 'Overall display',
4067 'Rolling Averages',
4068 'Value display/formatting'
4069 ];
4070 var cats = {};
4071 for (var i = 0; i < valid_cats.length; i++) cats[valid_cats[i]] = true;
4072
4073 for (var k in Dygraph.OPTIONS_REFERENCE) {
4074 if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(k)) continue;
4075 var op = Dygraph.OPTIONS_REFERENCE[k];
4076 for (var i = 0; i < flds.length; i++) {
4077 if (!op.hasOwnProperty(flds[i])) {
4078 warn('Option ' + k + ' missing "' + flds[i] + '" property');
4079 } else if (typeof(op[flds[i]]) != 'string') {
4080 warn(k + '.' + flds[i] + ' must be of type string');
4081 }
4082 }
4083 var labels = op['labels'];
4084 if (typeof(labels) !== 'object') {
4085 warn('Option "' + k + '" is missing a "labels": [...] option');
4086 for (var i = 0; i < labels.length; i++) {
4087 if (!cats.hasOwnProperty(labels[i])) {
4088 warn('Option "' + k + '" has label "' + labels[i] +
4089 '", which is invalid.');
4090 }
4091 }
4092 }
4093 }
4094 })();
4095 // </REMOVE_FOR_COMBINED>