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://dygraphs.com/
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__();
77 * Formatting to use for an integer number.
79 * @param {Number} x The number to format
80 * @param {Number} unused_precision The precision to use, ignored.
81 * @return {String} A string formatted like %g in printf. The max generated
82 * string length should be precision + 6 (e.g 1.123e+300).
84 Dygraph
.intFormat
= function(x
, unused_precision
) {
89 * Number formatting function which mimicks the behavior of %g in printf, i.e.
90 * either exponential or fixed format (without trailing 0s) is used depending on
91 * the length of the generated string. The advantage of this format is that
92 * there is a predictable upper bound on the resulting string length,
93 * significant figures are not dropped, and normal numbers are not displayed in
94 * exponential notation.
96 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
97 * It creates strings which are too long for absolute values between 10^-4 and
98 * 10^-6. See tests/number-format.html for output examples.
100 * @param {Number} x The number to format
101 * @param {Number} opt_precision The precision to use, default 2.
102 * @return {String} A string formatted like %g in printf. The max generated
103 * string length should be precision + 6 (e.g 1.123e+300).
105 Dygraph
.floatFormat
= function(x
, opt_precision
) {
106 // Avoid invalid precision values; [1, 21] is the valid range.
107 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
109 // This is deceptively simple. The actual algorithm comes from:
111 // Max allowed length = p + 4
112 // where 4 comes from 'e+n' and '.'.
114 // Length of fixed format = 2 + y + p
115 // where 2 comes from '0.' and y = # of leading zeroes.
117 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
120 // Since the behavior of toPrecision() is identical for larger numbers, we
121 // don't have to worry about the other bound.
123 // Finally, the argument for toExponential() is the number of trailing digits,
124 // so we take off 1 for the value before the '.'.
125 return (Math
.abs(x
) < 1.0e-3 && x
!= 0.0) ?
126 x
.toExponential(p
- 1) : x
.toPrecision(p
);
129 // Various default values
130 Dygraph
.DEFAULT_ROLL_PERIOD
= 1;
131 Dygraph
.DEFAULT_WIDTH
= 480;
132 Dygraph
.DEFAULT_HEIGHT
= 320;
133 Dygraph
.AXIS_LINE_WIDTH
= 0.3;
136 // Default attribute values.
137 Dygraph
.DEFAULT_ATTRS
= {
138 highlightCircleSize
: 3,
144 // TODO(danvk): move defaults from createStatusMessage_ here.
146 labelsSeparateLines
: false,
147 labelsShowZeroValues
: true,
150 showLabelsOnHighlight
: true,
152 yValueFormatter
: Dygraph
.floatFormat
,
157 axisLabelFontSize
: 14,
160 xAxisLabelFormatter
: Dygraph
.dateAxisFormatter
,
164 xValueFormatter
: Dygraph
.dateString_
,
165 xValueParser
: Dygraph
.dateParser
,
166 xTicker
: Dygraph
.dateTicker
,
174 wilsonInterval
: true, // only relevant if fractions is true
178 connectSeparatedPoints
: false,
181 hideOverlayOnMouseOut
: true,
186 interactionModel
: null // will be set to Dygraph.defaultInteractionModel.
189 // Various logging levels.
195 // Directions for panning and zooming. Use bit operations when combined
196 // values are possible.
197 Dygraph
.HORIZONTAL
= 1;
198 Dygraph
.VERTICAL
= 2;
200 // Used for initializing annotation CSS rules only once.
201 Dygraph
.addedAnnotationCSS
= false;
203 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
204 // Labels is no longer a constructor parameter, since it's typically set
205 // directly from the data source. It also conains a name for the x-axis,
206 // which the previous constructor form did not.
207 if (labels
!= null) {
208 var new_labels
= ["Date"];
209 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
210 Dygraph
.update(attrs
, { 'labels': new_labels
});
212 this.__init__(div
, file
, attrs
);
216 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
217 * and context <canvas> inside of it. See the constructor for details
219 * @param {Element} div the Element to render the graph into.
220 * @param {String | Function} file Source data
221 * @param {Object} attrs Miscellaneous other options
224 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
225 // Hack for IE: if we're using excanvas and the document hasn't finished
226 // loading yet (and hence may not have initialized whatever it needs to
227 // initialize), then keep calling this routine periodically until it has.
228 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
229 typeof(G_vmlCanvasManager
) != 'undefined' &&
230 document
.readyState
!= 'complete') {
232 setTimeout(function() { self
.__init__(div
, file
, attrs
) }, 100);
235 // Support two-argument constructor
236 if (attrs
== null) { attrs
= {}; }
238 // Copy the important bits into the object
239 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
242 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
243 this.previousVerticalX_
= -1;
244 this.fractions_
= attrs
.fractions
|| false;
245 this.dateWindow_
= attrs
.dateWindow
|| null;
247 this.wilsonInterval_
= attrs
.wilsonInterval
|| true;
248 this.is_initial_draw_
= true;
249 this.annotations_
= [];
251 // Number of digits to use when labeling the x (if numeric) and y axis
253 this.numXDigits_
= 2;
254 this.numYDigits_
= 2;
256 // When labeling x (if numeric) or y values in the legend, there are
257 // numDigits + numExtraDigits of precision used. For axes labels with N
258 // digits of precision, the data should be displayed with at least N+1 digits
259 // of precision. The reason for this is to divide each interval between
260 // successive ticks into tenths (for 1) or hundredths (for 2), etc. For
261 // example, if the labels are [0, 1, 2], we want data to be displayed as
263 this.numExtraDigits_
= 1;
265 // Clear the div. This ensure that, if multiple dygraphs are passed the same
266 // div, then only one will be drawn.
269 // If the div isn't already sized then inherit from our attrs or
270 // give it a default size.
271 if (div
.style
.width
== '') {
272 div
.style
.width
= (attrs
.width
|| Dygraph
.DEFAULT_WIDTH
) + "px";
274 if (div
.style
.height
== '') {
275 div
.style
.height
= (attrs
.height
|| Dygraph
.DEFAULT_HEIGHT
) + "px";
277 this.width_
= parseInt(div
.style
.width
, 10);
278 this.height_
= parseInt(div
.style
.height
, 10);
279 // The div might have been specified as percent of the current window size,
280 // convert that to an appropriate number of pixels.
281 if (div
.style
.width
.indexOf("%") == div
.style
.width
.length
- 1) {
282 this.width_
= div
.offsetWidth
;
284 if (div
.style
.height
.indexOf("%") == div
.style
.height
.length
- 1) {
285 this.height_
= div
.offsetHeight
;
288 if (this.width_
== 0) {
289 this.error("dygraph has zero width. Please specify a width in pixels.");
291 if (this.height_
== 0) {
292 this.error("dygraph has zero height. Please specify a height in pixels.");
295 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
296 if (attrs
['stackedGraph']) {
297 attrs
['fillGraph'] = true;
298 // TODO(nikhilk): Add any other stackedGraph checks here.
301 // Dygraphs has many options, some of which interact with one another.
302 // To keep track of everything, we maintain two sets of options:
304 // this.user_attrs_ only options explicitly set by the user.
305 // this.attrs_ defaults, options derived from user_attrs_, data.
307 // Options are then accessed this.attr_('attr'), which first looks at
308 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
309 // defaults without overriding behavior that the user specifically asks for.
310 this.user_attrs_
= {};
311 Dygraph
.update(this.user_attrs_
, attrs
);
314 Dygraph
.update(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
316 this.boundaryIds_
= [];
318 // Make a note of whether labels will be pulled from the CSV file.
319 this.labelsFromCSV_
= (this.attr_("labels") == null);
321 // Create the containing DIV and other interactive elements
322 this.createInterface_();
327 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
329 typeof(this.user_attrs_
[seriesName
]) != 'undefined' &&
330 this.user_attrs_
[seriesName
] != null &&
331 typeof(this.user_attrs_
[seriesName
][name
]) != 'undefined') {
332 return this.user_attrs_
[seriesName
][name
];
333 } else if (typeof(this.user_attrs_
[name
]) != 'undefined') {
334 return this.user_attrs_
[name
];
335 } else if (typeof(this.attrs_
[name
]) != 'undefined') {
336 return this.attrs_
[name
];
342 // TODO(danvk): any way I can get the line numbers to be this.warn call?
343 Dygraph
.prototype.log
= function(severity
, message
) {
344 if (typeof(console
) != 'undefined') {
347 console
.debug('dygraphs: ' + message
);
350 console
.info('dygraphs: ' + message
);
352 case Dygraph
.WARNING
:
353 console
.warn('dygraphs: ' + message
);
356 console
.error('dygraphs: ' + message
);
361 Dygraph
.prototype.info
= function(message
) {
362 this.log(Dygraph
.INFO
, message
);
364 Dygraph
.prototype.warn
= function(message
) {
365 this.log(Dygraph
.WARNING
, message
);
367 Dygraph
.prototype.error
= function(message
) {
368 this.log(Dygraph
.ERROR
, message
);
372 * Returns the current rolling period, as set by the user or an option.
373 * @return {Number} The number of points in the rolling window
375 Dygraph
.prototype.rollPeriod
= function() {
376 return this.rollPeriod_
;
380 * Returns the currently-visible x-range. This can be affected by zooming,
381 * panning or a call to updateOptions.
382 * Returns a two-element array: [left, right].
383 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
385 Dygraph
.prototype.xAxisRange
= function() {
386 if (this.dateWindow_
) return this.dateWindow_
;
388 // The entire chart is visible.
389 var left
= this.rawData_
[0][0];
390 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
391 return [left
, right
];
395 * Returns the currently-visible y-range for an axis. This can be affected by
396 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
397 * called with no arguments, returns the range of the first axis.
398 * Returns a two-element array: [bottom, top].
400 Dygraph
.prototype.yAxisRange
= function(idx
) {
401 if (typeof(idx
) == "undefined") idx
= 0;
402 if (idx
< 0 || idx
>= this.axes_
.length
) return null;
403 return [ this.axes_
[idx
].computedValueRange
[0],
404 this.axes_
[idx
].computedValueRange
[1] ];
408 * Returns the currently-visible y-ranges for each axis. This can be affected by
409 * zooming, panning, calls to updateOptions, etc.
410 * Returns an array of [bottom, top] pairs, one for each y-axis.
412 Dygraph
.prototype.yAxisRanges
= function() {
414 for (var i
= 0; i
< this.axes_
.length
; i
++) {
415 ret
.push(this.yAxisRange(i
));
420 // TODO(danvk): use these functions throughout dygraphs.
422 * Convert from data coordinates to canvas/div X/Y coordinates.
423 * If specified, do this conversion for the coordinate system of a particular
424 * axis. Uses the first axis by default.
425 * Returns a two-element array: [X, Y]
427 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
428 var ret
= [null, null];
429 var area
= this.plotter_
.area
;
431 var xRange
= this.xAxisRange();
432 ret
[0] = area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
436 var yRange
= this.yAxisRange(axis
);
437 ret
[1] = area
.y
+ (yRange
[1] - y
) / (yRange
[1] - yRange
[0]) * area
.h
;
444 * Convert from canvas/div coords to data coordinates.
445 * If specified, do this conversion for the coordinate system of a particular
446 * axis. Uses the first axis by default.
447 * Returns a two-element array: [X, Y]
449 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
450 var ret
= [null, null];
451 var area
= this.plotter_
.area
;
453 var xRange
= this.xAxisRange();
454 ret
[0] = xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
458 var yRange
= this.yAxisRange(axis
);
459 ret
[1] = yRange
[0] + (area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
466 * Returns the number of columns (including the independent variable).
468 Dygraph
.prototype.numColumns
= function() {
469 return this.rawData_
[0].length
;
473 * Returns the number of rows (excluding any header/label row).
475 Dygraph
.prototype.numRows
= function() {
476 return this.rawData_
.length
;
480 * Returns the value in the given row and column. If the row and column exceed
481 * the bounds on the data, returns null. Also returns null if the value is
484 Dygraph
.prototype.getValue
= function(row
, col
) {
485 if (row
< 0 || row
> this.rawData_
.length
) return null;
486 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
488 return this.rawData_
[row
][col
];
491 Dygraph
.addEvent
= function(el
, evt
, fn
) {
492 var normed_fn
= function(e
) {
493 if (!e
) var e
= window
.event
;
496 if (window
.addEventListener
) { // Mozilla, Netscape, Firefox
497 el
.addEventListener(evt
, normed_fn
, false);
499 el
.attachEvent('on' + evt
, normed_fn
);
504 // Based on the article at
505 // http://www.switchonthecode.com/tutorials
/javascript
-tutorial
-the
-scroll
-wheel
506 Dygraph
.cancelEvent
= function(e
) {
507 e
= e
? e
: window
.event
;
508 if (e
.stopPropagation
) {
511 if (e
.preventDefault
) {
514 e
.cancelBubble
= true;
516 e
.returnValue
= false;
522 * Generates interface elements for the Dygraph: a containing div, a div to
523 * display the current point, and a textbox to adjust the rolling average
524 * period. Also creates the Renderer/Layout elements.
527 Dygraph
.prototype.createInterface_
= function() {
528 // Create the all-enclosing graph div
529 var enclosing
= this.maindiv_
;
531 this.graphDiv
= document
.createElement("div");
532 this.graphDiv
.style
.width
= this.width_
+ "px";
533 this.graphDiv
.style
.height
= this.height_
+ "px";
534 enclosing
.appendChild(this.graphDiv
);
536 // Create the canvas for interactive parts of the chart.
537 this.canvas_
= Dygraph
.createCanvas();
538 this.canvas_
.style
.position
= "absolute";
539 this.canvas_
.width
= this.width_
;
540 this.canvas_
.height
= this.height_
;
541 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
542 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
544 // ... and for static parts of the chart.
545 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
547 // The interactive parts of the graph are drawn on top of the chart.
548 this.graphDiv
.appendChild(this.hidden_
);
549 this.graphDiv
.appendChild(this.canvas_
);
550 this.mouseEventElement_
= this.canvas_
;
553 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', function(e
) {
554 dygraph
.mouseMove_(e
);
556 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', function(e
) {
557 dygraph
.mouseOut_(e
);
560 // Create the grapher
561 // TODO(danvk): why does the Layout need its own set of options?
562 this.layoutOptions_
= { 'xOriginIsZero': false };
563 Dygraph
.update(this.layoutOptions_
, this.attrs_
);
564 Dygraph
.update(this.layoutOptions_
, this.user_attrs_
);
565 Dygraph
.update(this.layoutOptions_
, {
566 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
568 this.layout_
= new DygraphLayout(this, this.layoutOptions_
);
570 // TODO(danvk): why does the Renderer need its own set of options?
571 this.renderOptions_
= { colorScheme
: this.colors_
,
573 axisLineWidth
: Dygraph
.AXIS_LINE_WIDTH
};
574 Dygraph
.update(this.renderOptions_
, this.attrs_
);
575 Dygraph
.update(this.renderOptions_
, this.user_attrs_
);
577 this.createStatusMessage_();
578 this.createDragInterface_();
582 * Detach DOM elements in the dygraph and null out all data references.
583 * Calling this when you're done with a dygraph can dramatically reduce memory
584 * usage. See, e.g., the tests/perf.html example.
586 Dygraph
.prototype.destroy
= function() {
587 var removeRecursive
= function(node
) {
588 while (node
.hasChildNodes()) {
589 removeRecursive(node
.firstChild
);
590 node
.removeChild(node
.firstChild
);
593 removeRecursive(this.maindiv_
);
595 var nullOut
= function(obj
) {
597 if (typeof(obj
[n
]) === 'object') {
603 // These may not all be necessary, but it can't hurt...
604 nullOut(this.layout_
);
605 nullOut(this.plotter_
);
610 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
611 * this particular canvas. All Dygraph work is done on this.canvas_.
612 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
613 * @return {Object} The newly-created canvas
616 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
617 var h
= Dygraph
.createCanvas();
618 h
.style
.position
= "absolute";
619 // TODO(danvk): h should be offset from canvas. canvas needs to include
620 // some extra area to make it easier to zoom in on the far left and far
621 // right. h needs to be precisely the plot area, so that clipping occurs.
622 h
.style
.top
= canvas
.style
.top
;
623 h
.style
.left
= canvas
.style
.left
;
624 h
.width
= this.width_
;
625 h
.height
= this.height_
;
626 h
.style
.width
= this.width_
+ "px"; // for IE
627 h
.style
.height
= this.height_
+ "px"; // for IE
631 // Taken from MochiKit.Color
632 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
636 if (saturation
=== 0) {
641 var i
= Math
.floor(hue
* 6);
642 var f
= (hue
* 6) - i
;
643 var p
= value
* (1 - saturation
);
644 var q
= value
* (1 - (saturation
* f
));
645 var t
= value
* (1 - (saturation
* (1 - f
)));
647 case 1: red
= q
; green
= value
; blue
= p
; break;
648 case 2: red
= p
; green
= value
; blue
= t
; break;
649 case 3: red
= p
; green
= q
; blue
= value
; break;
650 case 4: red
= t
; green
= p
; blue
= value
; break;
651 case 5: red
= value
; green
= p
; blue
= q
; break;
652 case 6: // fall through
653 case 0: red
= value
; green
= t
; blue
= p
; break;
656 red
= Math
.floor(255 * red
+ 0.5);
657 green
= Math
.floor(255 * green
+ 0.5);
658 blue
= Math
.floor(255 * blue
+ 0.5);
659 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
664 * Generate a set of distinct colors for the data series. This is done with a
665 * color wheel. Saturation/Value are customizable, and the hue is
666 * equally-spaced around the color wheel. If a custom set of colors is
667 * specified, that is used instead.
670 Dygraph
.prototype.setColors_
= function() {
671 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
672 // away with this.renderOptions_.
673 var num
= this.attr_("labels").length
- 1;
675 var colors
= this.attr_('colors');
677 var sat
= this.attr_('colorSaturation') || 1.0;
678 var val
= this.attr_('colorValue') || 0.5;
679 var half
= Math
.ceil(num
/ 2);
680 for (var i
= 1; i
<= num
; i
++) {
681 if (!this.visibility()[i
-1]) continue;
682 // alternate colors for high contrast.
683 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
684 var hue
= (1.0 * idx
/ (1 + num
));
685 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
688 for (var i
= 0; i
< num
; i
++) {
689 if (!this.visibility()[i
]) continue;
690 var colorStr
= colors
[i
% colors
.length
];
691 this.colors_
.push(colorStr
);
695 // TODO(danvk): update this w/r
/t/ the
new options system
.
696 this.renderOptions_
.colorScheme
= this.colors_
;
697 Dygraph
.update(this.plotter_
.options
, this.renderOptions_
);
698 Dygraph
.update(this.layoutOptions_
, this.user_attrs_
);
699 Dygraph
.update(this.layoutOptions_
, this.attrs_
);
703 * Return the list of colors. This is either the list of colors passed in the
704 * attributes, or the autogenerated list of rgb(r,g,b) strings.
705 * @return {Array<string>} The list of colors.
707 Dygraph
.prototype.getColors
= function() {
711 // The following functions are from quirksmode.org with a modification for Safari from
712 // http://blog.firetree.net/2005/07/04/javascript-find-position/
713 // http://www.quirksmode.org/js
/findpos
.html
714 Dygraph
.findPosX
= function(obj
) {
719 curleft
+= obj
.offsetLeft
;
720 if(!obj
.offsetParent
)
722 obj
= obj
.offsetParent
;
729 Dygraph
.findPosY
= function(obj
) {
734 curtop
+= obj
.offsetTop
;
735 if(!obj
.offsetParent
)
737 obj
= obj
.offsetParent
;
747 * Create the div that contains information on the selected point(s)
748 * This goes in the top right of the canvas, unless an external div has already
752 Dygraph
.prototype.createStatusMessage_
= function() {
753 var userLabelsDiv
= this.user_attrs_
["labelsDiv"];
754 if (userLabelsDiv
&& null != userLabelsDiv
755 && (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
)) {
756 this.user_attrs_
["labelsDiv"] = document
.getElementById(userLabelsDiv
);
758 if (!this.attr_("labelsDiv")) {
759 var divWidth
= this.attr_('labelsDivWidth');
761 "position": "absolute",
764 "width": divWidth
+ "px",
766 "left": (this.width_
- divWidth
- 2) + "px",
767 "background": "white",
769 "overflow": "hidden"};
770 Dygraph
.update(messagestyle
, this.attr_('labelsDivStyles'));
771 var div
= document
.createElement("div");
772 for (var name
in messagestyle
) {
773 if (messagestyle
.hasOwnProperty(name
)) {
774 div
.style
[name
] = messagestyle
[name
];
777 this.graphDiv
.appendChild(div
);
778 this.attrs_
.labelsDiv
= div
;
783 * Position the labels div so that its right edge is flush with the right edge
784 * of the charting area.
786 Dygraph
.prototype.positionLabelsDiv_
= function() {
787 // Don't touch a user-specified labelsDiv.
788 if (this.user_attrs_
.hasOwnProperty("labelsDiv")) return;
790 var area
= this.plotter_
.area
;
791 var div
= this.attr_("labelsDiv");
792 div
.style
.left
= area
.x
+ area
.w
- this.attr_("labelsDivWidth") - 1 + "px";
796 * Create the text box to adjust the averaging period
799 Dygraph
.prototype.createRollInterface_
= function() {
800 // Create a roller if one doesn't exist already.
802 this.roller_
= document
.createElement("input");
803 this.roller_
.type
= "text";
804 this.roller_
.style
.display
= "none";
805 this.graphDiv
.appendChild(this.roller_
);
808 var display
= this.attr_('showRoller') ? 'block' : 'none';
810 var textAttr
= { "position": "absolute",
812 "top": (this.plotter_
.area
.h
- 25) + "px",
813 "left": (this.plotter_
.area
.x
+ 1) + "px",
816 this.roller_
.size
= "2";
817 this.roller_
.value
= this.rollPeriod_
;
818 for (var name
in textAttr
) {
819 if (textAttr
.hasOwnProperty(name
)) {
820 this.roller_
.style
[name
] = textAttr
[name
];
825 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
828 // These functions are taken from MochiKit.Signal
829 Dygraph
.pageX
= function(e
) {
831 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
834 var b
= document
.body
;
836 (de
.scrollLeft
|| b
.scrollLeft
) -
837 (de
.clientLeft
|| 0);
841 Dygraph
.pageY
= function(e
) {
843 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
846 var b
= document
.body
;
848 (de
.scrollTop
|| b
.scrollTop
) -
853 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
854 return Dygraph
.pageX(e
) - context
.px
857 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
858 return Dygraph
.pageY(e
) - context
.py
861 // Called in response to an interaction model operation that
862 // should start the default panning behavior.
864 // It's used in the default callback for "mousedown" operations.
865 // Custom interaction model builders can use it to provide the default
868 Dygraph
.startPan
= function(event
, g
, context
) {
869 // have to be zoomed in to pan.
870 // TODO(konigsberg): Let's loosen this zoom-to-pan restriction, also
871 // perhaps create panning boundaries? A more flexible pan would make it,
872 // ahem, 'pan-useful'.
874 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
875 if (g
.axes_
[i
].valueWindow
|| g
.axes_
[i
].valueRange
) {
880 if (!g
.dateWindow_
&& !zoomedY
) return;
882 context
.isPanning
= true;
883 var xRange
= g
.xAxisRange();
884 context
.dateRange
= xRange
[1] - xRange
[0];
886 // Record the range of each y-axis at the start of the drag.
887 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
888 context
.is2DPan
= false;
889 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
890 var axis
= g
.axes_
[i
];
891 var yRange
= g
.yAxisRange(i
);
892 axis
.dragValueRange
= yRange
[1] - yRange
[0];
893 var r
= g
.toDataCoords(null, context
.dragStartY
, i
);
894 axis
.draggingValue
= r
[1];
895 if (axis
.valueWindow
|| axis
.valueRange
) context
.is2DPan
= true;
898 // TODO(konigsberg): Switch from all this math to toDataCoords?
899 // Seems to work for the dragging value.
900 context
.draggingDate
= (context
.dragStartX
/ g
.width_
) * context
.dateRange
+ xRange
[0];
903 // Called in response to an interaction model operation that
904 // responds to an event that pans the view.
906 // It's used in the default callback for "mousemove" operations.
907 // Custom interaction model builders can use it to provide the default
910 Dygraph
.movePan
= function(event
, g
, context
) {
911 context
.dragEndX
= g
.dragGetX_(event
, context
);
912 context
.dragEndY
= g
.dragGetY_(event
, context
);
914 // TODO(danvk): update this comment
915 // Want to have it so that:
916 // 1. draggingDate appears at dragEndX, draggingValue appears at dragEndY.
917 // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
918 // 3. draggingValue appears at dragEndY.
919 // 4. valueRange is unaltered.
921 var minDate
= context
.draggingDate
- (context
.dragEndX
/ g
.width_
) * context
.dateRange
;
922 var maxDate
= minDate
+ context
.dateRange
;
923 g
.dateWindow_
= [minDate
, maxDate
];
925 // y-axis scaling is automatic unless this is a full 2D pan.
926 if (context
.is2DPan
) {
927 // Adjust each axis appropriately.
928 var y_frac
= context
.dragEndY
/ g
.height_
;
929 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
930 var axis
= g
.axes_
[i
];
931 var maxValue
= axis
.draggingValue
+ y_frac
* axis
.dragValueRange
;
932 var minValue
= maxValue
- axis
.dragValueRange
;
933 axis
.valueWindow
= [ minValue
, maxValue
];
940 // Called in response to an interaction model operation that
941 // responds to an event that ends panning.
943 // It's used in the default callback for "mouseup" operations.
944 // Custom interaction model builders can use it to provide the default
947 Dygraph
.endPan
= function(event
, g
, context
) {
948 context
.isPanning
= false;
949 context
.is2DPan
= false;
950 context
.draggingDate
= null;
951 context
.dateRange
= null;
952 context
.valueRange
= null;
955 // Called in response to an interaction model operation that
956 // responds to an event that starts zooming.
958 // It's used in the default callback for "mousedown" operations.
959 // Custom interaction model builders can use it to provide the default
962 Dygraph
.startZoom
= function(event
, g
, context
) {
963 context
.isZooming
= true;
966 // Called in response to an interaction model operation that
967 // responds to an event that defines zoom boundaries.
969 // It's used in the default callback for "mousemove" operations.
970 // Custom interaction model builders can use it to provide the default
973 Dygraph
.moveZoom
= function(event
, g
, context
) {
974 context
.dragEndX
= g
.dragGetX_(event
, context
);
975 context
.dragEndY
= g
.dragGetY_(event
, context
);
977 var xDelta
= Math
.abs(context
.dragStartX
- context
.dragEndX
);
978 var yDelta
= Math
.abs(context
.dragStartY
- context
.dragEndY
);
980 // drag direction threshold for y axis is twice as large as x axis
981 context
.dragDirection
= (xDelta
< yDelta
/ 2) ? Dygraph
.VERTICAL
: Dygraph
.HORIZONTAL
;
984 context
.dragDirection
,
989 context
.prevDragDirection
,
993 context
.prevEndX
= context
.dragEndX
;
994 context
.prevEndY
= context
.dragEndY
;
995 context
.prevDragDirection
= context
.dragDirection
;
998 // Called in response to an interaction model operation that
999 // responds to an event that performs a zoom based on previously defined
1002 // It's used in the default callback for "mouseup" operations.
1003 // Custom interaction model builders can use it to provide the default
1004 // zooming behavior.
1006 Dygraph
.endZoom
= function(event
, g
, context
) {
1007 context
.isZooming
= false;
1008 context
.dragEndX
= g
.dragGetX_(event
, context
);
1009 context
.dragEndY
= g
.dragGetY_(event
, context
);
1010 var regionWidth
= Math
.abs(context
.dragEndX
- context
.dragStartX
);
1011 var regionHeight
= Math
.abs(context
.dragEndY
- context
.dragStartY
);
1013 if (regionWidth
< 2 && regionHeight
< 2 &&
1014 g
.lastx_
!= undefined
&& g
.lastx_
!= -1) {
1015 // TODO(danvk): pass along more info about the points, e.g. 'x'
1016 if (g
.attr_('clickCallback') != null) {
1017 g
.attr_('clickCallback')(event
, g
.lastx_
, g
.selPoints_
);
1019 if (g
.attr_('pointClickCallback')) {
1020 // check if the click was on a particular point.
1021 var closestIdx
= -1;
1022 var closestDistance
= 0;
1023 for (var i
= 0; i
< g
.selPoints_
.length
; i
++) {
1024 var p
= g
.selPoints_
[i
];
1025 var distance
= Math
.pow(p
.canvasx
- context
.dragEndX
, 2) +
1026 Math
.pow(p
.canvasy
- context
.dragEndY
, 2);
1027 if (closestIdx
== -1 || distance
< closestDistance
) {
1028 closestDistance
= distance
;
1033 // Allow any click within two pixels of the dot.
1034 var radius
= g
.attr_('highlightCircleSize') + 2;
1035 if (closestDistance
<= 5 * 5) {
1036 g
.attr_('pointClickCallback')(event
, g
.selPoints_
[closestIdx
]);
1041 if (regionWidth
>= 10 && context
.dragDirection
== Dygraph
.HORIZONTAL
) {
1042 g
.doZoomX_(Math
.min(context
.dragStartX
, context
.dragEndX
),
1043 Math
.max(context
.dragStartX
, context
.dragEndX
));
1044 } else if (regionHeight
>= 10 && context
.dragDirection
== Dygraph
.VERTICAL
) {
1045 g
.doZoomY_(Math
.min(context
.dragStartY
, context
.dragEndY
),
1046 Math
.max(context
.dragStartY
, context
.dragEndY
));
1048 g
.canvas_
.getContext("2d").clearRect(0, 0,
1052 context
.dragStartX
= null;
1053 context
.dragStartY
= null;
1056 Dygraph
.defaultInteractionModel
= {
1057 // Track the beginning of drag events
1058 mousedown
: function(event
, g
, context
) {
1059 context
.initializeMouseDown(event
, g
, context
);
1061 if (event
.altKey
|| event
.shiftKey
) {
1062 Dygraph
.startPan(event
, g
, context
);
1064 Dygraph
.startZoom(event
, g
, context
);
1068 // Draw zoom rectangles when the mouse is down and the user moves around
1069 mousemove
: function(event
, g
, context
) {
1070 if (context
.isZooming
) {
1071 Dygraph
.moveZoom(event
, g
, context
);
1072 } else if (context
.isPanning
) {
1073 Dygraph
.movePan(event
, g
, context
);
1077 mouseup
: function(event
, g
, context
) {
1078 if (context
.isZooming
) {
1079 Dygraph
.endZoom(event
, g
, context
);
1080 } else if (context
.isPanning
) {
1081 Dygraph
.endPan(event
, g
, context
);
1085 // Temporarily cancel the dragging event when the mouse leaves the graph
1086 mouseout
: function(event
, g
, context
) {
1087 if (context
.isZooming
) {
1088 context
.dragEndX
= null;
1089 context
.dragEndY
= null;
1093 // Disable zooming out if panning.
1094 dblclick
: function(event
, g
, context
) {
1095 if (event
.altKey
|| event
.shiftKey
) {
1098 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1099 // friendlier to public use.
1104 Dygraph
.DEFAULT_ATTRS
.interactionModel
= Dygraph
.defaultInteractionModel
;
1107 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1111 Dygraph
.prototype.createDragInterface_
= function() {
1113 // Tracks whether the mouse is down right now
1115 isPanning
: false, // is this drag part of a pan?
1116 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1121 dragDirection
: null,
1124 prevDragDirection
: null,
1126 // TODO(danvk): update this comment
1127 // draggingDate and draggingValue represent the [date,value] point on the
1128 // graph at which the mouse was pressed. As the mouse moves while panning,
1129 // the viewport must pan so that the mouse position points to
1130 // [draggingDate, draggingValue]
1133 // TODO(danvk): update this comment
1134 // The range in second/value units that the viewport encompasses during a
1135 // panning operation.
1138 // Utility function to convert page-wide coordinates to canvas coords
1142 initializeMouseDown
: function(event
, g
, context
) {
1143 // prevents mouse drags from selecting page text.
1144 if (event
.preventDefault
) {
1145 event
.preventDefault(); // Firefox, Chrome, etc.
1147 event
.returnValue
= false; // IE
1148 event
.cancelBubble
= true;
1151 context
.px
= Dygraph
.findPosX(g
.canvas_
);
1152 context
.py
= Dygraph
.findPosY(g
.canvas_
);
1153 context
.dragStartX
= g
.dragGetX_(event
, context
);
1154 context
.dragStartY
= g
.dragGetY_(event
, context
);
1158 var interactionModel
= this.attr_("interactionModel");
1160 // Self is the graph.
1163 // Function that binds the graph and context to the handler.
1164 var bindHandler
= function(handler
) {
1165 return function(event
) {
1166 handler(event
, self
, context
);
1170 for (var eventName
in interactionModel
) {
1171 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1172 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
1173 bindHandler(interactionModel
[eventName
]));
1176 // If the user releases the mouse button during a drag, but not over the
1177 // canvas, then it doesn't count as a zooming action.
1178 Dygraph
.addEvent(document
, 'mouseup', function(event
) {
1179 if (context
.isZooming
|| context
.isPanning
) {
1180 context
.isZooming
= false;
1181 context
.dragStartX
= null;
1182 context
.dragStartY
= null;
1185 if (context
.isPanning
) {
1186 context
.isPanning
= false;
1187 context
.draggingDate
= null;
1188 context
.dateRange
= null;
1189 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1190 delete self
.axes_
[i
].draggingValue
;
1191 delete self
.axes_
[i
].dragValueRange
;
1199 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1200 * up any previous zoom rectangles that were drawn. This could be optimized to
1201 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1204 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1205 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1206 * @param {Number} startX The X position where the drag started, in canvas
1208 * @param {Number} endX The current X position of the drag, in canvas coords.
1209 * @param {Number} startY The Y position where the drag started, in canvas
1211 * @param {Number} endY The current Y position of the drag, in canvas coords.
1212 * @param {Number} prevDirection the value of direction on the previous call to
1213 * this function. Used to avoid excess redrawing
1214 * @param {Number} prevEndX The value of endX on the previous call to this
1215 * function. Used to avoid excess redrawing
1216 * @param {Number} prevEndY The value of endY on the previous call to this
1217 * function. Used to avoid excess redrawing
1220 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1221 endY
, prevDirection
, prevEndX
,
1223 var ctx
= this.canvas_
.getContext("2d");
1225 // Clean up from the previous rect if necessary
1226 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1227 ctx
.clearRect(Math
.min(startX
, prevEndX
), 0,
1228 Math
.abs(startX
- prevEndX
), this.height_
);
1229 } else if (prevDirection
== Dygraph
.VERTICAL
){
1230 ctx
.clearRect(0, Math
.min(startY
, prevEndY
),
1231 this.width_
, Math
.abs(startY
- prevEndY
));
1234 // Draw a light-grey rectangle to show the new viewing area
1235 if (direction
== Dygraph
.HORIZONTAL
) {
1236 if (endX
&& startX
) {
1237 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1238 ctx
.fillRect(Math
.min(startX
, endX
), 0,
1239 Math
.abs(endX
- startX
), this.height_
);
1242 if (direction
== Dygraph
.VERTICAL
) {
1243 if (endY
&& startY
) {
1244 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1245 ctx
.fillRect(0, Math
.min(startY
, endY
),
1246 this.width_
, Math
.abs(endY
- startY
));
1252 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1253 * the canvas. The exact zoom window may be slightly larger if there are no data
1254 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1255 * which accepts dates that match the raw data. This function redraws the graph.
1257 * @param {Number} lowX The leftmost pixel value that should be visible.
1258 * @param {Number} highX The rightmost pixel value that should be visible.
1261 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1262 // Find the earliest and latest dates contained in this canvasx range.
1263 // Convert the call to date ranges of the raw data.
1264 var r
= this.toDataCoords(lowX
, null);
1266 r
= this.toDataCoords(highX
, null);
1268 this.doZoomXDates_(minDate
, maxDate
);
1272 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1273 * method with doZoomX which accepts pixel coordinates. This function redraws
1276 * @param {Number} minDate The minimum date that should be visible.
1277 * @param {Number} maxDate The maximum date that should be visible.
1280 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1281 this.dateWindow_
= [minDate
, maxDate
];
1283 if (this.attr_("zoomCallback")) {
1284 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1289 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1290 * the canvas. This function redraws the graph.
1292 * @param {Number} lowY The topmost pixel value that should be visible.
1293 * @param {Number} highY The lowest pixel value that should be visible.
1296 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1297 // Find the highest and lowest values in pixel range for each axis.
1298 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1299 // This is because pixels increase as you go down on the screen, whereas data
1300 // coordinates increase as you go up the screen.
1301 var valueRanges
= [];
1302 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1303 var hi
= this.toDataCoords(null, lowY
, i
);
1304 var low
= this.toDataCoords(null, highY
, i
);
1305 this.axes_
[i
].valueWindow
= [low
[1], hi
[1]];
1306 valueRanges
.push([low
[1], hi
[1]]);
1310 if (this.attr_("zoomCallback")) {
1311 var xRange
= this.xAxisRange();
1312 this.attr_("zoomCallback")(xRange
[0], xRange
[1], this.yAxisRanges());
1317 * Reset the zoom to the original view coordinates. This is the same as
1318 * double-clicking on the graph.
1322 Dygraph
.prototype.doUnzoom_
= function() {
1324 if (this.dateWindow_
!= null) {
1326 this.dateWindow_
= null;
1329 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1330 if (this.axes_
[i
].valueWindow
!= null) {
1332 delete this.axes_
[i
].valueWindow
;
1337 // Putting the drawing operation before the callback because it resets
1340 if (this.attr_("zoomCallback")) {
1341 var minDate
= this.rawData_
[0][0];
1342 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1343 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1349 * When the mouse moves in the canvas, display information about a nearby data
1350 * point and draw dots over those points in the data series. This function
1351 * takes care of cleanup of previously-drawn dots.
1352 * @param {Object} event The mousemove event from the browser.
1355 Dygraph
.prototype.mouseMove_
= function(event
) {
1356 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1357 var points
= this.layout_
.points
;
1362 // Loop through all the points and find the date nearest to our current
1364 var minDist
= 1e+100;
1366 for (var i
= 0; i
< points
.length
; i
++) {
1367 var point
= points
[i
];
1368 if (point
== null) continue;
1369 var dist
= Math
.abs(point
.canvasx
- canvasx
);
1370 if (dist
> minDist
) continue;
1374 if (idx
>= 0) lastx
= points
[idx
].xval
;
1375 // Check that you can really highlight the last day's data
1376 var last
= points
[points
.length
-1];
1377 if (last
!= null && canvasx
> last
.canvasx
)
1378 lastx
= points
[points
.length
-1].xval
;
1380 // Extract the points we've selected
1381 this.selPoints_
= [];
1382 var l
= points
.length
;
1383 if (!this.attr_("stackedGraph")) {
1384 for (var i
= 0; i
< l
; i
++) {
1385 if (points
[i
].xval
== lastx
) {
1386 this.selPoints_
.push(points
[i
]);
1390 // Need to 'unstack' points starting from the bottom
1391 var cumulative_sum
= 0;
1392 for (var i
= l
- 1; i
>= 0; i
--) {
1393 if (points
[i
].xval
== lastx
) {
1394 var p
= {}; // Clone the point since we modify it
1395 for (var k
in points
[i
]) {
1396 p
[k
] = points
[i
][k
];
1398 p
.yval
-= cumulative_sum
;
1399 cumulative_sum
+= p
.yval
;
1400 this.selPoints_
.push(p
);
1403 this.selPoints_
.reverse();
1406 if (this.attr_("highlightCallback")) {
1407 var px
= this.lastx_
;
1408 if (px
!== null && lastx
!= px
) {
1409 // only fire if the selected point has changed.
1410 this.attr_("highlightCallback")(event
, lastx
, this.selPoints_
, this.idxToRow_(idx
));
1414 // Save last x position for callbacks.
1415 this.lastx_
= lastx
;
1417 this.updateSelection_();
1421 * Transforms layout_.points index into data row number.
1422 * @param int layout_.points index
1423 * @return int row number, or -1 if none could be found.
1426 Dygraph
.prototype.idxToRow_
= function(idx
) {
1427 if (idx
< 0) return -1;
1429 for (var i
in this.layout_
.datasets
) {
1430 if (idx
< this.layout_
.datasets
[i
].length
) {
1431 return this.boundaryIds_
[0][0]+idx
;
1433 idx
-= this.layout_
.datasets
[i
].length
;
1439 * Draw dots over the selectied points in the data series. This function
1440 * takes care of cleanup of previously-drawn dots.
1443 Dygraph
.prototype.updateSelection_
= function() {
1444 // Clear the previously drawn vertical, if there is one
1445 var ctx
= this.canvas_
.getContext("2d");
1446 if (this.previousVerticalX_
>= 0) {
1447 // Determine the maximum highlight circle size.
1448 var maxCircleSize
= 0;
1449 var labels
= this.attr_('labels');
1450 for (var i
= 1; i
< labels
.length
; i
++) {
1451 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1452 if (r
> maxCircleSize
) maxCircleSize
= r
;
1454 var px
= this.previousVerticalX_
;
1455 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1456 2 * maxCircleSize
+ 2, this.height_
);
1459 var isOK
= function(x
) { return x
&& !isNaN(x
); };
1461 if (this.selPoints_
.length
> 0) {
1462 var canvasx
= this.selPoints_
[0].canvasx
;
1464 // Set the status message to indicate the selected point(s)
1465 var replace
= this.attr_('xValueFormatter')(
1466 this.lastx_
, this.numXDigits_
+ this.numExtraDigits_
) + ":";
1467 var fmtFunc
= this.attr_('yValueFormatter');
1468 var clen
= this.colors_
.length
;
1470 if (this.attr_('showLabelsOnHighlight')) {
1471 // Set the status message to indicate the selected point(s)
1472 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1473 if (!this.attr_("labelsShowZeroValues") && this.selPoints_
[i
].yval
== 0) continue;
1474 if (!isOK(this.selPoints_
[i
].canvasy
)) continue;
1475 if (this.attr_("labelsSeparateLines")) {
1478 var point
= this.selPoints_
[i
];
1479 var c
= new RGBColor(this.plotter_
.colors
[point
.name
]);
1480 var yval
= fmtFunc(point
.yval
, this.numYDigits_
+ this.numExtraDigits_
);
1481 replace
+= " <b><font color='" + c
.toHex() + "'>"
1482 + point
.name
+ "</font></b>:"
1486 this.attr_("labelsDiv").innerHTML
= replace
;
1489 // Draw colored circles over the center of each selected point
1491 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1492 if (!isOK(this.selPoints_
[i
].canvasy
)) continue;
1494 this.attr_('highlightCircleSize', this.selPoints_
[i
].name
);
1496 ctx
.fillStyle
= this.plotter_
.colors
[this.selPoints_
[i
].name
];
1497 ctx
.arc(canvasx
, this.selPoints_
[i
].canvasy
, circleSize
,
1498 0, 2 * Math
.PI
, false);
1503 this.previousVerticalX_
= canvasx
;
1508 * Set manually set selected dots, and display information about them
1509 * @param int row number that should by highlighted
1510 * false value clears the selection
1513 Dygraph
.prototype.setSelection
= function(row
) {
1514 // Extract the points we've selected
1515 this.selPoints_
= [];
1518 if (row
!== false) {
1519 row
= row
-this.boundaryIds_
[0][0];
1522 if (row
!== false && row
>= 0) {
1523 for (var i
in this.layout_
.datasets
) {
1524 if (row
< this.layout_
.datasets
[i
].length
) {
1525 var point
= this.layout_
.points
[pos
+row
];
1527 if (this.attr_("stackedGraph")) {
1528 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
1531 this.selPoints_
.push(point
);
1533 pos
+= this.layout_
.datasets
[i
].length
;
1537 if (this.selPoints_
.length
) {
1538 this.lastx_
= this.selPoints_
[0].xval
;
1539 this.updateSelection_();
1542 this.clearSelection();
1548 * The mouse has left the canvas. Clear out whatever artifacts remain
1549 * @param {Object} event the mouseout event from the browser.
1552 Dygraph
.prototype.mouseOut_
= function(event
) {
1553 if (this.attr_("unhighlightCallback")) {
1554 this.attr_("unhighlightCallback")(event
);
1557 if (this.attr_("hideOverlayOnMouseOut")) {
1558 this.clearSelection();
1563 * Remove all selection from the canvas
1566 Dygraph
.prototype.clearSelection
= function() {
1567 // Get rid of the overlay data
1568 var ctx
= this.canvas_
.getContext("2d");
1569 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1570 this.attr_("labelsDiv").innerHTML
= "";
1571 this.selPoints_
= [];
1576 * Returns the number of the currently selected row
1577 * @return int row number, of -1 if nothing is selected
1580 Dygraph
.prototype.getSelection
= function() {
1581 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1585 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
1586 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
1587 return row
+ this.boundaryIds_
[0][0];
1593 Dygraph
.zeropad
= function(x
) {
1594 if (x
< 10) return "0" + x
; else return "" + x
;
1598 * Return a string version of the hours, minutes and seconds portion of a date.
1599 * @param {Number} date The JavaScript date (ms since epoch)
1600 * @return {String} A time of the form "HH:MM:SS"
1603 Dygraph
.hmsString_
= function(date
) {
1604 var zeropad
= Dygraph
.zeropad
;
1605 var d
= new Date(date
);
1606 if (d
.getSeconds()) {
1607 return zeropad(d
.getHours()) + ":" +
1608 zeropad(d
.getMinutes()) + ":" +
1609 zeropad(d
.getSeconds());
1611 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
1616 * Convert a JS date to a string appropriate to display on an axis that
1617 * is displaying values at the stated granularity.
1618 * @param {Date} date The date to format
1619 * @param {Number} granularity One of the Dygraph granularity constants
1620 * @return {String} The formatted date
1623 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
1624 if (granularity
>= Dygraph
.DECADAL
) {
1625 return date
.strftime('%Y');
1626 } else if (granularity
>= Dygraph
.MONTHLY
) {
1627 return date
.strftime('%b %y');
1629 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
1630 if (frac
== 0 || granularity
>= Dygraph
.DAILY
) {
1631 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
1633 return Dygraph
.hmsString_(date
.getTime());
1639 * Convert a JS date (millis since epoch) to YYYY/MM/DD
1640 * @param {Number} date The JavaScript date (ms since epoch)
1641 * @return {String} A date of the form "YYYY/MM/DD"
1644 Dygraph
.dateString_
= function(date
) {
1645 var zeropad
= Dygraph
.zeropad
;
1646 var d
= new Date(date
);
1649 var year
= "" + d
.getFullYear();
1650 // Get a 0 padded month string
1651 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
1652 // Get a 0 padded day string
1653 var day
= zeropad(d
.getDate());
1656 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
1657 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
1659 return year
+ "/" + month + "/" + day
+ ret
;
1663 * Fires when there's data available to be graphed.
1664 * @param {String} data Raw CSV data to be plotted
1667 Dygraph
.prototype.loadedEvent_
= function(data
) {
1668 this.rawData_
= this.parseCSV_(data
);
1672 Dygraph
.prototype.months
= ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
1673 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1674 Dygraph
.prototype.quarters
= ["Jan", "Apr", "Jul", "Oct"];
1677 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1680 Dygraph
.prototype.addXTicks_
= function() {
1681 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1683 if (this.dateWindow_
) {
1684 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
1686 range
= [this.rawData_
[0][0], this.rawData_
[this.rawData_
.length
- 1][0]];
1689 var formatter
= this.attr_('xTicker');
1690 var ret
= formatter(range
[0], range
[1], this);
1693 if (ret
.ticks
!== undefined
) {
1694 // numericTicks() returns multiple values.
1696 this.numXDigits_
= ret
.numDigits
;
1701 this.layout_
.updateOptions({xTicks
: xTicks
});
1704 // Time granularity enumeration
1705 Dygraph
.SECONDLY
= 0;
1706 Dygraph
.TWO_SECONDLY
= 1;
1707 Dygraph
.FIVE_SECONDLY
= 2;
1708 Dygraph
.TEN_SECONDLY
= 3;
1709 Dygraph
.THIRTY_SECONDLY
= 4;
1710 Dygraph
.MINUTELY
= 5;
1711 Dygraph
.TWO_MINUTELY
= 6;
1712 Dygraph
.FIVE_MINUTELY
= 7;
1713 Dygraph
.TEN_MINUTELY
= 8;
1714 Dygraph
.THIRTY_MINUTELY
= 9;
1715 Dygraph
.HOURLY
= 10;
1716 Dygraph
.TWO_HOURLY
= 11;
1717 Dygraph
.SIX_HOURLY
= 12;
1719 Dygraph
.WEEKLY
= 14;
1720 Dygraph
.MONTHLY
= 15;
1721 Dygraph
.QUARTERLY
= 16;
1722 Dygraph
.BIANNUAL
= 17;
1723 Dygraph
.ANNUAL
= 18;
1724 Dygraph
.DECADAL
= 19;
1725 Dygraph
.CENTENNIAL
= 20;
1726 Dygraph
.NUM_GRANULARITIES
= 21;
1728 Dygraph
.SHORT_SPACINGS
= [];
1729 Dygraph
.SHORT_SPACINGS
[Dygraph
.SECONDLY
] = 1000 * 1;
1730 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_SECONDLY
] = 1000 * 2;
1731 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_SECONDLY
] = 1000 * 5;
1732 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_SECONDLY
] = 1000 * 10;
1733 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_SECONDLY
] = 1000 * 30;
1734 Dygraph
.SHORT_SPACINGS
[Dygraph
.MINUTELY
] = 1000 * 60;
1735 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_MINUTELY
] = 1000 * 60 * 2;
1736 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_MINUTELY
] = 1000 * 60 * 5;
1737 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_MINUTELY
] = 1000 * 60 * 10;
1738 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_MINUTELY
] = 1000 * 60 * 30;
1739 Dygraph
.SHORT_SPACINGS
[Dygraph
.HOURLY
] = 1000 * 3600;
1740 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_HOURLY
] = 1000 * 3600 * 2;
1741 Dygraph
.SHORT_SPACINGS
[Dygraph
.SIX_HOURLY
] = 1000 * 3600 * 6;
1742 Dygraph
.SHORT_SPACINGS
[Dygraph
.DAILY
] = 1000 * 86400;
1743 Dygraph
.SHORT_SPACINGS
[Dygraph
.WEEKLY
] = 1000 * 604800;
1747 // If we used this time granularity, how many ticks would there be?
1748 // This is only an approximation, but it's generally good enough.
1750 Dygraph
.prototype.NumXTicks
= function(start_time
, end_time
, granularity
) {
1751 if (granularity
< Dygraph
.MONTHLY
) {
1752 // Generate one tick mark for every fixed interval of time.
1753 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
1754 return Math
.floor(0.5 + 1.0 * (end_time
- start_time
) / spacing
);
1756 var year_mod
= 1; // e.g. to only print one point every 10 years.
1757 var num_months
= 12;
1758 if (granularity
== Dygraph
.QUARTERLY
) num_months
= 3;
1759 if (granularity
== Dygraph
.BIANNUAL
) num_months
= 2;
1760 if (granularity
== Dygraph
.ANNUAL
) num_months
= 1;
1761 if (granularity
== Dygraph
.DECADAL
) { num_months
= 1; year_mod
= 10; }
1762 if (granularity
== Dygraph
.CENTENNIAL
) { num_months
= 1; year_mod
= 100; }
1764 var msInYear
= 365.2524 * 24 * 3600 * 1000;
1765 var num_years
= 1.0 * (end_time
- start_time
) / msInYear
;
1766 return Math
.floor(0.5 + 1.0 * num_years
* num_months
/ year_mod
);
1772 // Construct an x-axis of nicely-formatted times on meaningful boundaries
1773 // (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1775 // Returns an array containing {v: millis, label: label} dictionaries.
1777 Dygraph
.prototype.GetXAxis
= function(start_time
, end_time
, granularity
) {
1778 var formatter
= this.attr_("xAxisLabelFormatter");
1780 if (granularity
< Dygraph
.MONTHLY
) {
1781 // Generate one tick mark for every fixed interval of time.
1782 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
1783 var format
= '%d%b'; // e.g. "1Jan"
1785 // Find a time less than start_time which occurs on a "nice" time boundary
1786 // for this granularity.
1787 var g
= spacing
/ 1000;
1788 var d
= new Date(start_time
);
1789 if (g
<= 60) { // seconds
1790 var x
= d
.getSeconds(); d
.setSeconds(x
- x
% g
);
1794 if (g
<= 60) { // minutes
1795 var x
= d
.getMinutes(); d
.setMinutes(x
- x
% g
);
1800 if (g
<= 24) { // days
1801 var x
= d
.getHours(); d
.setHours(x
- x
% g
);
1806 if (g
== 7) { // one week
1807 d
.setDate(d
.getDate() - d
.getDay());
1812 start_time
= d
.getTime();
1814 for (var t
= start_time
; t
<= end_time
; t
+= spacing
) {
1815 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
1818 // Display a tick mark on the first of a set of months of each year.
1819 // Years get a tick mark iff y % year_mod == 0. This is useful for
1820 // displaying a tick mark once every 10 years, say, on long time scales.
1822 var year_mod
= 1; // e.g. to only print one point every 10 years.
1824 if (granularity
== Dygraph
.MONTHLY
) {
1825 months
= [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
1826 } else if (granularity
== Dygraph
.QUARTERLY
) {
1827 months
= [ 0, 3, 6, 9 ];
1828 } else if (granularity
== Dygraph
.BIANNUAL
) {
1830 } else if (granularity
== Dygraph
.ANNUAL
) {
1832 } else if (granularity
== Dygraph
.DECADAL
) {
1835 } else if (granularity
== Dygraph
.CENTENNIAL
) {
1839 this.warn("Span of dates is too long");
1842 var start_year
= new Date(start_time
).getFullYear();
1843 var end_year
= new Date(end_time
).getFullYear();
1844 var zeropad
= Dygraph
.zeropad
;
1845 for (var i
= start_year
; i
<= end_year
; i
++) {
1846 if (i
% year_mod
!= 0) continue;
1847 for (var j
= 0; j
< months
.length
; j
++) {
1848 var date_str
= i
+ "/" + zeropad(1 + months[j]) + "/01";
1849 var t
= Date
.parse(date_str
);
1850 if (t
< start_time
|| t
> end_time
) continue;
1851 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
1861 * Add ticks to the x-axis based on a date range.
1862 * @param {Number} startDate Start of the date window (millis since epoch)
1863 * @param {Number} endDate End of the date window (millis since epoch)
1864 * @return {Array.<Object>} Array of {label, value} tuples.
1867 Dygraph
.dateTicker
= function(startDate
, endDate
, self
) {
1869 for (var i
= 0; i
< Dygraph
.NUM_GRANULARITIES
; i
++) {
1870 var num_ticks
= self
.NumXTicks(startDate
, endDate
, i
);
1871 if (self
.width_
/ num_ticks
>= self
.attr_('pixelsPerXLabel')) {
1878 return self
.GetXAxis(startDate
, endDate
, chosen
);
1880 // TODO(danvk): signal error.
1885 * Determine the number of significant figures in a Number up to the specified
1886 * precision. Note that there is no way to determine if a trailing '0' is
1887 * significant or not, so by convention we return 1 for all of the following
1888 * inputs: 1, 1.0, 1.00, 1.000 etc.
1889 * @param {Number} x The input value.
1890 * @param {Number} opt_maxPrecision Optional maximum precision to consider.
1891 * Default and maximum allowed value is 13.
1892 * @return {Number} The number of significant figures which is >= 1.
1894 Dygraph
.significantFigures
= function(x
, opt_maxPrecision
) {
1895 var precision
= Math
.max(opt_maxPrecision
|| 13, 13);
1897 // Convert the number to its exponential notation form and work backwards,
1898 // ignoring the 'e+xx' bit. This may seem like a hack, but doing a loop and
1899 // dividing by 10 leads to roundoff errors. By using toExponential(), we let
1900 // the JavaScript interpreter handle the low level bits of the Number for us.
1901 var s
= x
.toExponential(precision
);
1902 var ePos
= s
.lastIndexOf('e'); // -1 case handled by return below.
1904 for (var i
= ePos
- 1; i
>= 0; i
--) {
1906 // Got to the decimal place. We'll call this 1 digit of precision because
1907 // we can't know for sure how many trailing 0s are significant.
1909 } else if (s
[i
] != '0') {
1910 // Found the first non-zero digit. Return the number of characters
1911 // except for the '.'.
1912 return i
; // This is i - 1 + 1 (-1 is for '.', +1 is for 0 based index).
1916 // Occurs if toExponential() doesn't return a string containing 'e', which
1917 // should never happen.
1922 * Add ticks when the x axis has numbers on it (instead of dates)
1923 * @param {Number} startDate Start of the date window (millis since epoch)
1924 * @param {Number} endDate End of the date window (millis since epoch)
1926 * @param {function} attribute accessor function.
1927 * @return {Array.<Object>} Array of {label, value} tuples.
1930 Dygraph
.numericTicks
= function(minV
, maxV
, self
, axis_props
, vals
) {
1931 var attr
= function(k
) {
1932 if (axis_props
&& axis_props
.hasOwnProperty(k
)) return axis_props
[k
];
1933 return self
.attr_(k
);
1938 for (var i
= 0; i
< vals
.length
; i
++) {
1939 ticks
[i
].push({v
: vals
[i
]});
1943 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
1944 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks
).
1945 // The first spacing greater than pixelsPerYLabel is what we use.
1946 // TODO(danvk): version that works on a log scale.
1947 if (attr("labelsKMG2")) {
1948 var mults
= [1, 2, 4, 8];
1950 var mults
= [1, 2, 5];
1952 var scale
, low_val
, high_val
, nTicks
;
1953 // TODO(danvk): make it possible to set this for x- and y-axes independently.
1954 var pixelsPerTick
= attr('pixelsPerYLabel');
1955 for (var i
= -10; i
< 50; i
++) {
1956 if (attr("labelsKMG2")) {
1957 var base_scale
= Math
.pow(16, i
);
1959 var base_scale
= Math
.pow(10, i
);
1961 for (var j
= 0; j
< mults
.length
; j
++) {
1962 scale
= base_scale
* mults
[j
];
1963 low_val
= Math
.floor(minV
/ scale
) * scale
;
1964 high_val
= Math
.ceil(maxV
/ scale
) * scale
;
1965 nTicks
= Math
.abs(high_val
- low_val
) / scale
;
1966 var spacing
= self
.height_
/ nTicks
;
1967 // wish I could break out of both loops at once...
1968 if (spacing
> pixelsPerTick
) break;
1970 if (spacing
> pixelsPerTick
) break;
1973 // Construct the set of ticks.
1974 // Allow reverse y-axis if it's explicitly requested.
1975 if (low_val
> high_val
) scale
*= -1;
1976 for (var i
= 0; i
< nTicks
; i
++) {
1977 var tickV
= low_val
+ i
* scale
;
1978 ticks
.push( {v
: tickV
} );
1982 // Add formatted labels to the ticks.
1985 if (attr("labelsKMB")) {
1987 k_labels
= [ "K", "M", "B", "T" ];
1989 if (attr("labelsKMG2")) {
1990 if (k
) self
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1992 k_labels
= [ "k", "M", "G", "T" ];
1994 var formatter
= attr('yAxisLabelFormatter') ?
1995 attr('yAxisLabelFormatter') : attr('yValueFormatter');
1997 // Determine the number of decimal places needed for the labels below by
1998 // taking the maximum number of significant figures for any label. We must
1999 // take the max because we can't tell if trailing 0s are significant.
2001 for (var i
= 0; i
< ticks
.length
; i
++) {
2002 numDigits
= Math
.max(Dygraph
.significantFigures(ticks
[i
].v
), numDigits
);
2005 for (var i
= 0; i
< ticks
.length
; i
++) {
2006 var tickV
= ticks
[i
].v
;
2007 var absTickV
= Math
.abs(tickV
);
2008 var label
= (formatter
!== undefined
) ?
2009 formatter(tickV
, numDigits
) : tickV
.toPrecision(numDigits
);
2010 if (k_labels
.length
> 0) {
2011 // Round up to an appropriate unit.
2013 for (var j
= 3; j
>= 0; j
--, n
/= k
) {
2014 if (absTickV
>= n
) {
2015 label
= (tickV
/ n
).toPrecision(numDigits
) + k_labels
[j
];
2020 ticks
[i
].label
= label
;
2022 return {ticks
: ticks
, numDigits
: numDigits
};
2025 // Computes the range of the data series (including confidence intervals).
2026 // series is either [ [x1, y1], [x2, y2], ... ] or
2027 // [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2028 // Returns [low, high]
2029 Dygraph
.prototype.extremeValues_
= function(series
) {
2030 var minY
= null, maxY
= null;
2032 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2034 // With custom bars, maxY is the max of the high values.
2035 for (var j
= 0; j
< series
.length
; j
++) {
2036 var y
= series
[j
][1][0];
2038 var low
= y
- series
[j
][1][1];
2039 var high
= y
+ series
[j
][1][2];
2040 if (low
> y
) low
= y
; // this can happen with custom bars,
2041 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2042 if (maxY
== null || high
> maxY
) {
2045 if (minY
== null || low
< minY
) {
2050 for (var j
= 0; j
< series
.length
; j
++) {
2051 var y
= series
[j
][1];
2052 if (y
=== null || isNaN(y
)) continue;
2053 if (maxY
== null || y
> maxY
) {
2056 if (minY
== null || y
< minY
) {
2062 return [minY
, maxY
];
2066 * This function is called once when the chart's data is changed or the options
2067 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2068 * idea is that values derived from the chart's data can be computed here,
2069 * rather than every time the chart is drawn. This includes things like the
2070 * number of axes, rolling averages, etc.
2072 Dygraph
.prototype.predraw_
= function() {
2073 // TODO(danvk): move more computations out of drawGraph_ and into here.
2074 this.computeYAxes_();
2076 // Create a new plotter.
2077 if (this.plotter_
) this.plotter_
.clear();
2078 this.plotter_
= new DygraphCanvasRenderer(this,
2079 this.hidden_
, this.layout_
,
2080 this.renderOptions_
);
2082 // The roller sits in the bottom left corner of the chart. We don't know where
2083 // this will be until the options are available, so it's positioned here.
2084 this.createRollInterface_();
2086 // Same thing applies for the labelsDiv. It's right edge should be flush with
2087 // the right edge of the charting area (which may not be the same as the right
2088 // edge of the div, if we have two y-axes.
2089 this.positionLabelsDiv_();
2091 // If the data or options have changed, then we'd better redraw.
2097 * Update the graph with new data. This method is called when the viewing area
2098 * has changed. If the underlying data or options have changed, predraw_ will
2099 * be called before drawGraph_ is called.
2102 Dygraph
.prototype.drawGraph_
= function() {
2103 var data
= this.rawData_
;
2105 // This is used to set the second parameter to drawCallback, below.
2106 var is_initial_draw
= this.is_initial_draw_
;
2107 this.is_initial_draw_
= false;
2109 var minY
= null, maxY
= null;
2110 this.layout_
.removeAllDatasets();
2112 this.attrs_
['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
2114 // Loop over the fields (series). Go from the last to the first,
2115 // because if they're stacked that's how we accumulate the values.
2117 var cumulative_y
= []; // For stacked series.
2120 var extremes
= {}; // series name -> [low, high]
2122 // Loop over all fields and create datasets
2123 for (var i
= data
[0].length
- 1; i
>= 1; i
--) {
2124 if (!this.visibility()[i
- 1]) continue;
2126 var seriesName
= this.attr_("labels")[i
];
2127 var connectSeparatedPoints
= this.attr_('connectSeparatedPoints', i
);
2130 for (var j
= 0; j
< data
.length
; j
++) {
2131 if (data
[j
][i
] != null || !connectSeparatedPoints
) {
2132 var date
= data
[j
][0];
2133 series
.push([date
, data
[j
][i
]]);
2137 // TODO(danvk): move this into predraw_. It's insane to do it here.
2138 series
= this.rollingAverage(series
, this.rollPeriod_
);
2140 // Prune down to the desired range, if necessary (for zooming)
2141 // Because there can be lines going to points outside of the visible area,
2142 // we actually prune to visible points, plus one on either side.
2143 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2144 if (this.dateWindow_
) {
2145 var low
= this.dateWindow_
[0];
2146 var high
= this.dateWindow_
[1];
2148 // TODO(danvk): do binary search instead of linear search.
2149 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2150 var firstIdx
= null, lastIdx
= null;
2151 for (var k
= 0; k
< series
.length
; k
++) {
2152 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2155 if (series
[k
][0] <= high
) {
2159 if (firstIdx
=== null) firstIdx
= 0;
2160 if (firstIdx
> 0) firstIdx
--;
2161 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2162 if (lastIdx
< series
.length
- 1) lastIdx
++;
2163 this.boundaryIds_
[i
-1] = [firstIdx
, lastIdx
];
2164 for (var k
= firstIdx
; k
<= lastIdx
; k
++) {
2165 pruned
.push(series
[k
]);
2169 this.boundaryIds_
[i
-1] = [0, series
.length
-1];
2172 var seriesExtremes
= this.extremeValues_(series
);
2175 for (var j
=0; j
<series
.length
; j
++) {
2176 val
= [series
[j
][0], series
[j
][1][0], series
[j
][1][1], series
[j
][1][2]];
2179 } else if (this.attr_("stackedGraph")) {
2180 var l
= series
.length
;
2182 for (var j
= 0; j
< l
; j
++) {
2183 // If one data set has a NaN, let all subsequent stacked
2184 // sets inherit the NaN -- only start at 0 for the first set.
2185 var x
= series
[j
][0];
2186 if (cumulative_y
[x
] === undefined
) {
2187 cumulative_y
[x
] = 0;
2190 actual_y
= series
[j
][1];
2191 cumulative_y
[x
] += actual_y
;
2193 series
[j
] = [x
, cumulative_y
[x
]]
2195 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2196 seriesExtremes
[1] = cumulative_y
[x
];
2198 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2199 seriesExtremes
[0] = cumulative_y
[x
];
2203 extremes
[seriesName
] = seriesExtremes
;
2205 datasets
[i
] = series
;
2208 for (var i
= 1; i
< datasets
.length
; i
++) {
2209 if (!this.visibility()[i
- 1]) continue;
2210 this.layout_
.addDataset(this.attr_("labels")[i
], datasets
[i
]);
2213 this.computeYAxisRanges_(extremes
);
2214 this.layout_
.updateOptions( { yAxes
: this.axes_
,
2215 seriesToAxisMap
: this.seriesToAxisMap_
2220 // Tell PlotKit to use this new data and render itself
2221 this.layout_
.updateOptions({dateWindow
: this.dateWindow_
});
2222 this.layout_
.evaluateWithError();
2223 this.plotter_
.clear();
2224 this.plotter_
.render();
2225 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2226 this.canvas_
.height
);
2228 if (this.attr_("drawCallback") !== null) {
2229 this.attr_("drawCallback")(this, is_initial_draw
);
2234 * Determine properties of the y-axes which are independent of the data
2235 * currently being displayed. This includes things like the number of axes and
2236 * the style of the axes. It does not include the range of each axis and its
2238 * This fills in this.axes_ and this.seriesToAxisMap_.
2239 * axes_ = [ { options } ]
2240 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2241 * indices are into the axes_ array.
2243 Dygraph
.prototype.computeYAxes_
= function() {
2244 this.axes_
= [{}]; // always have at least one y-axis.
2245 this.seriesToAxisMap_
= {};
2247 // Get a list of series names.
2248 var labels
= this.attr_("labels");
2250 for (var i
= 1; i
< labels
.length
; i
++) series
[labels
[i
]] = (i
- 1);
2252 // all options which could be applied per-axis:
2260 'axisLabelFontSize',
2264 // Copy global axis options over to the first axis.
2265 for (var i
= 0; i
< axisOptions
.length
; i
++) {
2266 var k
= axisOptions
[i
];
2267 var v
= this.attr_(k
);
2268 if (v
) this.axes_
[0][k
] = v
;
2271 // Go through once and add all the axes.
2272 for (var seriesName
in series
) {
2273 if (!series
.hasOwnProperty(seriesName
)) continue;
2274 var axis
= this.attr_("axis", seriesName
);
2276 this.seriesToAxisMap_
[seriesName
] = 0;
2279 if (typeof(axis
) == 'object') {
2280 // Add a new axis, making a copy of its per-axis options.
2282 Dygraph
.update(opts
, this.axes_
[0]);
2283 Dygraph
.update(opts
, { valueRange
: null }); // shouldn't inherit this.
2284 Dygraph
.update(opts
, axis
);
2285 this.axes_
.push(opts
);
2286 this.seriesToAxisMap_
[seriesName
] = this.axes_
.length
- 1;
2290 // Go through one more time and assign series to an axis defined by another
2291 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2292 for (var seriesName
in series
) {
2293 if (!series
.hasOwnProperty(seriesName
)) continue;
2294 var axis
= this.attr_("axis", seriesName
);
2295 if (typeof(axis
) == 'string') {
2296 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
2297 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
2298 "series " + axis
+ ", which does not define its own axis.");
2301 var idx
= this.seriesToAxisMap_
[axis
];
2302 this.seriesToAxisMap_
[seriesName
] = idx
;
2306 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2307 // this last so that hiding the first series doesn't destroy the axis
2308 // properties of the primary axis.
2309 var seriesToAxisFiltered
= {};
2310 var vis
= this.visibility();
2311 for (var i
= 1; i
< labels
.length
; i
++) {
2313 if (vis
[i
- 1]) seriesToAxisFiltered
[s
] = this.seriesToAxisMap_
[s
];
2315 this.seriesToAxisMap_
= seriesToAxisFiltered
;
2319 * Returns the number of y-axes on the chart.
2320 * @return {Number} the number of axes.
2322 Dygraph
.prototype.numAxes
= function() {
2324 for (var series
in this.seriesToAxisMap_
) {
2325 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2326 var idx
= this.seriesToAxisMap_
[series
];
2327 if (idx
> last_axis
) last_axis
= idx
;
2329 return 1 + last_axis
;
2333 * Determine the value range and tick marks for each axis.
2334 * @param {Object} extremes A mapping from seriesName -> [low, high]
2335 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2337 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2338 // Build a map from axis number -> [list of series names]
2339 var seriesForAxis
= [];
2340 for (var series
in this.seriesToAxisMap_
) {
2341 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2342 var idx
= this.seriesToAxisMap_
[series
];
2343 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2344 seriesForAxis
[idx
].push(series
);
2347 // Compute extreme values, a span and tick marks for each axis.
2348 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2349 var axis
= this.axes_
[i
];
2350 if (axis
.valueWindow
) {
2351 // This is only set if the user has zoomed on the y-axis. It is never set
2352 // by a user. It takes precedence over axis.valueRange because, if you set
2353 // valueRange, you'd still expect to be able to pan.
2354 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2355 } else if (axis
.valueRange
) {
2356 // This is a user-set value range for this axis.
2357 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
2359 // Calculate the extremes of extremes.
2360 var series
= seriesForAxis
[i
];
2361 var minY
= Infinity
; // extremes[series[0]][0];
2362 var maxY
= -Infinity
; // extremes[series[0]][1];
2363 for (var j
= 0; j
< series
.length
; j
++) {
2364 minY
= Math
.min(extremes
[series
[j
]][0], minY
);
2365 maxY
= Math
.max(extremes
[series
[j
]][1], maxY
);
2367 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2369 // Add some padding and round up to an integer to be human-friendly.
2370 var span
= maxY
- minY
;
2371 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2372 if (span
== 0) { span
= maxY
; }
2373 var maxAxisY
= maxY
+ 0.1 * span
;
2374 var minAxisY
= minY
- 0.1 * span
;
2376 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2377 if (!this.attr_("avoidMinZero")) {
2378 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2379 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2382 if (this.attr_("includeZero")) {
2383 if (maxY
< 0) maxAxisY
= 0;
2384 if (minY
> 0) minAxisY
= 0;
2387 axis
.computedValueRange
= [minAxisY
, maxAxisY
];
2390 // Add ticks. By default, all axes inherit the tick positions of the
2391 // primary axis. However, if an axis is specifically marked as having
2392 // independent ticks, then that is permissible as well.
2393 if (i
== 0 || axis
.independentTicks
) {
2395 Dygraph
.numericTicks(axis
.computedValueRange
[0],
2396 axis
.computedValueRange
[1],
2399 axis
.ticks
= ret
.ticks
;
2400 this.numYDigits_
= ret
.numDigits
;
2402 var p_axis
= this.axes_
[0];
2403 var p_ticks
= p_axis
.ticks
;
2404 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2405 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2406 var tick_values
= [];
2407 for (var i
= 0; i
< p_ticks
.length
; i
++) {
2408 var y_frac
= (p_ticks
[i
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2409 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2410 tick_values
.push(y_val
);
2414 Dygraph
.numericTicks(axis
.computedValueRange
[0],
2415 axis
.computedValueRange
[1],
2416 this, axis
, tick_values
);
2417 axis
.ticks
= ret
.ticks
;
2418 this.numYDigits_
= ret
.numDigits
;
2424 * Calculates the rolling average of a data set.
2425 * If originalData is [label, val], rolls the average of those.
2426 * If originalData is [label, [, it's interpreted as [value, stddev]
2427 * and the roll is returned in the same form, with appropriately reduced
2428 * stddev for each value.
2429 * Note that this is where fractional input (i.e. '5/10') is converted into
2431 * @param {Array} originalData The data in the appropriate format (see above)
2432 * @param {Number} rollPeriod The number of points over which to average the
2435 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2436 if (originalData
.length
< 2)
2437 return originalData
;
2438 var rollPeriod
= Math
.min(rollPeriod
, originalData
.length
- 1);
2439 var rollingData
= [];
2440 var sigma
= this.attr_("sigma");
2442 if (this.fractions_
) {
2444 var den
= 0; // numerator/denominator
2446 for (var i
= 0; i
< originalData
.length
; i
++) {
2447 num
+= originalData
[i
][1][0];
2448 den
+= originalData
[i
][1][1];
2449 if (i
- rollPeriod
>= 0) {
2450 num
-= originalData
[i
- rollPeriod
][1][0];
2451 den
-= originalData
[i
- rollPeriod
][1][1];
2454 var date
= originalData
[i
][0];
2455 var value
= den
? num
/ den
: 0.0;
2456 if (this.attr_("errorBars")) {
2457 if (this.wilsonInterval_
) {
2458 // For more details on this confidence interval, see:
2459 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2461 var p
= value
< 0 ? 0 : value
, n
= den
;
2462 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2463 var denom
= 1 + sigma
* sigma
/ den
;
2464 var low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2465 var high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2466 rollingData
[i
] = [date
,
2467 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2469 rollingData
[i
] = [date
, [0, 0, 0]];
2472 var stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2473 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2476 rollingData
[i
] = [date
, mult
* value
];
2479 } else if (this.attr_("customBars")) {
2484 for (var i
= 0; i
< originalData
.length
; i
++) {
2485 var data
= originalData
[i
][1];
2487 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2489 if (y
!= null && !isNaN(y
)) {
2495 if (i
- rollPeriod
>= 0) {
2496 var prev
= originalData
[i
- rollPeriod
];
2497 if (prev
[1][1] != null && !isNaN(prev
[1][1])) {
2504 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2505 1.0 * (mid
- low
) / count
,
2506 1.0 * (high
- mid
) / count
]];
2509 // Calculate the rolling average for the first rollPeriod - 1 points where
2510 // there is not enough data to roll over the full number of points
2511 var num_init_points
= Math
.min(rollPeriod
- 1, originalData
.length
- 2);
2512 if (!this.attr_("errorBars")){
2513 if (rollPeriod
== 1) {
2514 return originalData
;
2517 for (var i
= 0; i
< originalData
.length
; i
++) {
2520 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2521 var y
= originalData
[j
][1];
2522 if (y
== null || isNaN(y
)) continue;
2524 sum
+= originalData
[j
][1];
2527 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2529 rollingData
[i
] = [originalData
[i
][0], null];
2534 for (var i
= 0; i
< originalData
.length
; i
++) {
2538 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2539 var y
= originalData
[j
][1][0];
2540 if (y
== null || isNaN(y
)) continue;
2542 sum
+= originalData
[j
][1][0];
2543 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2546 var stddev
= Math
.sqrt(variance
) / num_ok
;
2547 rollingData
[i
] = [originalData
[i
][0],
2548 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2550 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2560 * Parses a date, returning the number of milliseconds since epoch. This can be
2561 * passed in as an xValueParser in the Dygraph constructor.
2562 * TODO(danvk): enumerate formats that this understands.
2563 * @param {String} A date in YYYYMMDD format.
2564 * @return {Number} Milliseconds since epoch.
2567 Dygraph
.dateParser
= function(dateStr
, self
) {
2570 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
2571 dateStrSlashed
= dateStr
.replace("-", "/", "g");
2572 while (dateStrSlashed
.search("-") != -1) {
2573 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
2575 d
= Date
.parse(dateStrSlashed
);
2576 } else if (dateStr
.length
== 8) { // e.g. '20090712'
2577 // TODO(danvk): remove support for this format. It's confusing.
2578 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr
.substr(4,2)
2579 + "/" + dateStr
.substr(6,2);
2580 d
= Date
.parse(dateStrSlashed
);
2582 // Any format that Date.parse will accept, e.g. "2009/07/12" or
2583 // "2009/07/12 12:34:56"
2584 d
= Date
.parse(dateStr
);
2587 if (!d
|| isNaN(d
)) {
2588 self
.error("Couldn't parse " + dateStr
+ " as a date");
2594 * Detects the type of the str (date or numeric) and sets the various
2595 * formatting attributes in this.attrs_ based on this type.
2596 * @param {String} str An x value.
2599 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2601 if (str
.indexOf('-') >= 0 ||
2602 str
.indexOf('/') >= 0 ||
2603 isNaN(parseFloat(str
))) {
2605 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2606 // TODO(danvk): remove support for this format.
2611 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
2612 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2613 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
2614 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2616 this.attrs_
.xValueFormatter
= this.attrs_
.xValueFormatter
;
2617 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2618 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2619 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
2624 * Parses a string in a special csv format. We expect a csv file where each
2625 * line is a date point, and the first field in each line is the date string.
2626 * We also expect that all remaining fields represent series.
2627 * if the errorBars attribute is set, then interpret the fields as:
2628 * date, series1, stddev1, series2, stddev2, ...
2629 * @param {Array.<Object>} data See above.
2632 * @return Array.<Object> An array with one entry for each row. These entries
2633 * are an array of cells in that row. The first entry is the parsed x-value for
2634 * the row. The second, third, etc. are the y-values. These can take on one of
2635 * three forms, depending on the CSV and constructor parameters:
2637 * 2. [ value, stddev ]
2638 * 3. [ low value, center value, high value ]
2640 Dygraph
.prototype.parseCSV_
= function(data
) {
2642 var lines
= data
.split("\n");
2644 // Use the default delimiter or fall back to a tab if that makes sense.
2645 var delim
= this.attr_('delimiter');
2646 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2651 if (this.labelsFromCSV_
) {
2653 this.attrs_
.labels
= lines
[0].split(delim
);
2656 // Parse the x as a float or return null if it's not a number.
2657 var parseFloatOrNull
= function(x
) {
2658 var val
= parseFloat(x
);
2659 // isFinite() returns false for NaN and +/-Infinity
.
2660 return isFinite(val
) ? val
: null;
2664 var defaultParserSet
= false; // attempt to auto-detect x value type
2665 var expectedCols
= this.attr_("labels").length
;
2666 var outOfOrder
= false;
2667 for (var i
= start
; i
< lines
.length
; i
++) {
2668 var line
= lines
[i
];
2669 if (line
.length
== 0) continue; // skip blank lines
2670 if (line
[0] == '#') continue; // skip comment lines
2671 var inFields
= line
.split(delim
);
2672 if (inFields
.length
< 2) continue;
2675 if (!defaultParserSet
) {
2676 this.detectTypeFromString_(inFields
[0]);
2677 xParser
= this.attr_("xValueParser");
2678 defaultParserSet
= true;
2680 fields
[0] = xParser(inFields
[0], this);
2682 // If fractions are expected, parse the numbers as "A/B
"
2683 if (this.fractions_) {
2684 for (var j = 1; j < inFields.length; j++) {
2685 // TODO(danvk): figure out an appropriate way to flag parse errors.
2686 var vals = inFields[j].split("/");
2687 fields[j] = [parseFloatOrNull(vals[0]), parseFloatOrNull(vals[1])];
2689 } else if (this.attr_("errorBars
")) {
2690 // If there are error bars, values are (value, stddev) pairs
2691 for (var j = 1; j < inFields.length; j += 2)
2692 fields[(j + 1) / 2] = [parseFloatOrNull(inFields[j]),
2693 parseFloatOrNull(inFields[j + 1])];
2694 } else if (this.attr_("customBars
")) {
2695 // Bars are a low;center;high tuple
2696 for (var j = 1; j < inFields.length; j++) {
2697 var vals = inFields[j].split(";");
2698 fields[j] = [ parseFloatOrNull(vals[0]),
2699 parseFloatOrNull(vals[1]),
2700 parseFloatOrNull(vals[2]) ];
2703 // Values are just numbers
2704 for (var j = 1; j < inFields.length; j++) {
2705 fields[j] = parseFloatOrNull(inFields[j]);
2708 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2713 if (fields.length != expectedCols) {
2714 this.error("Number of columns
in line
" + i + " (" + fields.length +
2715 ") does not agree
with number of
labels (" + expectedCols +
2721 this.warn("CSV is out of order
; order it correctly to speed loading
.");
2722 ret.sort(function(a,b) { return a[0] - b[0] });
2729 * The user has provided their data as a pre-packaged JS array. If the x values
2730 * are numeric, this is the same as dygraphs' internal format. If the x values
2731 * are dates, we need to convert them from Date objects to ms since epoch.
2732 * @param {Array.<Object>} data
2733 * @return {Array.<Object>} data with numeric x values.
2735 Dygraph.prototype.parseArray_ = function(data) {
2736 // Peek at the first x value to see if it's numeric.
2737 if (data.length == 0) {
2738 this.error("Can
't plot empty data set");
2741 if (data[0].length == 0) {
2742 this.error("Data set cannot contain an empty row");
2746 if (this.attr_("labels") == null) {
2747 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
2748 "in the options parameter");
2749 this.attrs_.labels = [ "X" ];
2750 for (var i = 1; i < data[0].length; i++) {
2751 this.attrs_.labels.push("Y" + i);
2755 if (Dygraph.isDateLike(data[0][0])) {
2756 // Some intelligent defaults for a date x-axis.
2757 this.attrs_.xValueFormatter = Dygraph.dateString_;
2758 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
2759 this.attrs_.xTicker = Dygraph.dateTicker;
2761 // Assume they're all dates
.
2762 var parsedData
= Dygraph
.clone(data
);
2763 for (var i
= 0; i
< data
.length
; i
++) {
2764 if (parsedData
[i
].length
== 0) {
2765 this.error("Row " + (1 + i
) + " of data is empty");
2768 if (parsedData
[i
][0] == null
2769 || typeof(parsedData
[i
][0].getTime
) != 'function'
2770 || isNaN(parsedData
[i
][0].getTime())) {
2771 this.error("x value in row " + (1 + i
) + " is not a Date");
2774 parsedData
[i
][0] = parsedData
[i
][0].getTime();
2778 // Some intelligent defaults for a numeric x-axis.
2779 this.attrs_
.xValueFormatter
= this.attrs_
.yValueFormatter
;
2780 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2786 * Parses a DataTable object from gviz.
2787 * The data is expected to have a first column that is either a date or a
2788 * number. All subsequent columns must be numbers. If there is a clear mismatch
2789 * between this.xValueParser_ and the type of the first column, it will be
2790 * fixed. Fills out rawData_.
2791 * @param {Array.<Object>} data See above.
2794 Dygraph
.prototype.parseDataTable_
= function(data
) {
2795 var cols
= data
.getNumberOfColumns();
2796 var rows
= data
.getNumberOfRows();
2798 var indepType
= data
.getColumnType(0);
2799 if (indepType
== 'date' || indepType
== 'datetime') {
2800 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
2801 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2802 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
2803 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2804 } else if (indepType
== 'number') {
2805 this.attrs_
.xValueFormatter
= this.attrs_
.yValueFormatter
;
2806 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2807 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2808 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
2810 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2811 "column 1 of DataTable input (Got '" + indepType
+ "')");
2815 // Array of the column indices which contain data (and not annotations).
2817 var annotationCols
= {}; // data index -> [annotation cols]
2818 var hasAnnotations
= false;
2819 for (var i
= 1; i
< cols
; i
++) {
2820 var type
= data
.getColumnType(i
);
2821 if (type
== 'number') {
2823 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
2824 // This is OK -- it's an annotation column.
2825 var dataIdx
= colIdx
[colIdx
.length
- 1];
2826 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
2827 annotationCols
[dataIdx
] = [i
];
2829 annotationCols
[dataIdx
].push(i
);
2831 hasAnnotations
= true;
2833 this.error("Only 'number' is supported as a dependent type with Gviz." +
2834 " 'string' is only supported if displayAnnotations is true");
2838 // Read column labels
2839 // TODO(danvk): add support back for errorBars
2840 var labels
= [data
.getColumnLabel(0)];
2841 for (var i
= 0; i
< colIdx
.length
; i
++) {
2842 labels
.push(data
.getColumnLabel(colIdx
[i
]));
2843 if (this.attr_("errorBars")) i
+= 1;
2845 this.attrs_
.labels
= labels
;
2846 cols
= labels
.length
;
2849 var outOfOrder
= false;
2850 var annotations
= [];
2851 for (var i
= 0; i
< rows
; i
++) {
2853 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
2854 data
.getValue(i
, 0) === null) {
2855 this.warn("Ignoring row " + i
+
2856 " of DataTable because of undefined or null first column.");
2860 if (indepType
== 'date' || indepType
== 'datetime') {
2861 row
.push(data
.getValue(i
, 0).getTime());
2863 row
.push(data
.getValue(i
, 0));
2865 if (!this.attr_("errorBars")) {
2866 for (var j
= 0; j
< colIdx
.length
; j
++) {
2867 var col
= colIdx
[j
];
2868 row
.push(data
.getValue(i
, col
));
2869 if (hasAnnotations
&&
2870 annotationCols
.hasOwnProperty(col
) &&
2871 data
.getValue(i
, annotationCols
[col
][0]) != null) {
2873 ann
.series
= data
.getColumnLabel(col
);
2875 ann
.shortText
= String
.fromCharCode(65 /* A */ + annotations
.length
)
2877 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
2878 if (k
) ann
.text
+= "\n";
2879 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
2881 annotations
.push(ann
);
2885 for (var j
= 0; j
< cols
- 1; j
++) {
2886 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
2889 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
2893 // Strip out infinities, which give dygraphs problems later on.
2894 for (var j
= 0; j
< row
.length
; j
++) {
2895 if (!isFinite(row
[j
])) row
[j
] = null;
2901 this.warn("DataTable is out of order; order it correctly to speed loading.");
2902 ret
.sort(function(a
,b
) { return a
[0] - b
[0] });
2904 this.rawData_
= ret
;
2906 if (annotations
.length
> 0) {
2907 this.setAnnotations(annotations
, true);
2911 // These functions are all based on MochiKit.
2912 Dygraph
.update
= function (self
, o
) {
2913 if (typeof(o
) != 'undefined' && o
!== null) {
2915 if (o
.hasOwnProperty(k
)) {
2923 Dygraph
.isArrayLike
= function (o
) {
2924 var typ
= typeof(o
);
2926 (typ
!= 'object' && !(typ
== 'function' &&
2927 typeof(o
.item
) == 'function')) ||
2929 typeof(o
.length
) != 'number' ||
2937 Dygraph
.isDateLike
= function (o
) {
2938 if (typeof(o
) != "object" || o
=== null ||
2939 typeof(o
.getTime
) != 'function') {
2945 Dygraph
.clone
= function(o
) {
2946 // TODO(danvk): figure out how MochiKit's version works
2948 for (var i
= 0; i
< o
.length
; i
++) {
2949 if (Dygraph
.isArrayLike(o
[i
])) {
2950 r
.push(Dygraph
.clone(o
[i
]));
2960 * Get the CSV data. If it's in a function, call that function. If it's in a
2961 * file, do an XMLHttpRequest to get it.
2964 Dygraph
.prototype.start_
= function() {
2965 if (typeof this.file_
== 'function') {
2966 // CSV string. Pretend we got it via XHR.
2967 this.loadedEvent_(this.file_());
2968 } else if (Dygraph
.isArrayLike(this.file_
)) {
2969 this.rawData_
= this.parseArray_(this.file_
);
2971 } else if (typeof this.file_
== 'object' &&
2972 typeof this.file_
.getColumnRange
== 'function') {
2973 // must be a DataTable from gviz.
2974 this.parseDataTable_(this.file_
);
2976 } else if (typeof this.file_
== 'string') {
2977 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2978 if (this.file_
.indexOf('\n') >= 0) {
2979 this.loadedEvent_(this.file_
);
2981 var req
= new XMLHttpRequest();
2983 req
.onreadystatechange
= function () {
2984 if (req
.readyState
== 4) {
2985 if (req
.status
== 200) {
2986 caller
.loadedEvent_(req
.responseText
);
2991 req
.open("GET", this.file_
, true);
2995 this.error("Unknown data format: " + (typeof this.file_
));
3000 * Changes various properties of the graph. These can include:
3002 * <li>file: changes the source data for the graph</li>
3003 * <li>errorBars: changes whether the data contains stddev</li>
3005 * @param {Object} attrs The new properties and values
3007 Dygraph
.prototype.updateOptions
= function(attrs
) {
3008 // TODO(danvk): this is a mess. Rethink this function.
3009 if ('rollPeriod' in attrs
) {
3010 this.rollPeriod_
= attrs
.rollPeriod
;
3012 if ('dateWindow' in attrs
) {
3013 this.dateWindow_
= attrs
.dateWindow
;
3016 // TODO(danvk): validate per-series options.
3021 // highlightCircleSize
3023 Dygraph
.update(this.user_attrs_
, attrs
);
3024 Dygraph
.update(this.renderOptions_
, attrs
);
3026 this.labelsFromCSV_
= (this.attr_("labels") == null);
3028 // TODO(danvk): this doesn't match the constructor logic
3029 this.layout_
.updateOptions({ 'errorBars': this.attr_("errorBars") });
3030 if (attrs
['file']) {
3031 this.file_
= attrs
['file'];
3039 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3040 * containing div (which has presumably changed size since the dygraph was
3041 * instantiated. If the width/height are specified, the div will be resized.
3043 * This is far more efficient than destroying and re-instantiating a
3044 * Dygraph, since it doesn't have to reparse the underlying data.
3046 * @param {Number} width Width (in pixels)
3047 * @param {Number} height Height (in pixels)
3049 Dygraph
.prototype.resize
= function(width
, height
) {
3050 if (this.resize_lock
) {
3053 this.resize_lock
= true;
3055 if ((width
=== null) != (height
=== null)) {
3056 this.warn("Dygraph.resize() should be called with zero parameters or " +
3057 "two non-NULL parameters. Pretending it was zero.");
3058 width
= height
= null;
3061 // TODO(danvk): there should be a clear() method.
3062 this.maindiv_
.innerHTML
= "";
3063 this.attrs_
.labelsDiv
= null;
3066 this.maindiv_
.style
.width
= width
+ "px";
3067 this.maindiv_
.style
.height
= height
+ "px";
3068 this.width_
= width
;
3069 this.height_
= height
;
3071 this.width_
= this.maindiv_
.offsetWidth
;
3072 this.height_
= this.maindiv_
.offsetHeight
;
3075 this.createInterface_();
3078 this.resize_lock
= false;
3082 * Adjusts the number of points in the rolling average. Updates the graph to
3083 * reflect the new averaging period.
3084 * @param {Number} length Number of points over which to average the data.
3086 Dygraph
.prototype.adjustRoll
= function(length
) {
3087 this.rollPeriod_
= length
;
3092 * Returns a boolean array of visibility statuses.
3094 Dygraph
.prototype.visibility
= function() {
3095 // Do lazy-initialization, so that this happens after we know the number of
3097 if (!this.attr_("visibility")) {
3098 this.attrs_
["visibility"] = [];
3100 while (this.attr_("visibility").length
< this.rawData_
[0].length
- 1) {
3101 this.attr_("visibility").push(true);
3103 return this.attr_("visibility");
3107 * Changes the visiblity of a series.
3109 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3110 var x
= this.visibility();
3111 if (num
< 0 || num
>= x
.length
) {
3112 this.warn("invalid series number in setVisibility: " + num
);
3120 * Update the list of annotations and redraw the chart.
3122 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3123 // Only add the annotation CSS rule once we know it will be used.
3124 Dygraph
.addAnnotationRule();
3125 this.annotations_
= ann
;
3126 this.layout_
.setAnnotations(this.annotations_
);
3127 if (!suppressDraw
) {
3133 * Return the list of annotations.
3135 Dygraph
.prototype.annotations
= function() {
3136 return this.annotations_
;
3140 * Get the index of a series (column) given its name. The first column is the
3141 * x-axis, so the data series start with index 1.
3143 Dygraph
.prototype.indexFromSetName
= function(name
) {
3144 var labels
= this.attr_("labels");
3145 for (var i
= 0; i
< labels
.length
; i
++) {
3146 if (labels
[i
] == name
) return i
;
3151 Dygraph
.addAnnotationRule
= function() {
3152 if (Dygraph
.addedAnnotationCSS
) return;
3154 var rule
= "border: 1px solid black; " +
3155 "background-color: white; " +
3156 "text-align: center;";
3158 var styleSheetElement
= document
.createElement("style");
3159 styleSheetElement
.type
= "text/css";
3160 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3162 // Find the first style sheet that we can access.
3163 // We may not add a rule to a style sheet from another domain for security
3164 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3165 // adds its own style sheets from google.com.
3166 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3167 if (document
.styleSheets
[i
].disabled
) continue;
3168 var mysheet
= document
.styleSheets
[i
];
3170 if (mysheet
.insertRule
) { // Firefox
3171 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3172 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3173 } else if (mysheet
.addRule
) { // IE
3174 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3176 Dygraph
.addedAnnotationCSS
= true;
3179 // Was likely a security exception.
3183 this.warn("Unable to add default annotation CSS rule; display may be off.");
3187 * Create a new canvas element. This is more complex than a simple
3188 * document.createElement("canvas") because of IE and excanvas.
3190 Dygraph
.createCanvas
= function() {
3191 var canvas
= document
.createElement("canvas");
3193 isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
3194 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
3195 canvas
= G_vmlCanvasManager
.initElement(canvas
);
3203 * A wrapper around Dygraph that implements the gviz API.
3204 * @param {Object} container The DOM object the visualization should live in.
3206 Dygraph
.GVizChart
= function(container
) {
3207 this.container
= container
;
3210 Dygraph
.GVizChart
.prototype.draw
= function(data
, options
) {
3211 // Clear out any existing dygraph.
3212 // TODO(danvk): would it make more sense to simply redraw using the current
3213 // date_graph object?
3214 this.container
.innerHTML
= '';
3215 if (typeof(this.date_graph
) != 'undefined') {
3216 this.date_graph
.destroy();
3219 this.date_graph
= new Dygraph(this.container
, data
, options
);
3223 * Google charts compatible setSelection
3224 * Only row selection is supported, all points in the row will be highlighted
3225 * @param {Array} array of the selected cells
3228 Dygraph
.GVizChart
.prototype.setSelection
= function(selection_array
) {
3230 if (selection_array
.length
) {
3231 row
= selection_array
[0].row
;
3233 this.date_graph
.setSelection(row
);
3237 * Google charts compatible getSelection implementation
3238 * @return {Array} array of the selected cells
3241 Dygraph
.GVizChart
.prototype.getSelection
= function() {
3244 var row
= this.date_graph
.getSelection();
3246 if (row
< 0) return selection
;
3249 for (var i
in this.date_graph
.layout_
.datasets
) {
3250 selection
.push({row
: row
, column
: col
});
3257 // Older pages may still use this name.
3258 DateGraph
= Dygraph
;