ba2f31ed47b04aac15815795b21f2fa32c9bca07
[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
28 Date,SeriesA,SeriesB,...
29 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
30 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
31
32 If the 'fractions' option is set, the input should be of the form:
33
34 Date,SeriesA,SeriesB,...
35 YYYYMMDD,A1/B1,A2/B2,...
36 YYYYMMDD,A1/B1,A2/B2,...
37
38 And error bars will be calculated automatically using a binomial distribution.
39
40 For further documentation and examples, see http://www.danvk.org/dygraphs
41
42 */
43
44 /**
45 * An interactive, zoomable graph
46 * @param {String | Function} file A file containing CSV data or a function that
47 * returns this data. The expected format for each line is
48 * YYYYMMDD,val1,val2,... or, if attrs.errorBars is set,
49 * YYYYMMDD,val1,stddev1,val2,stddev2,...
50 * @param {Object} attrs Various other attributes, e.g. errorBars determines
51 * whether the input data contains error ranges.
52 */
53 Dygraph = function(div, data, opts) {
54 if (arguments.length > 0) {
55 if (arguments.length == 4) {
56 // Old versions of dygraphs took in the series labels as a constructor
57 // parameter. This doesn't make sense anymore, but it's easy to continue
58 // to support this usage.
59 this.warn("Using deprecated four-argument dygraph constructor");
60 this.__old_init__(div, data, arguments[2], arguments[3]);
61 } else {
62 this.__init__(div, data, opts);
63 }
64 }
65 };
66
67 Dygraph.NAME = "Dygraph";
68 Dygraph.VERSION = "1.2";
69 Dygraph.__repr__ = function() {
70 return "[" + this.NAME + " " + this.VERSION + "]";
71 };
72 Dygraph.toString = function() {
73 return this.__repr__();
74 };
75
76 // Various default values
77 Dygraph.DEFAULT_ROLL_PERIOD = 1;
78 Dygraph.DEFAULT_WIDTH = 480;
79 Dygraph.DEFAULT_HEIGHT = 320;
80 Dygraph.AXIS_LINE_WIDTH = 0.3;
81
82 // Default attribute values.
83 Dygraph.DEFAULT_ATTRS = {
84 highlightCircleSize: 3,
85 pixelsPerXLabel: 60,
86 pixelsPerYLabel: 30,
87
88 labelsDivWidth: 250,
89 labelsDivStyles: {
90 // TODO(danvk): move defaults from createStatusMessage_ here.
91 },
92 labelsSeparateLines: false,
93 labelsKMB: false,
94 labelsKMG2: false,
95
96 strokeWidth: 1.0,
97
98 axisTickSize: 3,
99 axisLabelFontSize: 14,
100 xAxisLabelWidth: 50,
101 yAxisLabelWidth: 50,
102 rightGap: 5,
103
104 showRoller: false,
105 xValueFormatter: Dygraph.dateString_,
106 xValueParser: Dygraph.dateParser,
107 xTicker: Dygraph.dateTicker,
108
109 delimiter: ',',
110
111 logScale: false,
112 sigma: 2.0,
113 errorBars: false,
114 fractions: false,
115 wilsonInterval: true, // only relevant if fractions is true
116 customBars: false,
117 fillGraph: false,
118 fillAlpha: 0.15,
119
120 stackedGraph: false,
121 hideOverlayOnMouseOut: true
122 };
123
124 // Various logging levels.
125 Dygraph.DEBUG = 1;
126 Dygraph.INFO = 2;
127 Dygraph.WARNING = 3;
128 Dygraph.ERROR = 3;
129
130 Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
131 // Labels is no longer a constructor parameter, since it's typically set
132 // directly from the data source. It also conains a name for the x-axis,
133 // which the previous constructor form did not.
134 if (labels != null) {
135 var new_labels = ["Date"];
136 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
137 Dygraph.update(attrs, { 'labels': new_labels });
138 }
139 this.__init__(div, file, attrs);
140 };
141
142 /**
143 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
144 * and interaction &lt;canvas&gt; inside of it. See the constructor for details
145 * on the parameters.
146 * @param {String | Function} file Source data
147 * @param {Array.<String>} labels Names of the data series
148 * @param {Object} attrs Miscellaneous other options
149 * @private
150 */
151 Dygraph.prototype.__init__ = function(div, file, attrs) {
152 // Support two-argument constructor
153 if (attrs == null) { attrs = {}; }
154
155 // Copy the important bits into the object
156 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
157 this.maindiv_ = div;
158 this.file_ = file;
159 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
160 this.previousVerticalX_ = -1;
161 this.fractions_ = attrs.fractions || false;
162 this.dateWindow_ = attrs.dateWindow || null;
163 this.valueRange_ = attrs.valueRange || null;
164 this.wilsonInterval_ = attrs.wilsonInterval || true;
165 this.is_initial_draw_ = true;
166
167 // Clear the div. This ensure that, if multiple dygraphs are passed the same
168 // div, then only one will be drawn.
169 div.innerHTML = "";
170
171 // If the div isn't already sized then inherit from our attrs or
172 // give it a default size.
173 if (div.style.width == '') {
174 div.style.width = attrs.width || Dygraph.DEFAULT_WIDTH + "px";
175 }
176 if (div.style.height == '') {
177 div.style.height = attrs.height || Dygraph.DEFAULT_HEIGHT + "px";
178 }
179 this.width_ = parseInt(div.style.width, 10);
180 this.height_ = parseInt(div.style.height, 10);
181 // The div might have been specified as percent of the current window size,
182 // convert that to an appropriate number of pixels.
183 if (div.style.width.indexOf("%") == div.style.width.length - 1) {
184 // Minus ten pixels keeps scrollbars from showing up for a 100% width div.
185 this.width_ = (this.width_ * self.innerWidth / 100) - 10;
186 }
187 if (div.style.height.indexOf("%") == div.style.height.length - 1) {
188 this.height_ = (this.height_ * self.innerHeight / 100) - 10;
189 }
190
191 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
192 if (attrs['stackedGraph']) {
193 attrs['fillGraph'] = true;
194 // TODO(nikhilk): Add any other stackedGraph checks here.
195 }
196
197 // Dygraphs has many options, some of which interact with one another.
198 // To keep track of everything, we maintain two sets of options:
199 //
200 // this.user_attrs_ only options explicitly set by the user.
201 // this.attrs_ defaults, options derived from user_attrs_, data.
202 //
203 // Options are then accessed this.attr_('attr'), which first looks at
204 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
205 // defaults without overriding behavior that the user specifically asks for.
206 this.user_attrs_ = {};
207 Dygraph.update(this.user_attrs_, attrs);
208
209 this.attrs_ = {};
210 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
211
212 // Make a note of whether labels will be pulled from the CSV file.
213 this.labelsFromCSV_ = (this.attr_("labels") == null);
214
215 // Create the containing DIV and other interactive elements
216 this.createInterface_();
217
218 this.start_();
219 };
220
221 Dygraph.prototype.attr_ = function(name) {
222 if (typeof(this.user_attrs_[name]) != 'undefined') {
223 return this.user_attrs_[name];
224 } else if (typeof(this.attrs_[name]) != 'undefined') {
225 return this.attrs_[name];
226 } else {
227 return null;
228 }
229 };
230
231 // TODO(danvk): any way I can get the line numbers to be this.warn call?
232 Dygraph.prototype.log = function(severity, message) {
233 if (typeof(console) != 'undefined') {
234 switch (severity) {
235 case Dygraph.DEBUG:
236 console.debug('dygraphs: ' + message);
237 break;
238 case Dygraph.INFO:
239 console.info('dygraphs: ' + message);
240 break;
241 case Dygraph.WARNING:
242 console.warn('dygraphs: ' + message);
243 break;
244 case Dygraph.ERROR:
245 console.error('dygraphs: ' + message);
246 break;
247 }
248 }
249 }
250 Dygraph.prototype.info = function(message) {
251 this.log(Dygraph.INFO, message);
252 }
253 Dygraph.prototype.warn = function(message) {
254 this.log(Dygraph.WARNING, message);
255 }
256 Dygraph.prototype.error = function(message) {
257 this.log(Dygraph.ERROR, message);
258 }
259
260 /**
261 * Returns the current rolling period, as set by the user or an option.
262 * @return {Number} The number of days in the rolling window
263 */
264 Dygraph.prototype.rollPeriod = function() {
265 return this.rollPeriod_;
266 };
267
268 /**
269 * Returns the currently-visible x-range. This can be affected by zooming,
270 * panning or a call to updateOptions.
271 * Returns a two-element array: [left, right].
272 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
273 */
274 Dygraph.prototype.xAxisRange = function() {
275 if (this.dateWindow_) return this.dateWindow_;
276
277 // The entire chart is visible.
278 var left = this.rawData_[0][0];
279 var right = this.rawData_[this.rawData_.length - 1][0];
280 return [left, right];
281 };
282
283 Dygraph.addEvent = function(el, evt, fn) {
284 var normed_fn = function(e) {
285 if (!e) var e = window.event;
286 fn(e);
287 };
288 if (window.addEventListener) { // Mozilla, Netscape, Firefox
289 el.addEventListener(evt, normed_fn, false);
290 } else { // IE
291 el.attachEvent('on' + evt, normed_fn);
292 }
293 };
294
295 Dygraph.clipCanvas_ = function(cnv, clip) {
296 var ctx = cnv.getContext("2d");
297 ctx.beginPath();
298 ctx.rect(clip.left, clip.top, clip.width, clip.height);
299 ctx.clip();
300 };
301
302 /**
303 * Generates interface elements for the Dygraph: a containing div, a div to
304 * display the current point, and a textbox to adjust the rolling average
305 * period. Also creates the Renderer/Layout elements.
306 * @private
307 */
308 Dygraph.prototype.createInterface_ = function() {
309 // Create the all-enclosing graph div
310 var enclosing = this.maindiv_;
311
312 this.graphDiv = document.createElement("div");
313 this.graphDiv.style.width = this.width_ + "px";
314 this.graphDiv.style.height = this.height_ + "px";
315 enclosing.appendChild(this.graphDiv);
316
317 var clip = {
318 top: 0,
319 left: this.attr_("yAxisLabelWidth") + 2 * this.attr_("axisTickSize")
320 };
321 clip.width = this.width_ - clip.left - this.attr_("rightGap");
322 clip.height = this.height_ - this.attr_("axisLabelFontSize")
323 - 2 * this.attr_("axisTickSize");
324 this.clippingArea_ = clip;
325
326 // Create the canvas for interactive parts of the chart.
327 this.canvas_ = Dygraph.createCanvas();
328 this.canvas_.style.position = "absolute";
329 this.canvas_.width = this.width_;
330 this.canvas_.height = this.height_;
331 this.canvas_.style.width = this.width_ + "px"; // for IE
332 this.canvas_.style.height = this.height_ + "px"; // for IE
333 this.graphDiv.appendChild(this.canvas_);
334
335 // ... and for static parts of the chart.
336 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
337
338 // Make sure we don't overdraw.
339 Dygraph.clipCanvas_(this.hidden_, this.clippingArea_);
340 Dygraph.clipCanvas_(this.canvas_, this.clippingArea_);
341
342 var dygraph = this;
343 Dygraph.addEvent(this.hidden_, 'mousemove', function(e) {
344 dygraph.mouseMove_(e);
345 });
346 Dygraph.addEvent(this.hidden_, 'mouseout', function(e) {
347 dygraph.mouseOut_(e);
348 });
349
350 // Create the grapher
351 // TODO(danvk): why does the Layout need its own set of options?
352 this.layoutOptions_ = { 'xOriginIsZero': false };
353 Dygraph.update(this.layoutOptions_, this.attrs_);
354 Dygraph.update(this.layoutOptions_, this.user_attrs_);
355 Dygraph.update(this.layoutOptions_, {
356 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
357
358 this.layout_ = new DygraphLayout(this, this.layoutOptions_);
359
360 // TODO(danvk): why does the Renderer need its own set of options?
361 this.renderOptions_ = { colorScheme: this.colors_,
362 strokeColor: null,
363 axisLineWidth: Dygraph.AXIS_LINE_WIDTH };
364 Dygraph.update(this.renderOptions_, this.attrs_);
365 Dygraph.update(this.renderOptions_, this.user_attrs_);
366 this.plotter_ = new DygraphCanvasRenderer(this,
367 this.hidden_, this.layout_,
368 this.renderOptions_);
369
370 this.createStatusMessage_();
371 this.createRollInterface_();
372 this.createDragInterface_();
373 };
374
375 /**
376 * Detach DOM elements in the dygraph and null out all data references.
377 * Calling this when you're done with a dygraph can dramatically reduce memory
378 * usage. See, e.g., the tests/perf.html example.
379 */
380 Dygraph.prototype.destroy = function() {
381 var removeRecursive = function(node) {
382 while (node.hasChildNodes()) {
383 removeRecursive(node.firstChild);
384 node.removeChild(node.firstChild);
385 }
386 };
387 removeRecursive(this.maindiv_);
388
389 var nullOut = function(obj) {
390 for (var n in obj) {
391 if (typeof(obj[n]) === 'object') {
392 obj[n] = null;
393 }
394 }
395 };
396
397 // These may not all be necessary, but it can't hurt...
398 nullOut(this.layout_);
399 nullOut(this.plotter_);
400 nullOut(this);
401 };
402
403 /**
404 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
405 * this particular canvas. All Dygraph work is done on this.canvas_.
406 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
407 * @return {Object} The newly-created canvas
408 * @private
409 */
410 Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
411 var h = Dygraph.createCanvas();
412 h.style.position = "absolute";
413 // TODO(danvk): h should be offset from canvas. canvas needs to include
414 // some extra area to make it easier to zoom in on the far left and far
415 // right. h needs to be precisely the plot area, so that clipping occurs.
416 h.style.top = canvas.style.top;
417 h.style.left = canvas.style.left;
418 h.width = this.width_;
419 h.height = this.height_;
420 h.style.width = this.width_ + "px"; // for IE
421 h.style.height = this.height_ + "px"; // for IE
422 this.graphDiv.appendChild(h);
423 return h;
424 };
425
426 // Taken from MochiKit.Color
427 Dygraph.hsvToRGB = function (hue, saturation, value) {
428 var red;
429 var green;
430 var blue;
431 if (saturation === 0) {
432 red = value;
433 green = value;
434 blue = value;
435 } else {
436 var i = Math.floor(hue * 6);
437 var f = (hue * 6) - i;
438 var p = value * (1 - saturation);
439 var q = value * (1 - (saturation * f));
440 var t = value * (1 - (saturation * (1 - f)));
441 switch (i) {
442 case 1: red = q; green = value; blue = p; break;
443 case 2: red = p; green = value; blue = t; break;
444 case 3: red = p; green = q; blue = value; break;
445 case 4: red = t; green = p; blue = value; break;
446 case 5: red = value; green = p; blue = q; break;
447 case 6: // fall through
448 case 0: red = value; green = t; blue = p; break;
449 }
450 }
451 red = Math.floor(255 * red + 0.5);
452 green = Math.floor(255 * green + 0.5);
453 blue = Math.floor(255 * blue + 0.5);
454 return 'rgb(' + red + ',' + green + ',' + blue + ')';
455 };
456
457
458 /**
459 * Generate a set of distinct colors for the data series. This is done with a
460 * color wheel. Saturation/Value are customizable, and the hue is
461 * equally-spaced around the color wheel. If a custom set of colors is
462 * specified, that is used instead.
463 * @private
464 */
465 Dygraph.prototype.setColors_ = function() {
466 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
467 // away with this.renderOptions_.
468 var num = this.attr_("labels").length - 1;
469 this.colors_ = [];
470 var colors = this.attr_('colors');
471 if (!colors) {
472 var sat = this.attr_('colorSaturation') || 1.0;
473 var val = this.attr_('colorValue') || 0.5;
474 for (var i = 1; i <= num; i++) {
475 if (!this.visibility()[i-1]) continue;
476 // alternate colors for high contrast.
477 var idx = i - parseInt(i % 2 ? i / 2 : (i - num)/2, 10);
478 var hue = (1.0 * idx/ (1 + num));
479 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
480 }
481 } else {
482 for (var i = 0; i < num; i++) {
483 if (!this.visibility()[i]) continue;
484 var colorStr = colors[i % colors.length];
485 this.colors_.push(colorStr);
486 }
487 }
488
489 // TODO(danvk): update this w/r/t/ the new options system.
490 this.renderOptions_.colorScheme = this.colors_;
491 Dygraph.update(this.plotter_.options, this.renderOptions_);
492 Dygraph.update(this.layoutOptions_, this.user_attrs_);
493 Dygraph.update(this.layoutOptions_, this.attrs_);
494 }
495
496 /**
497 * Return the list of colors. This is either the list of colors passed in the
498 * attributes, or the autogenerated list of rgb(r,g,b) strings.
499 * @return {Array<string>} The list of colors.
500 */
501 Dygraph.prototype.getColors = function() {
502 return this.colors_;
503 };
504
505 // The following functions are from quirksmode.org with a modification for Safari from
506 // http://blog.firetree.net/2005/07/04/javascript-find-position/
507 // http://www.quirksmode.org/js/findpos.html
508 Dygraph.findPosX = function(obj) {
509 var curleft = 0;
510 if(obj.offsetParent)
511 while(1)
512 {
513 curleft += obj.offsetLeft;
514 if(!obj.offsetParent)
515 break;
516 obj = obj.offsetParent;
517 }
518 else if(obj.x)
519 curleft += obj.x;
520 return curleft;
521 };
522
523 Dygraph.findPosY = function(obj) {
524 var curtop = 0;
525 if(obj.offsetParent)
526 while(1)
527 {
528 curtop += obj.offsetTop;
529 if(!obj.offsetParent)
530 break;
531 obj = obj.offsetParent;
532 }
533 else if(obj.y)
534 curtop += obj.y;
535 return curtop;
536 };
537
538
539
540 /**
541 * Create the div that contains information on the selected point(s)
542 * This goes in the top right of the canvas, unless an external div has already
543 * been specified.
544 * @private
545 */
546 Dygraph.prototype.createStatusMessage_ = function(){
547 if (!this.attr_("labelsDiv")) {
548 var divWidth = this.attr_('labelsDivWidth');
549 var messagestyle = {
550 "position": "absolute",
551 "fontSize": "14px",
552 "zIndex": 10,
553 "width": divWidth + "px",
554 "top": "0px",
555 "left": (this.width_ - divWidth - 2) + "px",
556 "background": "white",
557 "textAlign": "left",
558 "overflow": "hidden"};
559 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
560 var div = document.createElement("div");
561 for (var name in messagestyle) {
562 if (messagestyle.hasOwnProperty(name)) {
563 div.style[name] = messagestyle[name];
564 }
565 }
566 this.graphDiv.appendChild(div);
567 this.attrs_.labelsDiv = div;
568 }
569 };
570
571 /**
572 * Create the text box to adjust the averaging period
573 * @return {Object} The newly-created text box
574 * @private
575 */
576 Dygraph.prototype.createRollInterface_ = function() {
577 var display = this.attr_('showRoller') ? "block" : "none";
578 var textAttr = { "position": "absolute",
579 "zIndex": 10,
580 "top": (this.plotter_.area.h - 25) + "px",
581 "left": (this.plotter_.area.x + 1) + "px",
582 "display": display
583 };
584 var roller = document.createElement("input");
585 roller.type = "text";
586 roller.size = "2";
587 roller.value = this.rollPeriod_;
588 for (var name in textAttr) {
589 if (textAttr.hasOwnProperty(name)) {
590 roller.style[name] = textAttr[name];
591 }
592 }
593
594 var pa = this.graphDiv;
595 pa.appendChild(roller);
596 var dygraph = this;
597 roller.onchange = function() { dygraph.adjustRoll(roller.value); };
598 return roller;
599 };
600
601 // These functions are taken from MochiKit.Signal
602 Dygraph.pageX = function(e) {
603 if (e.pageX) {
604 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
605 } else {
606 var de = document;
607 var b = document.body;
608 return e.clientX +
609 (de.scrollLeft || b.scrollLeft) -
610 (de.clientLeft || 0);
611 }
612 };
613
614 Dygraph.pageY = function(e) {
615 if (e.pageY) {
616 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
617 } else {
618 var de = document;
619 var b = document.body;
620 return e.clientY +
621 (de.scrollTop || b.scrollTop) -
622 (de.clientTop || 0);
623 }
624 };
625
626 /**
627 * Set up all the mouse handlers needed to capture dragging behavior for zoom
628 * events.
629 * @private
630 */
631 Dygraph.prototype.createDragInterface_ = function() {
632 var self = this;
633
634 // Tracks whether the mouse is down right now
635 var isZooming = false;
636 var isPanning = false;
637 var dragStartX = null;
638 var dragStartY = null;
639 var dragEndX = null;
640 var dragEndY = null;
641 var prevEndX = null;
642 var draggingDate = null;
643 var dateRange = null;
644
645 // Utility function to convert page-wide coordinates to canvas coords
646 var px = 0;
647 var py = 0;
648 var getX = function(e) { return Dygraph.pageX(e) - px };
649 var getY = function(e) { return Dygraph.pageX(e) - py };
650
651 // Draw zoom rectangles when the mouse is down and the user moves around
652 Dygraph.addEvent(this.hidden_, 'mousemove', function(event) {
653 if (isZooming) {
654 dragEndX = getX(event);
655 dragEndY = getY(event);
656
657 self.drawZoomRect_(dragStartX, dragEndX, prevEndX);
658 prevEndX = dragEndX;
659 } else if (isPanning) {
660 dragEndX = getX(event);
661 dragEndY = getY(event);
662
663 // Want to have it so that:
664 // 1. draggingDate appears at dragEndX
665 // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
666
667 self.dateWindow_[0] = draggingDate - (dragEndX / self.width_) * dateRange;
668 self.dateWindow_[1] = self.dateWindow_[0] + dateRange;
669 self.drawGraph_(self.rawData_);
670 }
671 });
672
673 // Track the beginning of drag events
674 Dygraph.addEvent(this.hidden_, 'mousedown', function(event) {
675 px = Dygraph.findPosX(self.canvas_);
676 py = Dygraph.findPosY(self.canvas_);
677 dragStartX = getX(event);
678 dragStartY = getY(event);
679
680 if (event.altKey || event.shiftKey) {
681 if (!self.dateWindow_) return; // have to be zoomed in to pan.
682 isPanning = true;
683 dateRange = self.dateWindow_[1] - self.dateWindow_[0];
684 draggingDate = (dragStartX / self.width_) * dateRange +
685 self.dateWindow_[0];
686 } else {
687 isZooming = true;
688 }
689 });
690
691 // If the user releases the mouse button during a drag, but not over the
692 // canvas, then it doesn't count as a zooming action.
693 Dygraph.addEvent(document, 'mouseup', function(event) {
694 if (isZooming || isPanning) {
695 isZooming = false;
696 dragStartX = null;
697 dragStartY = null;
698 }
699
700 if (isPanning) {
701 isPanning = false;
702 draggingDate = null;
703 dateRange = null;
704 }
705 });
706
707 // Temporarily cancel the dragging event when the mouse leaves the graph
708 Dygraph.addEvent(this.hidden_, 'mouseout', function(event) {
709 if (isZooming) {
710 dragEndX = null;
711 dragEndY = null;
712 }
713 });
714
715 // If the mouse is released on the canvas during a drag event, then it's a
716 // zoom. Only do the zoom if it's over a large enough area (>= 10 pixels)
717 Dygraph.addEvent(this.hidden_, 'mouseup', function(event) {
718 if (isZooming) {
719 isZooming = false;
720 dragEndX = getX(event);
721 dragEndY = getY(event);
722 var regionWidth = Math.abs(dragEndX - dragStartX);
723 var regionHeight = Math.abs(dragEndY - dragStartY);
724
725 if (regionWidth < 2 && regionHeight < 2 &&
726 self.attr_('clickCallback') != null &&
727 self.lastx_ != undefined) {
728 // TODO(danvk): pass along more info about the points.
729 self.attr_('clickCallback')(event, self.lastx_, self.selPoints_);
730 }
731
732 if (regionWidth >= 10) {
733 self.doZoom_(Math.min(dragStartX, dragEndX),
734 Math.max(dragStartX, dragEndX));
735 } else {
736 self.canvas_.getContext("2d").clearRect(0, 0,
737 self.canvas_.width,
738 self.canvas_.height);
739 }
740
741 dragStartX = null;
742 dragStartY = null;
743 }
744
745 if (isPanning) {
746 isPanning = false;
747 draggingDate = null;
748 dateRange = null;
749 }
750 });
751
752 // Double-clicking zooms back out
753 Dygraph.addEvent(this.hidden_, 'dblclick', function(event) {
754 if (self.dateWindow_ == null) return;
755 self.dateWindow_ = null;
756 self.drawGraph_(self.rawData_);
757 var minDate = self.rawData_[0][0];
758 var maxDate = self.rawData_[self.rawData_.length - 1][0];
759 if (self.attr_("zoomCallback")) {
760 self.attr_("zoomCallback")(minDate, maxDate);
761 }
762 });
763 };
764
765 /**
766 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
767 * up any previous zoom rectangles that were drawn. This could be optimized to
768 * avoid extra redrawing, but it's tricky to avoid interactions with the status
769 * dots.
770 * @param {Number} startX The X position where the drag started, in canvas
771 * coordinates.
772 * @param {Number} endX The current X position of the drag, in canvas coords.
773 * @param {Number} prevEndX The value of endX on the previous call to this
774 * function. Used to avoid excess redrawing
775 * @private
776 */
777 Dygraph.prototype.drawZoomRect_ = function(startX, endX, prevEndX) {
778 var ctx = this.canvas_.getContext("2d");
779
780 // Clean up from the previous rect if necessary
781 if (prevEndX) {
782 ctx.clearRect(Math.min(startX, prevEndX), 0,
783 Math.abs(startX - prevEndX), this.height_);
784 }
785
786 // Draw a light-grey rectangle to show the new viewing area
787 if (endX && startX) {
788 ctx.fillStyle = "rgba(128,128,128,0.33)";
789 ctx.fillRect(Math.min(startX, endX), 0,
790 Math.abs(endX - startX), this.height_);
791 }
792 };
793
794 /**
795 * Zoom to something containing [lowX, highX]. These are pixel coordinates
796 * in the canvas. The exact zoom window may be slightly larger if there are no
797 * data points near lowX or highX. This function redraws the graph.
798 * @param {Number} lowX The leftmost pixel value that should be visible.
799 * @param {Number} highX The rightmost pixel value that should be visible.
800 * @private
801 */
802 Dygraph.prototype.doZoom_ = function(lowX, highX) {
803 // Find the earliest and latest dates contained in this canvasx range.
804 var points = this.layout_.points;
805 var minDate = null;
806 var maxDate = null;
807 // Find the nearest [minDate, maxDate] that contains [lowX, highX]
808 for (var i = 0; i < points.length; i++) {
809 var cx = points[i].canvasx;
810 var x = points[i].xval;
811 if (cx < lowX && (minDate == null || x > minDate)) minDate = x;
812 if (cx > highX && (maxDate == null || x < maxDate)) maxDate = x;
813 }
814 // Use the extremes if either is missing
815 if (minDate == null) minDate = points[0].xval;
816 if (maxDate == null) maxDate = points[points.length-1].xval;
817
818 this.dateWindow_ = [minDate, maxDate];
819 this.drawGraph_(this.rawData_);
820 if (this.attr_("zoomCallback")) {
821 this.attr_("zoomCallback")(minDate, maxDate);
822 }
823 };
824
825 /**
826 * When the mouse moves in the canvas, display information about a nearby data
827 * point and draw dots over those points in the data series. This function
828 * takes care of cleanup of previously-drawn dots.
829 * @param {Object} event The mousemove event from the browser.
830 * @private
831 */
832 Dygraph.prototype.mouseMove_ = function(event) {
833 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.hidden_);
834 var points = this.layout_.points;
835
836 var lastx = -1;
837 var lasty = -1;
838
839 // Loop through all the points and find the date nearest to our current
840 // location.
841 var minDist = 1e+100;
842 var idx = -1;
843 for (var i = 0; i < points.length; i++) {
844 var dist = Math.abs(points[i].canvasx - canvasx);
845 if (dist > minDist) break;
846 minDist = dist;
847 idx = i;
848 }
849 if (idx >= 0) lastx = points[idx].xval;
850 // Check that you can really highlight the last day's data
851 if (canvasx > points[points.length-1].canvasx)
852 lastx = points[points.length-1].xval;
853
854 // Extract the points we've selected
855 this.selPoints_ = [];
856 for (var i = 0; i < points.length; i++) {
857 if (points[i].xval == lastx) {
858 this.selPoints_.push(points[i]);
859 }
860 }
861
862 if (this.attr_("highlightCallback")) {
863 var px = this.lastHighlightCallbackX;
864 if (px !== null && lastx != px) {
865 // only fire if the selected point has changed.
866 this.lastHighlightCallbackX = lastx;
867 if (!this.attr_("stackedGraph")) {
868 this.attr_("highlightCallback")(event, lastx, this.selPoints_);
869 } else {
870 // "unstack" the points.
871 var callbackPoints = this.selPoints_.map(
872 function(p) { return {xval: p.xval, yval: p.yval, name: p.name} });
873 var cumulative_sum = 0;
874 for (var j = callbackPoints.length - 1; j >= 0; j--) {
875 callbackPoints[j].yval -= cumulative_sum;
876 cumulative_sum += callbackPoints[j].yval;
877 }
878 this.attr_("highlightCallback")(event, lastx, callbackPoints);
879 }
880 }
881 }
882
883 // Clear the previously drawn vertical, if there is one
884 var circleSize = this.attr_('highlightCircleSize');
885 var ctx = this.canvas_.getContext("2d");
886 if (this.previousVerticalX_ >= 0) {
887 var px = this.previousVerticalX_;
888 ctx.clearRect(px - circleSize - 1, 0, 2 * circleSize + 2, this.height_);
889 }
890
891 var isOK = function(x) { return x && !isNaN(x); };
892
893 if (this.selPoints_.length > 0) {
894 var canvasx = this.selPoints_[0].canvasx;
895
896 // Set the status message to indicate the selected point(s)
897 var replace = this.attr_('xValueFormatter')(lastx, this) + ":";
898 var clen = this.colors_.length;
899 for (var i = 0; i < this.selPoints_.length; i++) {
900 if (!isOK(this.selPoints_[i].canvasy)) continue;
901 if (this.attr_("labelsSeparateLines")) {
902 replace += "<br/>";
903 }
904 var point = this.selPoints_[i];
905 var c = new RGBColor(this.colors_[i%clen]);
906 replace += " <b><font color='" + c.toHex() + "'>"
907 + point.name + "</font></b>:"
908 + this.round_(point.yval, 2);
909 }
910 this.attr_("labelsDiv").innerHTML = replace;
911
912 // Save last x position for callbacks.
913 this.lastx_ = lastx;
914
915 // Draw colored circles over the center of each selected point
916 ctx.save();
917 for (var i = 0; i < this.selPoints_.length; i++) {
918 if (!isOK(this.selPoints_[i%clen].canvasy)) continue;
919 ctx.beginPath();
920 ctx.fillStyle = this.colors_[i%clen];
921 ctx.arc(canvasx, this.selPoints_[i%clen].canvasy, circleSize,
922 0, 2 * Math.PI, false);
923 ctx.fill();
924 }
925 ctx.restore();
926
927 this.previousVerticalX_ = canvasx;
928 }
929 };
930
931 /**
932 * The mouse has left the canvas. Clear out whatever artifacts remain
933 * @param {Object} event the mouseout event from the browser.
934 * @private
935 */
936 Dygraph.prototype.mouseOut_ = function(event) {
937 if (this.attr_("hideOverlayOnMouseOut")) {
938 // Get rid of the overlay data
939 var ctx = this.canvas_.getContext("2d");
940 ctx.clearRect(0, 0, this.width_, this.height_);
941 this.attr_("labelsDiv").innerHTML = "";
942 }
943 };
944
945 Dygraph.zeropad = function(x) {
946 if (x < 10) return "0" + x; else return "" + x;
947 }
948
949 /**
950 * Return a string version of the hours, minutes and seconds portion of a date.
951 * @param {Number} date The JavaScript date (ms since epoch)
952 * @return {String} A time of the form "HH:MM:SS"
953 * @private
954 */
955 Dygraph.prototype.hmsString_ = function(date) {
956 var zeropad = Dygraph.zeropad;
957 var d = new Date(date);
958 if (d.getSeconds()) {
959 return zeropad(d.getHours()) + ":" +
960 zeropad(d.getMinutes()) + ":" +
961 zeropad(d.getSeconds());
962 } else {
963 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
964 }
965 }
966
967 /**
968 * Convert a JS date (millis since epoch) to YYYY/MM/DD
969 * @param {Number} date The JavaScript date (ms since epoch)
970 * @return {String} A date of the form "YYYY/MM/DD"
971 * @private
972 * TODO(danvk): why is this part of the prototype?
973 */
974 Dygraph.dateString_ = function(date, self) {
975 var zeropad = Dygraph.zeropad;
976 var d = new Date(date);
977
978 // Get the year:
979 var year = "" + d.getFullYear();
980 // Get a 0 padded month string
981 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
982 // Get a 0 padded day string
983 var day = zeropad(d.getDate());
984
985 var ret = "";
986 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
987 if (frac) ret = " " + self.hmsString_(date);
988
989 return year + "/" + month + "/" + day + ret;
990 };
991
992 /**
993 * Round a number to the specified number of digits past the decimal point.
994 * @param {Number} num The number to round
995 * @param {Number} places The number of decimals to which to round
996 * @return {Number} The rounded number
997 * @private
998 */
999 Dygraph.prototype.round_ = function(num, places) {
1000 var shift = Math.pow(10, places);
1001 return Math.round(num * shift)/shift;
1002 };
1003
1004 /**
1005 * Fires when there's data available to be graphed.
1006 * @param {String} data Raw CSV data to be plotted
1007 * @private
1008 */
1009 Dygraph.prototype.loadedEvent_ = function(data) {
1010 this.rawData_ = this.parseCSV_(data);
1011 this.drawGraph_(this.rawData_);
1012 };
1013
1014 Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
1015 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1016 Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
1017
1018 /**
1019 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1020 * @private
1021 */
1022 Dygraph.prototype.addXTicks_ = function() {
1023 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1024 var startDate, endDate;
1025 if (this.dateWindow_) {
1026 startDate = this.dateWindow_[0];
1027 endDate = this.dateWindow_[1];
1028 } else {
1029 startDate = this.rawData_[0][0];
1030 endDate = this.rawData_[this.rawData_.length - 1][0];
1031 }
1032
1033 var xTicks = this.attr_('xTicker')(startDate, endDate, this);
1034 this.layout_.updateOptions({xTicks: xTicks});
1035 };
1036
1037 // Time granularity enumeration
1038 Dygraph.SECONDLY = 0;
1039 Dygraph.TWO_SECONDLY = 1;
1040 Dygraph.FIVE_SECONDLY = 2;
1041 Dygraph.TEN_SECONDLY = 3;
1042 Dygraph.THIRTY_SECONDLY = 4;
1043 Dygraph.MINUTELY = 5;
1044 Dygraph.TWO_MINUTELY = 6;
1045 Dygraph.FIVE_MINUTELY = 7;
1046 Dygraph.TEN_MINUTELY = 8;
1047 Dygraph.THIRTY_MINUTELY = 9;
1048 Dygraph.HOURLY = 10;
1049 Dygraph.TWO_HOURLY = 11;
1050 Dygraph.SIX_HOURLY = 12;
1051 Dygraph.DAILY = 13;
1052 Dygraph.WEEKLY = 14;
1053 Dygraph.MONTHLY = 15;
1054 Dygraph.QUARTERLY = 16;
1055 Dygraph.BIANNUAL = 17;
1056 Dygraph.ANNUAL = 18;
1057 Dygraph.DECADAL = 19;
1058 Dygraph.NUM_GRANULARITIES = 20;
1059
1060 Dygraph.SHORT_SPACINGS = [];
1061 Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
1062 Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
1063 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
1064 Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
1065 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
1066 Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
1067 Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
1068 Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
1069 Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
1070 Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
1071 Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
1072 Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
1073 Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
1074 Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
1075 Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
1076
1077 // NumXTicks()
1078 //
1079 // If we used this time granularity, how many ticks would there be?
1080 // This is only an approximation, but it's generally good enough.
1081 //
1082 Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
1083 if (granularity < Dygraph.MONTHLY) {
1084 // Generate one tick mark for every fixed interval of time.
1085 var spacing = Dygraph.SHORT_SPACINGS[granularity];
1086 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
1087 } else {
1088 var year_mod = 1; // e.g. to only print one point every 10 years.
1089 var num_months = 12;
1090 if (granularity == Dygraph.QUARTERLY) num_months = 3;
1091 if (granularity == Dygraph.BIANNUAL) num_months = 2;
1092 if (granularity == Dygraph.ANNUAL) num_months = 1;
1093 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
1094
1095 var msInYear = 365.2524 * 24 * 3600 * 1000;
1096 var num_years = 1.0 * (end_time - start_time) / msInYear;
1097 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
1098 }
1099 };
1100
1101 // GetXAxis()
1102 //
1103 // Construct an x-axis of nicely-formatted times on meaningful boundaries
1104 // (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1105 //
1106 // Returns an array containing {v: millis, label: label} dictionaries.
1107 //
1108 Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
1109 var ticks = [];
1110 if (granularity < Dygraph.MONTHLY) {
1111 // Generate one tick mark for every fixed interval of time.
1112 var spacing = Dygraph.SHORT_SPACINGS[granularity];
1113 var format = '%d%b'; // e.g. "1Jan"
1114
1115 // Find a time less than start_time which occurs on a "nice" time boundary
1116 // for this granularity.
1117 var g = spacing / 1000;
1118 var d = new Date(start_time);
1119 if (g <= 60) { // seconds
1120 var x = d.getSeconds(); d.setSeconds(x - x % g);
1121 } else {
1122 d.setSeconds(0);
1123 g /= 60;
1124 if (g <= 60) { // minutes
1125 var x = d.getMinutes(); d.setMinutes(x - x % g);
1126 } else {
1127 d.setMinutes(0);
1128 g /= 60;
1129
1130 if (g <= 24) { // days
1131 var x = d.getHours(); d.setHours(x - x % g);
1132 } else {
1133 d.setHours(0);
1134 g /= 24;
1135
1136 if (g == 7) { // one week
1137 d.setDate(d.getDate() - d.getDay());
1138 }
1139 }
1140 }
1141 }
1142 start_time = d.getTime();
1143
1144 for (var t = start_time; t <= end_time; t += spacing) {
1145 var d = new Date(t);
1146 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
1147 if (frac == 0 || granularity >= Dygraph.DAILY) {
1148 // the extra hour covers DST problems.
1149 ticks.push({ v:t, label: new Date(t + 3600*1000).strftime(format) });
1150 } else {
1151 ticks.push({ v:t, label: this.hmsString_(t) });
1152 }
1153 }
1154 } else {
1155 // Display a tick mark on the first of a set of months of each year.
1156 // Years get a tick mark iff y % year_mod == 0. This is useful for
1157 // displaying a tick mark once every 10 years, say, on long time scales.
1158 var months;
1159 var year_mod = 1; // e.g. to only print one point every 10 years.
1160
1161 if (granularity == Dygraph.MONTHLY) {
1162 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
1163 } else if (granularity == Dygraph.QUARTERLY) {
1164 months = [ 0, 3, 6, 9 ];
1165 } else if (granularity == Dygraph.BIANNUAL) {
1166 months = [ 0, 6 ];
1167 } else if (granularity == Dygraph.ANNUAL) {
1168 months = [ 0 ];
1169 } else if (granularity == Dygraph.DECADAL) {
1170 months = [ 0 ];
1171 year_mod = 10;
1172 }
1173
1174 var start_year = new Date(start_time).getFullYear();
1175 var end_year = new Date(end_time).getFullYear();
1176 var zeropad = Dygraph.zeropad;
1177 for (var i = start_year; i <= end_year; i++) {
1178 if (i % year_mod != 0) continue;
1179 for (var j = 0; j < months.length; j++) {
1180 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
1181 var t = Date.parse(date_str);
1182 if (t < start_time || t > end_time) continue;
1183 ticks.push({ v:t, label: new Date(t).strftime('%b %y') });
1184 }
1185 }
1186 }
1187
1188 return ticks;
1189 };
1190
1191
1192 /**
1193 * Add ticks to the x-axis based on a date range.
1194 * @param {Number} startDate Start of the date window (millis since epoch)
1195 * @param {Number} endDate End of the date window (millis since epoch)
1196 * @return {Array.<Object>} Array of {label, value} tuples.
1197 * @public
1198 */
1199 Dygraph.dateTicker = function(startDate, endDate, self) {
1200 var chosen = -1;
1201 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
1202 var num_ticks = self.NumXTicks(startDate, endDate, i);
1203 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
1204 chosen = i;
1205 break;
1206 }
1207 }
1208
1209 if (chosen >= 0) {
1210 return self.GetXAxis(startDate, endDate, chosen);
1211 } else {
1212 // TODO(danvk): signal error.
1213 }
1214 };
1215
1216 /**
1217 * Add ticks when the x axis has numbers on it (instead of dates)
1218 * @param {Number} startDate Start of the date window (millis since epoch)
1219 * @param {Number} endDate End of the date window (millis since epoch)
1220 * @return {Array.<Object>} Array of {label, value} tuples.
1221 * @public
1222 */
1223 Dygraph.numericTicks = function(minV, maxV, self) {
1224 // Basic idea:
1225 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
1226 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
1227 // The first spacing greater than pixelsPerYLabel is what we use.
1228 // TODO(danvk): version that works on a log scale.
1229 if (self.attr_("labelsKMG2")) {
1230 var mults = [1, 2, 4, 8];
1231 } else {
1232 var mults = [1, 2, 5];
1233 }
1234 var scale, low_val, high_val, nTicks;
1235 // TODO(danvk): make it possible to set this for x- and y-axes independently.
1236 var pixelsPerTick = self.attr_('pixelsPerYLabel');
1237 for (var i = -10; i < 50; i++) {
1238 if (self.attr_("labelsKMG2")) {
1239 var base_scale = Math.pow(16, i);
1240 } else {
1241 var base_scale = Math.pow(10, i);
1242 }
1243 for (var j = 0; j < mults.length; j++) {
1244 scale = base_scale * mults[j];
1245 low_val = Math.floor(minV / scale) * scale;
1246 high_val = Math.ceil(maxV / scale) * scale;
1247 nTicks = (high_val - low_val) / scale;
1248 var spacing = self.height_ / nTicks;
1249 // wish I could break out of both loops at once...
1250 if (spacing > pixelsPerTick) break;
1251 }
1252 if (spacing > pixelsPerTick) break;
1253 }
1254
1255 // Construct labels for the ticks
1256 var ticks = [];
1257 var k;
1258 var k_labels = [];
1259 if (self.attr_("labelsKMB")) {
1260 k = 1000;
1261 k_labels = [ "K", "M", "B", "T" ];
1262 }
1263 if (self.attr_("labelsKMG2")) {
1264 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1265 k = 1024;
1266 k_labels = [ "k", "M", "G", "T" ];
1267 }
1268
1269 for (var i = 0; i < nTicks; i++) {
1270 var tickV = low_val + i * scale;
1271 var absTickV = Math.abs(tickV);
1272 var label = self.round_(tickV, 2);
1273 if (k_labels.length) {
1274 // Round up to an appropriate unit.
1275 var n = k*k*k*k;
1276 for (var j = 3; j >= 0; j--, n /= k) {
1277 if (absTickV >= n) {
1278 label = self.round_(tickV / n, 1) + k_labels[j];
1279 break;
1280 }
1281 }
1282 }
1283 ticks.push( {label: label, v: tickV} );
1284 }
1285 return ticks;
1286 };
1287
1288 /**
1289 * Adds appropriate ticks on the y-axis
1290 * @param {Number} minY The minimum Y value in the data set
1291 * @param {Number} maxY The maximum Y value in the data set
1292 * @private
1293 */
1294 Dygraph.prototype.addYTicks_ = function(minY, maxY) {
1295 // Set the number of ticks so that the labels are human-friendly.
1296 // TODO(danvk): make this an attribute as well.
1297 var ticks = Dygraph.numericTicks(minY, maxY, this);
1298 this.layout_.updateOptions( { yAxis: [minY, maxY],
1299 yTicks: ticks } );
1300 };
1301
1302 // Computes the range of the data series (including confidence intervals).
1303 // series is either [ [x1, y1], [x2, y2], ... ] or
1304 // [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
1305 // Returns [low, high]
1306 Dygraph.prototype.extremeValues_ = function(series) {
1307 var minY = null, maxY = null;
1308
1309 var bars = this.attr_("errorBars") || this.attr_("customBars");
1310 if (bars) {
1311 // With custom bars, maxY is the max of the high values.
1312 for (var j = 0; j < series.length; j++) {
1313 var y = series[j][1][0];
1314 if (!y) continue;
1315 var low = y - series[j][1][1];
1316 var high = y + series[j][1][2];
1317 if (low > y) low = y; // this can happen with custom bars,
1318 if (high < y) high = y; // e.g. in tests/custom-bars.html
1319 if (maxY == null || high > maxY) {
1320 maxY = high;
1321 }
1322 if (minY == null || low < minY) {
1323 minY = low;
1324 }
1325 }
1326 } else {
1327 for (var j = 0; j < series.length; j++) {
1328 var y = series[j][1];
1329 if (y === null || isNaN(y)) continue;
1330 if (maxY == null || y > maxY) {
1331 maxY = y;
1332 }
1333 if (minY == null || y < minY) {
1334 minY = y;
1335 }
1336 }
1337 }
1338
1339 return [minY, maxY];
1340 };
1341
1342 /**
1343 * Update the graph with new data. Data is in the format
1344 * [ [date1, val1, val2, ...], [date2, val1, val2, ...] if errorBars=false
1345 * or, if errorBars=true,
1346 * [ [date1, [val1,stddev1], [val2,stddev2], ...], [date2, ...], ...]
1347 * @param {Array.<Object>} data The data (see above)
1348 * @private
1349 */
1350 Dygraph.prototype.drawGraph_ = function(data) {
1351 // This is used to set the second parameter to drawCallback, below.
1352 var is_initial_draw = this.is_initial_draw_;
1353 this.is_initial_draw_ = false;
1354
1355 var minY = null, maxY = null;
1356 this.layout_.removeAllDatasets();
1357 this.setColors_();
1358 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
1359
1360 // For stacked series.
1361 var cumulative_y = [];
1362 var stacked_datasets = [];
1363
1364 // Loop over all fields in the dataset
1365
1366 for (var i = 1; i < data[0].length; i++) {
1367 if (!this.visibility()[i - 1]) continue;
1368
1369 var series = [];
1370 for (var j = 0; j < data.length; j++) {
1371 var date = data[j][0];
1372 series[j] = [date, data[j][i]];
1373 }
1374 series = this.rollingAverage(series, this.rollPeriod_);
1375
1376 // Prune down to the desired range, if necessary (for zooming)
1377 var bars = this.attr_("errorBars") || this.attr_("customBars");
1378 if (this.dateWindow_) {
1379 var low = this.dateWindow_[0];
1380 var high= this.dateWindow_[1];
1381 var pruned = [];
1382 for (var k = 0; k < series.length; k++) {
1383 // if (series[k][0] >= low && series[k][0] <= high) {
1384 pruned.push(series[k]);
1385 // }
1386 }
1387 series = pruned;
1388 }
1389
1390 var extremes = this.extremeValues_(series);
1391 var thisMinY = extremes[0];
1392 var thisMaxY = extremes[1];
1393 if (!minY || thisMinY < minY) minY = thisMinY;
1394 if (!maxY || thisMaxY > maxY) maxY = thisMaxY;
1395
1396 if (bars) {
1397 var vals = [];
1398 for (var j=0; j<series.length; j++)
1399 vals[j] = [series[j][0],
1400 series[j][1][0], series[j][1][1], series[j][1][2]];
1401 this.layout_.addDataset(this.attr_("labels")[i], vals);
1402 } else if (this.attr_("stackedGraph")) {
1403 var vals = [];
1404 var l = series.length;
1405 var actual_y;
1406 for (var j = 0; j < l; j++) {
1407 if (cumulative_y[series[j][0]] === undefined)
1408 cumulative_y[series[j][0]] = 0;
1409
1410 actual_y = series[j][1];
1411 cumulative_y[series[j][0]] += actual_y;
1412
1413 vals[j] = [series[j][0], cumulative_y[series[j][0]]]
1414
1415 if (!maxY || cumulative_y[series[j][0]] > maxY)
1416 maxY = cumulative_y[series[j][0]];
1417 }
1418 stacked_datasets.push([this.attr_("labels")[i], vals]);
1419 //this.layout_.addDataset(this.attr_("labels")[i], vals);
1420 } else {
1421 this.layout_.addDataset(this.attr_("labels")[i], series);
1422 }
1423 }
1424
1425 if (stacked_datasets.length > 0) {
1426 for (var i = (stacked_datasets.length - 1); i >= 0; i--) {
1427 this.layout_.addDataset(stacked_datasets[i][0], stacked_datasets[i][1]);
1428 }
1429 }
1430
1431 // Use some heuristics to come up with a good maxY value, unless it's been
1432 // set explicitly by the user.
1433 if (this.valueRange_ != null) {
1434 this.addYTicks_(this.valueRange_[0], this.valueRange_[1]);
1435 } else {
1436 // This affects the calculation of span, below.
1437 if (this.attr_("includeZero") && minY > 0) {
1438 minY = 0;
1439 }
1440
1441 // Add some padding and round up to an integer to be human-friendly.
1442 var span = maxY - minY;
1443 // special case: if we have no sense of scale, use +/-10% of the sole value.
1444 if (span == 0) { span = maxY; }
1445 var maxAxisY = maxY + 0.1 * span;
1446 var minAxisY = minY - 0.1 * span;
1447
1448 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
1449 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
1450 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
1451
1452 if (this.attr_("includeZero")) {
1453 if (maxY < 0) maxAxisY = 0;
1454 if (minY > 0) minAxisY = 0;
1455 }
1456
1457 this.addYTicks_(minAxisY, maxAxisY);
1458 }
1459
1460 this.addXTicks_();
1461
1462 // Tell PlotKit to use this new data and render itself
1463 this.layout_.updateOptions({dateWindow: this.dateWindow_});
1464 this.layout_.evaluateWithError();
1465 this.plotter_.clear();
1466 this.plotter_.render();
1467 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
1468 this.canvas_.height);
1469
1470 if (this.attr_("drawCallback") !== null) {
1471 this.attr_("drawCallback")(this, is_initial_draw);
1472 }
1473 };
1474
1475 /**
1476 * Calculates the rolling average of a data set.
1477 * If originalData is [label, val], rolls the average of those.
1478 * If originalData is [label, [, it's interpreted as [value, stddev]
1479 * and the roll is returned in the same form, with appropriately reduced
1480 * stddev for each value.
1481 * Note that this is where fractional input (i.e. '5/10') is converted into
1482 * decimal values.
1483 * @param {Array} originalData The data in the appropriate format (see above)
1484 * @param {Number} rollPeriod The number of days over which to average the data
1485 */
1486 Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
1487 if (originalData.length < 2)
1488 return originalData;
1489 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
1490 var rollingData = [];
1491 var sigma = this.attr_("sigma");
1492
1493 if (this.fractions_) {
1494 var num = 0;
1495 var den = 0; // numerator/denominator
1496 var mult = 100.0;
1497 for (var i = 0; i < originalData.length; i++) {
1498 num += originalData[i][1][0];
1499 den += originalData[i][1][1];
1500 if (i - rollPeriod >= 0) {
1501 num -= originalData[i - rollPeriod][1][0];
1502 den -= originalData[i - rollPeriod][1][1];
1503 }
1504
1505 var date = originalData[i][0];
1506 var value = den ? num / den : 0.0;
1507 if (this.attr_("errorBars")) {
1508 if (this.wilsonInterval_) {
1509 // For more details on this confidence interval, see:
1510 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
1511 if (den) {
1512 var p = value < 0 ? 0 : value, n = den;
1513 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
1514 var denom = 1 + sigma * sigma / den;
1515 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
1516 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
1517 rollingData[i] = [date,
1518 [p * mult, (p - low) * mult, (high - p) * mult]];
1519 } else {
1520 rollingData[i] = [date, [0, 0, 0]];
1521 }
1522 } else {
1523 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
1524 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
1525 }
1526 } else {
1527 rollingData[i] = [date, mult * value];
1528 }
1529 }
1530 } else if (this.attr_("customBars")) {
1531 var low = 0;
1532 var mid = 0;
1533 var high = 0;
1534 var count = 0;
1535 for (var i = 0; i < originalData.length; i++) {
1536 var data = originalData[i][1];
1537 var y = data[1];
1538 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
1539
1540 if (y != null && !isNaN(y)) {
1541 low += data[0];
1542 mid += y;
1543 high += data[2];
1544 count += 1;
1545 }
1546 if (i - rollPeriod >= 0) {
1547 var prev = originalData[i - rollPeriod];
1548 if (prev[1][1] != null && !isNaN(prev[1][1])) {
1549 low -= prev[1][0];
1550 mid -= prev[1][1];
1551 high -= prev[1][2];
1552 count -= 1;
1553 }
1554 }
1555 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
1556 1.0 * (mid - low) / count,
1557 1.0 * (high - mid) / count ]];
1558 }
1559 } else {
1560 // Calculate the rolling average for the first rollPeriod - 1 points where
1561 // there is not enough data to roll over the full number of days
1562 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
1563 if (!this.attr_("errorBars")){
1564 if (rollPeriod == 1) {
1565 return originalData;
1566 }
1567
1568 for (var i = 0; i < originalData.length; i++) {
1569 var sum = 0;
1570 var num_ok = 0;
1571 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
1572 var y = originalData[j][1];
1573 if (y == null || isNaN(y)) continue;
1574 num_ok++;
1575 sum += originalData[j][1];
1576 }
1577 if (num_ok) {
1578 rollingData[i] = [originalData[i][0], sum / num_ok];
1579 } else {
1580 rollingData[i] = [originalData[i][0], null];
1581 }
1582 }
1583
1584 } else {
1585 for (var i = 0; i < originalData.length; i++) {
1586 var sum = 0;
1587 var variance = 0;
1588 var num_ok = 0;
1589 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
1590 var y = originalData[j][1][0];
1591 if (y == null || isNaN(y)) continue;
1592 num_ok++;
1593 sum += originalData[j][1][0];
1594 variance += Math.pow(originalData[j][1][1], 2);
1595 }
1596 if (num_ok) {
1597 var stddev = Math.sqrt(variance) / num_ok;
1598 rollingData[i] = [originalData[i][0],
1599 [sum / num_ok, sigma * stddev, sigma * stddev]];
1600 } else {
1601 rollingData[i] = [originalData[i][0], [null, null, null]];
1602 }
1603 }
1604 }
1605 }
1606
1607 return rollingData;
1608 };
1609
1610 /**
1611 * Parses a date, returning the number of milliseconds since epoch. This can be
1612 * passed in as an xValueParser in the Dygraph constructor.
1613 * TODO(danvk): enumerate formats that this understands.
1614 * @param {String} A date in YYYYMMDD format.
1615 * @return {Number} Milliseconds since epoch.
1616 * @public
1617 */
1618 Dygraph.dateParser = function(dateStr, self) {
1619 var dateStrSlashed;
1620 var d;
1621 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
1622 dateStrSlashed = dateStr.replace("-", "/", "g");
1623 while (dateStrSlashed.search("-") != -1) {
1624 dateStrSlashed = dateStrSlashed.replace("-", "/");
1625 }
1626 d = Date.parse(dateStrSlashed);
1627 } else if (dateStr.length == 8) { // e.g. '20090712'
1628 // TODO(danvk): remove support for this format. It's confusing.
1629 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
1630 + "/" + dateStr.substr(6,2);
1631 d = Date.parse(dateStrSlashed);
1632 } else {
1633 // Any format that Date.parse will accept, e.g. "2009/07/12" or
1634 // "2009/07/12 12:34:56"
1635 d = Date.parse(dateStr);
1636 }
1637
1638 if (!d || isNaN(d)) {
1639 self.error("Couldn't parse " + dateStr + " as a date");
1640 }
1641 return d;
1642 };
1643
1644 /**
1645 * Detects the type of the str (date or numeric) and sets the various
1646 * formatting attributes in this.attrs_ based on this type.
1647 * @param {String} str An x value.
1648 * @private
1649 */
1650 Dygraph.prototype.detectTypeFromString_ = function(str) {
1651 var isDate = false;
1652 if (str.indexOf('-') >= 0 ||
1653 str.indexOf('/') >= 0 ||
1654 isNaN(parseFloat(str))) {
1655 isDate = true;
1656 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
1657 // TODO(danvk): remove support for this format.
1658 isDate = true;
1659 }
1660
1661 if (isDate) {
1662 this.attrs_.xValueFormatter = Dygraph.dateString_;
1663 this.attrs_.xValueParser = Dygraph.dateParser;
1664 this.attrs_.xTicker = Dygraph.dateTicker;
1665 } else {
1666 this.attrs_.xValueFormatter = function(x) { return x; };
1667 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1668 this.attrs_.xTicker = Dygraph.numericTicks;
1669 }
1670 };
1671
1672 /**
1673 * Parses a string in a special csv format. We expect a csv file where each
1674 * line is a date point, and the first field in each line is the date string.
1675 * We also expect that all remaining fields represent series.
1676 * if the errorBars attribute is set, then interpret the fields as:
1677 * date, series1, stddev1, series2, stddev2, ...
1678 * @param {Array.<Object>} data See above.
1679 * @private
1680 *
1681 * @return Array.<Object> An array with one entry for each row. These entries
1682 * are an array of cells in that row. The first entry is the parsed x-value for
1683 * the row. The second, third, etc. are the y-values. These can take on one of
1684 * three forms, depending on the CSV and constructor parameters:
1685 * 1. numeric value
1686 * 2. [ value, stddev ]
1687 * 3. [ low value, center value, high value ]
1688 */
1689 Dygraph.prototype.parseCSV_ = function(data) {
1690 var ret = [];
1691 var lines = data.split("\n");
1692
1693 // Use the default delimiter or fall back to a tab if that makes sense.
1694 var delim = this.attr_('delimiter');
1695 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
1696 delim = '\t';
1697 }
1698
1699 var start = 0;
1700 if (this.labelsFromCSV_) {
1701 start = 1;
1702 this.attrs_.labels = lines[0].split(delim);
1703 }
1704
1705 var xParser;
1706 var defaultParserSet = false; // attempt to auto-detect x value type
1707 var expectedCols = this.attr_("labels").length;
1708 var outOfOrder = false;
1709 for (var i = start; i < lines.length; i++) {
1710 var line = lines[i];
1711 if (line.length == 0) continue; // skip blank lines
1712 if (line[0] == '#') continue; // skip comment lines
1713 var inFields = line.split(delim);
1714 if (inFields.length < 2) continue;
1715
1716 var fields = [];
1717 if (!defaultParserSet) {
1718 this.detectTypeFromString_(inFields[0]);
1719 xParser = this.attr_("xValueParser");
1720 defaultParserSet = true;
1721 }
1722 fields[0] = xParser(inFields[0], this);
1723
1724 // If fractions are expected, parse the numbers as "A/B"
1725 if (this.fractions_) {
1726 for (var j = 1; j < inFields.length; j++) {
1727 // TODO(danvk): figure out an appropriate way to flag parse errors.
1728 var vals = inFields[j].split("/");
1729 fields[j] = [parseFloat(vals[0]), parseFloat(vals[1])];
1730 }
1731 } else if (this.attr_("errorBars")) {
1732 // If there are error bars, values are (value, stddev) pairs
1733 for (var j = 1; j < inFields.length; j += 2)
1734 fields[(j + 1) / 2] = [parseFloat(inFields[j]),
1735 parseFloat(inFields[j + 1])];
1736 } else if (this.attr_("customBars")) {
1737 // Bars are a low;center;high tuple
1738 for (var j = 1; j < inFields.length; j++) {
1739 var vals = inFields[j].split(";");
1740 fields[j] = [ parseFloat(vals[0]),
1741 parseFloat(vals[1]),
1742 parseFloat(vals[2]) ];
1743 }
1744 } else {
1745 // Values are just numbers
1746 for (var j = 1; j < inFields.length; j++) {
1747 fields[j] = parseFloat(inFields[j]);
1748 }
1749 }
1750 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
1751 outOfOrder = true;
1752 }
1753 ret.push(fields);
1754
1755 if (fields.length != expectedCols) {
1756 this.error("Number of columns in line " + i + " (" + fields.length +
1757 ") does not agree with number of labels (" + expectedCols +
1758 ") " + line);
1759 }
1760 }
1761
1762 if (outOfOrder) {
1763 this.warn("CSV is out of order; order it correctly to speed loading.");
1764 ret.sort(function(a,b) { return a[0] - b[0] });
1765 }
1766
1767 return ret;
1768 };
1769
1770 /**
1771 * The user has provided their data as a pre-packaged JS array. If the x values
1772 * are numeric, this is the same as dygraphs' internal format. If the x values
1773 * are dates, we need to convert them from Date objects to ms since epoch.
1774 * @param {Array.<Object>} data
1775 * @return {Array.<Object>} data with numeric x values.
1776 */
1777 Dygraph.prototype.parseArray_ = function(data) {
1778 // Peek at the first x value to see if it's numeric.
1779 if (data.length == 0) {
1780 this.error("Can't plot empty data set");
1781 return null;
1782 }
1783 if (data[0].length == 0) {
1784 this.error("Data set cannot contain an empty row");
1785 return null;
1786 }
1787
1788 if (this.attr_("labels") == null) {
1789 this.warn("Using default labels. Set labels explicitly via 'labels' " +
1790 "in the options parameter");
1791 this.attrs_.labels = [ "X" ];
1792 for (var i = 1; i < data[0].length; i++) {
1793 this.attrs_.labels.push("Y" + i);
1794 }
1795 }
1796
1797 if (Dygraph.isDateLike(data[0][0])) {
1798 // Some intelligent defaults for a date x-axis.
1799 this.attrs_.xValueFormatter = Dygraph.dateString_;
1800 this.attrs_.xTicker = Dygraph.dateTicker;
1801
1802 // Assume they're all dates.
1803 var parsedData = Dygraph.clone(data);
1804 for (var i = 0; i < data.length; i++) {
1805 if (parsedData[i].length == 0) {
1806 this.error("Row " << (1 + i) << " of data is empty");
1807 return null;
1808 }
1809 if (parsedData[i][0] == null
1810 || typeof(parsedData[i][0].getTime) != 'function') {
1811 this.error("x value in row " << (1 + i) << " is not a Date");
1812 return null;
1813 }
1814 parsedData[i][0] = parsedData[i][0].getTime();
1815 }
1816 return parsedData;
1817 } else {
1818 // Some intelligent defaults for a numeric x-axis.
1819 this.attrs_.xValueFormatter = function(x) { return x; };
1820 this.attrs_.xTicker = Dygraph.numericTicks;
1821 return data;
1822 }
1823 };
1824
1825 /**
1826 * Parses a DataTable object from gviz.
1827 * The data is expected to have a first column that is either a date or a
1828 * number. All subsequent columns must be numbers. If there is a clear mismatch
1829 * between this.xValueParser_ and the type of the first column, it will be
1830 * fixed. Returned value is in the same format as return value of parseCSV_.
1831 * @param {Array.<Object>} data See above.
1832 * @private
1833 */
1834 Dygraph.prototype.parseDataTable_ = function(data) {
1835 var cols = data.getNumberOfColumns();
1836 var rows = data.getNumberOfRows();
1837
1838 // Read column labels
1839 var labels = [];
1840 for (var i = 0; i < cols; i++) {
1841 labels.push(data.getColumnLabel(i));
1842 if (i != 0 && this.attr_("errorBars")) i += 1;
1843 }
1844 this.attrs_.labels = labels;
1845 cols = labels.length;
1846
1847 var indepType = data.getColumnType(0);
1848 if (indepType == 'date' || indepType == 'datetime') {
1849 this.attrs_.xValueFormatter = Dygraph.dateString_;
1850 this.attrs_.xValueParser = Dygraph.dateParser;
1851 this.attrs_.xTicker = Dygraph.dateTicker;
1852 } else if (indepType == 'number') {
1853 this.attrs_.xValueFormatter = function(x) { return x; };
1854 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1855 this.attrs_.xTicker = Dygraph.numericTicks;
1856 } else {
1857 this.error("only 'date', 'datetime' and 'number' types are supported for " +
1858 "column 1 of DataTable input (Got '" + indepType + "')");
1859 return null;
1860 }
1861
1862 var ret = [];
1863 var outOfOrder = false;
1864 for (var i = 0; i < rows; i++) {
1865 var row = [];
1866 if (typeof(data.getValue(i, 0)) === 'undefined' ||
1867 data.getValue(i, 0) === null) {
1868 this.warning("Ignoring row " + i +
1869 " of DataTable because of undefined or null first column.");
1870 continue;
1871 }
1872
1873 if (indepType == 'date' || indepType == 'datetime') {
1874 row.push(data.getValue(i, 0).getTime());
1875 } else {
1876 row.push(data.getValue(i, 0));
1877 }
1878 if (!this.attr_("errorBars")) {
1879 for (var j = 1; j < cols; j++) {
1880 row.push(data.getValue(i, j));
1881 }
1882 } else {
1883 for (var j = 0; j < cols - 1; j++) {
1884 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
1885 }
1886 }
1887 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
1888 outOfOrder = true;
1889 }
1890 ret.push(row);
1891 }
1892
1893 if (outOfOrder) {
1894 this.warn("DataTable is out of order; order it correctly to speed loading.");
1895 ret.sort(function(a,b) { return a[0] - b[0] });
1896 }
1897 return ret;
1898 }
1899
1900 // These functions are all based on MochiKit.
1901 Dygraph.update = function (self, o) {
1902 if (typeof(o) != 'undefined' && o !== null) {
1903 for (var k in o) {
1904 if (o.hasOwnProperty(k)) {
1905 self[k] = o[k];
1906 }
1907 }
1908 }
1909 return self;
1910 };
1911
1912 Dygraph.isArrayLike = function (o) {
1913 var typ = typeof(o);
1914 if (
1915 (typ != 'object' && !(typ == 'function' &&
1916 typeof(o.item) == 'function')) ||
1917 o === null ||
1918 typeof(o.length) != 'number' ||
1919 o.nodeType === 3
1920 ) {
1921 return false;
1922 }
1923 return true;
1924 };
1925
1926 Dygraph.isDateLike = function (o) {
1927 if (typeof(o) != "object" || o === null ||
1928 typeof(o.getTime) != 'function') {
1929 return false;
1930 }
1931 return true;
1932 };
1933
1934 Dygraph.clone = function(o) {
1935 // TODO(danvk): figure out how MochiKit's version works
1936 var r = [];
1937 for (var i = 0; i < o.length; i++) {
1938 if (Dygraph.isArrayLike(o[i])) {
1939 r.push(Dygraph.clone(o[i]));
1940 } else {
1941 r.push(o[i]);
1942 }
1943 }
1944 return r;
1945 };
1946
1947
1948 /**
1949 * Get the CSV data. If it's in a function, call that function. If it's in a
1950 * file, do an XMLHttpRequest to get it.
1951 * @private
1952 */
1953 Dygraph.prototype.start_ = function() {
1954 if (typeof this.file_ == 'function') {
1955 // CSV string. Pretend we got it via XHR.
1956 this.loadedEvent_(this.file_());
1957 } else if (Dygraph.isArrayLike(this.file_)) {
1958 this.rawData_ = this.parseArray_(this.file_);
1959 this.drawGraph_(this.rawData_);
1960 } else if (typeof this.file_ == 'object' &&
1961 typeof this.file_.getColumnRange == 'function') {
1962 // must be a DataTable from gviz.
1963 this.rawData_ = this.parseDataTable_(this.file_);
1964 this.drawGraph_(this.rawData_);
1965 } else if (typeof this.file_ == 'string') {
1966 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
1967 if (this.file_.indexOf('\n') >= 0) {
1968 this.loadedEvent_(this.file_);
1969 } else {
1970 var req = new XMLHttpRequest();
1971 var caller = this;
1972 req.onreadystatechange = function () {
1973 if (req.readyState == 4) {
1974 if (req.status == 200) {
1975 caller.loadedEvent_(req.responseText);
1976 }
1977 }
1978 };
1979
1980 req.open("GET", this.file_, true);
1981 req.send(null);
1982 }
1983 } else {
1984 this.error("Unknown data format: " + (typeof this.file_));
1985 }
1986 };
1987
1988 /**
1989 * Changes various properties of the graph. These can include:
1990 * <ul>
1991 * <li>file: changes the source data for the graph</li>
1992 * <li>errorBars: changes whether the data contains stddev</li>
1993 * </ul>
1994 * @param {Object} attrs The new properties and values
1995 */
1996 Dygraph.prototype.updateOptions = function(attrs) {
1997 // TODO(danvk): this is a mess. Rethink this function.
1998 if (attrs.rollPeriod) {
1999 this.rollPeriod_ = attrs.rollPeriod;
2000 }
2001 if (attrs.dateWindow) {
2002 this.dateWindow_ = attrs.dateWindow;
2003 }
2004 if (attrs.valueRange) {
2005 this.valueRange_ = attrs.valueRange;
2006 }
2007 Dygraph.update(this.user_attrs_, attrs);
2008
2009 this.labelsFromCSV_ = (this.attr_("labels") == null);
2010
2011 // TODO(danvk): this doesn't match the constructor logic
2012 this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") });
2013 if (attrs['file'] && attrs['file'] != this.file_) {
2014 this.file_ = attrs['file'];
2015 this.start_();
2016 } else {
2017 this.drawGraph_(this.rawData_);
2018 }
2019 };
2020
2021 /**
2022 * Resizes the dygraph. If no parameters are specified, resizes to fill the
2023 * containing div (which has presumably changed size since the dygraph was
2024 * instantiated. If the width/height are specified, the div will be resized.
2025 *
2026 * This is far more efficient than destroying and re-instantiating a
2027 * Dygraph, since it doesn't have to reparse the underlying data.
2028 *
2029 * @param {Number} width Width (in pixels)
2030 * @param {Number} height Height (in pixels)
2031 */
2032 Dygraph.prototype.resize = function(width, height) {
2033 if ((width === null) != (height === null)) {
2034 this.warn("Dygraph.resize() should be called with zero parameters or " +
2035 "two non-NULL parameters. Pretending it was zero.");
2036 width = height = null;
2037 }
2038
2039 // TODO(danvk): there should be a clear() method.
2040 this.maindiv_.innerHTML = "";
2041 this.attrs_.labelsDiv = null;
2042
2043 if (width) {
2044 this.maindiv_.style.width = width + "px";
2045 this.maindiv_.style.height = height + "px";
2046 this.width_ = width;
2047 this.height_ = height;
2048 } else {
2049 this.width_ = this.maindiv_.offsetWidth;
2050 this.height_ = this.maindiv_.offsetHeight;
2051 }
2052
2053 this.createInterface_();
2054 this.drawGraph_(this.rawData_);
2055 };
2056
2057 /**
2058 * Adjusts the number of days in the rolling average. Updates the graph to
2059 * reflect the new averaging period.
2060 * @param {Number} length Number of days over which to average the data.
2061 */
2062 Dygraph.prototype.adjustRoll = function(length) {
2063 this.rollPeriod_ = length;
2064 this.drawGraph_(this.rawData_);
2065 };
2066
2067 /**
2068 * Returns a boolean array of visibility statuses.
2069 */
2070 Dygraph.prototype.visibility = function() {
2071 // Do lazy-initialization, so that this happens after we know the number of
2072 // data series.
2073 if (!this.attr_("visibility")) {
2074 this.attrs_["visibility"] = [];
2075 }
2076 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
2077 this.attr_("visibility").push(true);
2078 }
2079 return this.attr_("visibility");
2080 };
2081
2082 /**
2083 * Changes the visiblity of a series.
2084 */
2085 Dygraph.prototype.setVisibility = function(num, value) {
2086 var x = this.visibility();
2087 if (num < 0 && num >= x.length) {
2088 this.warn("invalid series number in setVisibility: " + num);
2089 } else {
2090 x[num] = value;
2091 this.drawGraph_(this.rawData_);
2092 }
2093 };
2094
2095 /**
2096 * Create a new canvas element. This is more complex than a simple
2097 * document.createElement("canvas") because of IE and excanvas.
2098 */
2099 Dygraph.createCanvas = function() {
2100 var canvas = document.createElement("canvas");
2101
2102 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
2103 if (isIE) {
2104 canvas = G_vmlCanvasManager.initElement(canvas);
2105 }
2106
2107 return canvas;
2108 };
2109
2110
2111 /**
2112 * A wrapper around Dygraph that implements the gviz API.
2113 * @param {Object} container The DOM object the visualization should live in.
2114 */
2115 Dygraph.GVizChart = function(container) {
2116 this.container = container;
2117 }
2118
2119 Dygraph.GVizChart.prototype.draw = function(data, options) {
2120 this.container.innerHTML = '';
2121 this.date_graph = new Dygraph(this.container, data, options);
2122 }
2123
2124 // Older pages may still use this name.
2125 DateGraph = Dygraph;