1 // Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2 // All Rights Reserved.
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)
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
19 The CSV file is of the form
21 Date,SeriesA,SeriesB,SeriesC
25 If the 'errorBars' option is set in the constructor, the input should be of
28 Date,SeriesA,SeriesB,...
29 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
30 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
32 If the 'fractions' option is set, the input should be of the form:
34 Date,SeriesA,SeriesB,...
35 YYYYMMDD,A1/B1,A2/B2,...
36 YYYYMMDD,A1/B1,A2/B2,...
38 And error bars will be calculated automatically using a binomial distribution.
40 For further documentation and examples, see http://www.danvk.org/dygraphs
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.
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]);
62 this.__init__(div
, data
, opts
);
67 Dygraph
.NAME
= "Dygraph";
68 Dygraph
.VERSION
= "1.2";
69 Dygraph
.__repr__
= function() {
70 return "[" + this.NAME
+ " " + this.VERSION
+ "]";
72 Dygraph
.toString
= function() {
73 return this.__repr__();
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;
82 // Default attribute values.
83 Dygraph
.DEFAULT_ATTRS
= {
84 highlightCircleSize
: 3,
90 // TODO(danvk): move defaults from createStatusMessage_ here.
92 labelsSeparateLines
: false,
99 axisLabelFontSize
: 14,
105 xValueFormatter
: Dygraph
.dateString_
,
106 xValueParser
: Dygraph
.dateParser
,
107 xTicker
: Dygraph
.dateTicker
,
115 wilsonInterval
: true, // only relevant if fractions is true
121 hideOverlayOnMouseOut
: true
124 // Various logging levels.
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
});
139 this.__init__(div
, file
, attrs
);
143 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
144 * and interaction <canvas> inside of it. See the constructor for details
146 * @param {String | Function} file Source data
147 * @param {Array.<String>} labels Names of the data series
148 * @param {Object} attrs Miscellaneous other options
151 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
152 // Support two-argument constructor
153 if (attrs
== null) { attrs
= {}; }
155 // Copy the important bits into the object
156 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
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;
167 // Clear the div. This ensure that, if multiple dygraphs are passed the same
168 // div, then only one will be drawn.
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";
176 if (div
.style
.height
== '') {
177 div
.style
.height
= attrs
.height
|| Dygraph
.DEFAULT_HEIGHT
+ "px";
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;
187 if (div
.style
.height
.indexOf("%") == div
.style
.height
.length
- 1) {
188 this.height_
= (this.height_
* self
.innerHeight
/ 100) - 10;
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.
197 // Dygraphs has many options, some of which interact with one another.
198 // To keep track of everything, we maintain two sets of options:
200 // this.user_attrs_ only options explicitly set by the user.
201 // this.attrs_ defaults, options derived from user_attrs_, data.
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
);
210 Dygraph
.update(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
212 // Make a note of whether labels will be pulled from the CSV file.
213 this.labelsFromCSV_
= (this.attr_("labels") == null);
215 // Create the containing DIV and other interactive elements
216 this.createInterface_();
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
];
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') {
236 console
.debug('dygraphs: ' + message
);
239 console
.info('dygraphs: ' + message
);
241 case Dygraph
.WARNING
:
242 console
.warn('dygraphs: ' + message
);
245 console
.error('dygraphs: ' + message
);
250 Dygraph
.prototype.info
= function(message
) {
251 this.log(Dygraph
.INFO
, message
);
253 Dygraph
.prototype.warn
= function(message
) {
254 this.log(Dygraph
.WARNING
, message
);
256 Dygraph
.prototype.error
= function(message
) {
257 this.log(Dygraph
.ERROR
, message
);
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
264 Dygraph
.prototype.rollPeriod
= function() {
265 return this.rollPeriod_
;
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.
274 Dygraph
.prototype.xAxisRange
= function() {
275 if (this.dateWindow_
) return this.dateWindow_
;
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
];
283 Dygraph
.addEvent
= function(el
, evt
, fn
) {
284 var normed_fn
= function(e
) {
285 if (!e
) var e
= window
.event
;
288 if (window
.addEventListener
) { // Mozilla, Netscape, Firefox
289 el
.addEventListener(evt
, normed_fn
, false);
291 el
.attachEvent('on' + evt
, normed_fn
);
295 Dygraph
.clipCanvas_
= function(cnv
, clip
) {
296 var ctx
= cnv
.getContext("2d");
298 ctx
.rect(clip
.left
, clip
.top
, clip
.width
, clip
.height
);
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.
308 Dygraph
.prototype.createInterface_
= function() {
309 // Create the all-enclosing graph div
310 var enclosing
= this.maindiv_
;
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
);
319 left
: this.attr_("yAxisLabelWidth") + 2 * this.attr_("axisTickSize")
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
;
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_
);
335 // ... and for static parts of the chart.
336 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
338 // Make sure we don't overdraw.
339 Dygraph
.clipCanvas_(this.hidden_
, this.clippingArea_
);
340 Dygraph
.clipCanvas_(this.canvas_
, this.clippingArea_
);
343 Dygraph
.addEvent(this.hidden_
, 'mousemove', function(e
) {
344 dygraph
.mouseMove_(e
);
346 Dygraph
.addEvent(this.hidden_
, 'mouseout', function(e
) {
347 dygraph
.mouseOut_(e
);
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")) });
358 this.layout_
= new DygraphLayout(this, this.layoutOptions_
);
360 // TODO(danvk): why does the Renderer need its own set of options?
361 this.renderOptions_
= { colorScheme
: this.colors_
,
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_
);
370 this.createStatusMessage_();
371 this.createRollInterface_();
372 this.createDragInterface_();
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.
380 Dygraph
.prototype.destroy
= function() {
381 var removeRecursive
= function(node
) {
382 while (node
.hasChildNodes()) {
383 removeRecursive(node
.firstChild
);
384 node
.removeChild(node
.firstChild
);
387 removeRecursive(this.maindiv_
);
389 var nullOut
= function(obj
) {
391 if (typeof(obj
[n
]) === 'object') {
397 // These may not all be necessary, but it can't hurt...
398 nullOut(this.layout_
);
399 nullOut(this.plotter_
);
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
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
);
426 // Taken from MochiKit.Color
427 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
431 if (saturation
=== 0) {
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
)));
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;
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
+ ')';
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.
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;
470 var colors
= this.attr_('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
));
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
);
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_
);
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.
501 Dygraph
.prototype.getColors
= function() {
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
) {
513 curleft
+= obj
.offsetLeft
;
514 if(!obj
.offsetParent
)
516 obj
= obj
.offsetParent
;
523 Dygraph
.findPosY
= function(obj
) {
528 curtop
+= obj
.offsetTop
;
529 if(!obj
.offsetParent
)
531 obj
= obj
.offsetParent
;
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
546 Dygraph
.prototype.createStatusMessage_
= function(){
547 if (!this.attr_("labelsDiv")) {
548 var divWidth
= this.attr_('labelsDivWidth');
550 "position": "absolute",
553 "width": divWidth
+ "px",
555 "left": (this.width_
- divWidth
- 2) + "px",
556 "background": "white",
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
];
566 this.graphDiv
.appendChild(div
);
567 this.attrs_
.labelsDiv
= div
;
572 * Create the text box to adjust the averaging period
573 * @return {Object} The newly-created text box
576 Dygraph
.prototype.createRollInterface_
= function() {
577 var display
= this.attr_('showRoller') ? "block" : "none";
578 var textAttr
= { "position": "absolute",
580 "top": (this.plotter_
.area
.h
- 25) + "px",
581 "left": (this.plotter_
.area
.x
+ 1) + "px",
584 var roller
= document
.createElement("input");
585 roller
.type
= "text";
587 roller
.value
= this.rollPeriod_
;
588 for (var name
in textAttr
) {
589 if (textAttr
.hasOwnProperty(name
)) {
590 roller
.style
[name
] = textAttr
[name
];
594 var pa
= this.graphDiv
;
595 pa
.appendChild(roller
);
597 roller
.onchange
= function() { dygraph
.adjustRoll(roller
.value
); };
601 // These functions are taken from MochiKit.Signal
602 Dygraph
.pageX
= function(e
) {
604 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
607 var b
= document
.body
;
609 (de
.scrollLeft
|| b
.scrollLeft
) -
610 (de
.clientLeft
|| 0);
614 Dygraph
.pageY
= function(e
) {
616 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
619 var b
= document
.body
;
621 (de
.scrollTop
|| b
.scrollTop
) -
627 * Set up all the mouse handlers needed to capture dragging behavior for zoom
631 Dygraph
.prototype.createDragInterface_
= function() {
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;
642 var draggingDate
= null;
643 var dateRange
= null;
645 // Utility function to convert page-wide coordinates to canvas coords
648 var getX
= function(e
) { return Dygraph
.pageX(e
) - px
};
649 var getY
= function(e
) { return Dygraph
.pageX(e
) - py
};
651 // Draw zoom rectangles when the mouse is down and the user moves around
652 Dygraph
.addEvent(this.hidden_
, 'mousemove', function(event
) {
654 dragEndX
= getX(event
);
655 dragEndY
= getY(event
);
657 self
.drawZoomRect_(dragStartX
, dragEndX
, prevEndX
);
659 } else if (isPanning
) {
660 dragEndX
= getX(event
);
661 dragEndY
= getY(event
);
663 // Want to have it so that:
664 // 1. draggingDate appears at dragEndX
665 // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
667 self
.dateWindow_
[0] = draggingDate
- (dragEndX
/ self
.width_
) * dateRange
;
668 self
.dateWindow_
[1] = self
.dateWindow_
[0] + dateRange
;
669 self
.drawGraph_(self
.rawData_
);
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
);
680 if (event
.altKey
|| event
.shiftKey
) {
681 if (!self
.dateWindow_
) return; // have to be zoomed in to pan.
683 dateRange
= self
.dateWindow_
[1] - self
.dateWindow_
[0];
684 draggingDate
= (dragStartX
/ self
.width_
) * dateRange
+
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
) {
707 // Temporarily cancel the dragging event when the mouse leaves the graph
708 Dygraph
.addEvent(this.hidden_
, 'mouseout', function(event
) {
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
) {
720 dragEndX
= getX(event
);
721 dragEndY
= getY(event
);
722 var regionWidth
= Math
.abs(dragEndX
- dragStartX
);
723 var regionHeight
= Math
.abs(dragEndY
- dragStartY
);
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_
);
732 if (regionWidth
>= 10) {
733 self
.doZoom_(Math
.min(dragStartX
, dragEndX
),
734 Math
.max(dragStartX
, dragEndX
));
736 self
.canvas_
.getContext("2d").clearRect(0, 0,
738 self
.canvas_
.height
);
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
);
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
770 * @param {Number} startX The X position where the drag started, in canvas
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
777 Dygraph
.prototype.drawZoomRect_
= function(startX
, endX
, prevEndX
) {
778 var ctx
= this.canvas_
.getContext("2d");
780 // Clean up from the previous rect if necessary
782 ctx
.clearRect(Math
.min(startX
, prevEndX
), 0,
783 Math
.abs(startX
- prevEndX
), this.height_
);
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_
);
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.
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
;
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
;
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
;
818 this.dateWindow_
= [minDate
, maxDate
];
819 this.drawGraph_(this.rawData_
);
820 if (this.attr_("zoomCallback")) {
821 this.attr_("zoomCallback")(minDate
, maxDate
);
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.
832 Dygraph
.prototype.mouseMove_
= function(event
) {
833 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.hidden_
);
834 var points
= this.layout_
.points
;
839 // Loop through all the points and find the date nearest to our current
841 var minDist
= 1e+100;
843 for (var i
= 0; i
< points
.length
; i
++) {
844 var dist
= Math
.abs(points
[i
].canvasx
- canvasx
);
845 if (dist
> minDist
) break;
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
;
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
]);
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_
);
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
;
878 this.attr_("highlightCallback")(event
, lastx
, callbackPoints
);
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_
);
891 var isOK
= function(x
) { return x
&& !isNaN(x
); };
893 if (this.selPoints_
.length
> 0) {
894 var canvasx
= this.selPoints_
[0].canvasx
;
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")) {
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);
910 this.attr_("labelsDiv").innerHTML
= replace
;
912 // Save last x position for callbacks.
915 // Draw colored circles over the center of each selected point
917 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
918 if (!isOK(this.selPoints_
[i
%clen
].canvasy
)) continue;
920 ctx
.fillStyle
= this.colors_
[i
%clen
];
921 ctx
.arc(canvasx
, this.selPoints_
[i
%clen
].canvasy
, circleSize
,
922 0, 2 * Math
.PI
, false);
927 this.previousVerticalX_
= canvasx
;
932 * The mouse has left the canvas. Clear out whatever artifacts remain
933 * @param {Object} event the mouseout event from the browser.
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
= "";
945 Dygraph
.zeropad
= function(x
) {
946 if (x
< 10) return "0" + x
; else return "" + x
;
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"
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());
963 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
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"
972 * TODO(danvk): why is this part of the prototype?
974 Dygraph
.dateString_
= function(date
, self
) {
975 var zeropad
= Dygraph
.zeropad
;
976 var d
= new Date(date
);
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());
986 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
987 if (frac
) ret
= " " + self
.hmsString_(date
);
989 return year
+ "/" + month + "/" + day
+ ret
;
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
999 Dygraph
.prototype.round_
= function(num
, places
) {
1000 var shift
= Math
.pow(10, places
);
1001 return Math
.round(num
* shift
)/shift
;
1005 * Fires when there's data available to be graphed.
1006 * @param {String} data Raw CSV data to be plotted
1009 Dygraph
.prototype.loadedEvent_
= function(data
) {
1010 this.rawData_
= this.parseCSV_(data
);
1011 this.drawGraph_(this.rawData_
);
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"];
1019 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
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];
1029 startDate
= this.rawData_
[0][0];
1030 endDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1033 var xTicks
= this.attr_('xTicker')(startDate
, endDate
, this);
1034 this.layout_
.updateOptions({xTicks
: xTicks
});
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;
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;
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;
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.
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
);
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; }
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
);
1103 // Construct an x-axis of nicely-formatted times on meaningful boundaries
1104 // (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1106 // Returns an array containing {v: millis, label: label} dictionaries.
1108 Dygraph
.prototype.GetXAxis
= function(start_time
, end_time
, granularity
) {
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"
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
);
1124 if (g
<= 60) { // minutes
1125 var x
= d
.getMinutes(); d
.setMinutes(x
- x
% g
);
1130 if (g
<= 24) { // days
1131 var x
= d
.getHours(); d
.setHours(x
- x
% g
);
1136 if (g
== 7) { // one week
1137 d
.setDate(d
.getDate() - d
.getDay());
1142 start_time
= d
.getTime();
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
) });
1151 ticks
.push({ v
:t
, label
: this.hmsString_(t
) });
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.
1159 var year_mod
= 1; // e.g. to only print one point every 10 years.
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
) {
1167 } else if (granularity
== Dygraph
.ANNUAL
) {
1169 } else if (granularity
== Dygraph
.DECADAL
) {
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') });
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.
1199 Dygraph
.dateTicker
= function(startDate
, endDate
, self
) {
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')) {
1210 return self
.GetXAxis(startDate
, endDate
, chosen
);
1212 // TODO(danvk): signal error.
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.
1223 Dygraph
.numericTicks
= function(minV
, maxV
, self
) {
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];
1232 var mults
= [1, 2, 5];
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
);
1241 var base_scale
= Math
.pow(10, i
);
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;
1252 if (spacing
> pixelsPerTick
) break;
1255 // Construct labels for the ticks
1259 if (self
.attr_("labelsKMB")) {
1261 k_labels
= [ "K", "M", "B", "T" ];
1263 if (self
.attr_("labelsKMG2")) {
1264 if (k
) self
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1266 k_labels
= [ "k", "M", "G", "T" ];
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.
1276 for (var j
= 3; j
>= 0; j
--, n
/= k
) {
1277 if (absTickV
>= n
) {
1278 label
= self
.round_(tickV
/ n
, 1) + k_labels
[j
];
1283 ticks
.push( {label
: label
, v
: tickV
} );
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
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
],
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;
1309 var bars
= this.attr_("errorBars") || this.attr_("customBars");
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];
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
) {
1322 if (minY
== null || low
< minY
) {
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
) {
1333 if (minY
== null || y
< minY
) {
1339 return [minY
, maxY
];
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)
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;
1355 var minY
= null, maxY
= null;
1356 this.layout_
.removeAllDatasets();
1358 this.attrs_
['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
1360 // For stacked series.
1361 var cumulative_y
= [];
1362 var stacked_datasets
= [];
1364 // Loop over all fields in the dataset
1366 for (var i
= 1; i
< data
[0].length
; i
++) {
1367 if (!this.visibility()[i
- 1]) continue;
1370 for (var j
= 0; j
< data
.length
; j
++) {
1371 var date
= data
[j
][0];
1372 series
[j
] = [date
, data
[j
][i
]];
1374 series
= this.rollingAverage(series
, this.rollPeriod_
);
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];
1382 for (var k
= 0; k
< series
.length
; k
++) {
1383 // if (series[k][0] >= low && series[k][0] <= high) {
1384 pruned
.push(series
[k
]);
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
;
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")) {
1404 var l
= series
.length
;
1406 for (var j
= 0; j
< l
; j
++) {
1407 if (cumulative_y
[series
[j
][0]] === undefined
)
1408 cumulative_y
[series
[j
][0]] = 0;
1410 actual_y
= series
[j
][1];
1411 cumulative_y
[series
[j
][0]] += actual_y
;
1413 vals
[j
] = [series
[j
][0], cumulative_y
[series
[j
][0]]]
1415 if (!maxY
|| cumulative_y
[series
[j
][0]] > maxY
)
1416 maxY
= cumulative_y
[series
[j
][0]];
1418 stacked_datasets
.push([this.attr_("labels")[i
], vals
]);
1419 //this.layout_.addDataset(this.attr_("labels")[i], vals);
1421 this.layout_
.addDataset(this.attr_("labels")[i
], series
);
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]);
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]);
1436 // This affects the calculation of span, below.
1437 if (this.attr_("includeZero") && minY
> 0) {
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
;
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;
1452 if (this.attr_("includeZero")) {
1453 if (maxY
< 0) maxAxisY
= 0;
1454 if (minY
> 0) minAxisY
= 0;
1457 this.addYTicks_(minAxisY
, maxAxisY
);
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
);
1470 if (this.attr_("drawCallback") !== null) {
1471 this.attr_("drawCallback")(this, is_initial_draw
);
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
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
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");
1493 if (this.fractions_
) {
1495 var den
= 0; // numerator/denominator
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];
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
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
]];
1520 rollingData
[i
] = [date
, [0, 0, 0]];
1523 var stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
1524 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
1527 rollingData
[i
] = [date
, mult
* value
];
1530 } else if (this.attr_("customBars")) {
1535 for (var i
= 0; i
< originalData
.length
; i
++) {
1536 var data
= originalData
[i
][1];
1538 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
1540 if (y
!= null && !isNaN(y
)) {
1546 if (i
- rollPeriod
>= 0) {
1547 var prev
= originalData
[i
- rollPeriod
];
1548 if (prev
[1][1] != null && !isNaN(prev
[1][1])) {
1555 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
1556 1.0 * (mid
- low
) / count
,
1557 1.0 * (high
- mid
) / count
]];
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
;
1568 for (var i
= 0; i
< originalData
.length
; i
++) {
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;
1575 sum
+= originalData
[j
][1];
1578 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
1580 rollingData
[i
] = [originalData
[i
][0], null];
1585 for (var i
= 0; i
< originalData
.length
; i
++) {
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;
1593 sum
+= originalData
[j
][1][0];
1594 variance
+= Math
.pow(originalData
[j
][1][1], 2);
1597 var stddev
= Math
.sqrt(variance
) / num_ok
;
1598 rollingData
[i
] = [originalData
[i
][0],
1599 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
1601 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
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.
1618 Dygraph
.dateParser
= function(dateStr
, self
) {
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("-", "/");
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
);
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
);
1638 if (!d
|| isNaN(d
)) {
1639 self
.error("Couldn't parse " + dateStr
+ " as a date");
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.
1650 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
1652 if (str
.indexOf('-') >= 0 ||
1653 str
.indexOf('/') >= 0 ||
1654 isNaN(parseFloat(str
))) {
1656 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
1657 // TODO(danvk): remove support for this format.
1662 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
1663 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
1664 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
1666 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
1667 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
1668 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
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.
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:
1686 * 2. [ value, stddev ]
1687 * 3. [ low value, center value, high value ]
1689 Dygraph
.prototype.parseCSV_
= function(data
) {
1691 var lines
= data
.split("\n");
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) {
1700 if (this.labelsFromCSV_
) {
1702 this.attrs_
.labels
= lines
[0].split(delim
);
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;
1717 if (!defaultParserSet
) {
1718 this.detectTypeFromString_(inFields
[0]);
1719 xParser
= this.attr_("xValueParser");
1720 defaultParserSet
= true;
1722 fields
[0] = xParser(inFields
[0], this);
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])];
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]) ];
1745 // Values are just numbers
1746 for (var j = 1; j < inFields.length; j++) {
1747 fields[j] = parseFloat(inFields[j]);
1750 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
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 +
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] });
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.
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");
1783 if (data[0].length == 0) {
1784 this.error("Data set cannot contain an empty row");
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);
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;
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");
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");
1814 parsedData
[i
][0] = parsedData
[i
][0].getTime();
1818 // Some intelligent defaults for a numeric x-axis.
1819 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
1820 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
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.
1834 Dygraph
.prototype.parseDataTable_
= function(data
) {
1835 var cols
= data
.getNumberOfColumns();
1836 var rows
= data
.getNumberOfRows();
1838 // Read column labels
1840 for (var i
= 0; i
< cols
; i
++) {
1841 labels
.push(data
.getColumnLabel(i
));
1842 if (i
!= 0 && this.attr_("errorBars")) i
+= 1;
1844 this.attrs_
.labels
= labels
;
1845 cols
= labels
.length
;
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
;
1857 this.error("only 'date', 'datetime' and 'number' types are supported for " +
1858 "column 1 of DataTable input (Got '" + indepType
+ "')");
1863 var outOfOrder
= false;
1864 for (var i
= 0; i
< rows
; i
++) {
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.");
1873 if (indepType
== 'date' || indepType
== 'datetime') {
1874 row
.push(data
.getValue(i
, 0).getTime());
1876 row
.push(data
.getValue(i
, 0));
1878 if (!this.attr_("errorBars")) {
1879 for (var j
= 1; j
< cols
; j
++) {
1880 row
.push(data
.getValue(i
, j
));
1883 for (var j
= 0; j
< cols
- 1; j
++) {
1884 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
1887 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
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] });
1900 // These functions are all based on MochiKit.
1901 Dygraph
.update
= function (self
, o
) {
1902 if (typeof(o
) != 'undefined' && o
!== null) {
1904 if (o
.hasOwnProperty(k
)) {
1912 Dygraph
.isArrayLike
= function (o
) {
1913 var typ
= typeof(o
);
1915 (typ
!= 'object' && !(typ
== 'function' &&
1916 typeof(o
.item
) == 'function')) ||
1918 typeof(o
.length
) != 'number' ||
1926 Dygraph
.isDateLike
= function (o
) {
1927 if (typeof(o
) != "object" || o
=== null ||
1928 typeof(o
.getTime
) != 'function') {
1934 Dygraph
.clone
= function(o
) {
1935 // TODO(danvk): figure out how MochiKit's version works
1937 for (var i
= 0; i
< o
.length
; i
++) {
1938 if (Dygraph
.isArrayLike(o
[i
])) {
1939 r
.push(Dygraph
.clone(o
[i
]));
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.
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_
);
1970 var req
= new XMLHttpRequest();
1972 req
.onreadystatechange
= function () {
1973 if (req
.readyState
== 4) {
1974 if (req
.status
== 200) {
1975 caller
.loadedEvent_(req
.responseText
);
1980 req
.open("GET", this.file_
, true);
1984 this.error("Unknown data format: " + (typeof this.file_
));
1989 * Changes various properties of the graph. These can include:
1991 * <li>file: changes the source data for the graph</li>
1992 * <li>errorBars: changes whether the data contains stddev</li>
1994 * @param {Object} attrs The new properties and values
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
;
2001 if (attrs
.dateWindow
) {
2002 this.dateWindow_
= attrs
.dateWindow
;
2004 if (attrs
.valueRange
) {
2005 this.valueRange_
= attrs
.valueRange
;
2007 Dygraph
.update(this.user_attrs_
, attrs
);
2009 this.labelsFromCSV_
= (this.attr_("labels") == null);
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'];
2017 this.drawGraph_(this.rawData_
);
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.
2026 * This is far more efficient than destroying and re-instantiating a
2027 * Dygraph, since it doesn't have to reparse the underlying data.
2029 * @param {Number} width Width (in pixels)
2030 * @param {Number} height Height (in pixels)
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;
2039 // TODO(danvk): there should be a clear() method.
2040 this.maindiv_
.innerHTML
= "";
2041 this.attrs_
.labelsDiv
= null;
2044 this.maindiv_
.style
.width
= width
+ "px";
2045 this.maindiv_
.style
.height
= height
+ "px";
2046 this.width_
= width
;
2047 this.height_
= height
;
2049 this.width_
= this.maindiv_
.offsetWidth
;
2050 this.height_
= this.maindiv_
.offsetHeight
;
2053 this.createInterface_();
2054 this.drawGraph_(this.rawData_
);
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.
2062 Dygraph
.prototype.adjustRoll
= function(length
) {
2063 this.rollPeriod_
= length
;
2064 this.drawGraph_(this.rawData_
);
2068 * Returns a boolean array of visibility statuses.
2070 Dygraph
.prototype.visibility
= function() {
2071 // Do lazy-initialization, so that this happens after we know the number of
2073 if (!this.attr_("visibility")) {
2074 this.attrs_
["visibility"] = [];
2076 while (this.attr_("visibility").length
< this.rawData_
[0].length
- 1) {
2077 this.attr_("visibility").push(true);
2079 return this.attr_("visibility");
2083 * Changes the visiblity of a series.
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
);
2091 this.drawGraph_(this.rawData_
);
2096 * Create a new canvas element. This is more complex than a simple
2097 * document.createElement("canvas") because of IE and excanvas.
2099 Dygraph
.createCanvas
= function() {
2100 var canvas
= document
.createElement("canvas");
2102 isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
2104 canvas
= G_vmlCanvasManager
.initElement(canvas
);
2112 * A wrapper around Dygraph that implements the gviz API.
2113 * @param {Object} container The DOM object the visualization should live in.
2115 Dygraph
.GVizChart
= function(container
) {
2116 this.container
= container
;
2119 Dygraph
.GVizChart
.prototype.draw
= function(data
, options
) {
2120 this.container
.innerHTML
= '';
2121 this.date_graph
= new Dygraph(this.container
, data
, options
);
2124 // Older pages may still use this name.
2125 DateGraph
= Dygraph
;