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
: function(x
, opt_precision
) {
153 var s
= Dygraph
.floatFormat(x
, opt_precision
);
154 var s2
= Dygraph
.intFormat(x
);
155 return s
.length
<= s2
.length
? s
: s2
;
161 axisLabelFontSize
: 14,
164 xAxisLabelFormatter
: Dygraph
.dateAxisFormatter
,
168 xValueFormatter
: Dygraph
.dateString_
,
169 xValueParser
: Dygraph
.dateParser
,
170 xTicker
: Dygraph
.dateTicker
,
178 wilsonInterval
: true, // only relevant if fractions is true
182 connectSeparatedPoints
: false,
185 hideOverlayOnMouseOut
: true,
190 interactionModel
: null // will be set to Dygraph.defaultInteractionModel.
193 // Various logging levels.
199 // Directions for panning and zooming. Use bit operations when combined
200 // values are possible.
201 Dygraph
.HORIZONTAL
= 1;
202 Dygraph
.VERTICAL
= 2;
204 // Used for initializing annotation CSS rules only once.
205 Dygraph
.addedAnnotationCSS
= false;
207 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
208 // Labels is no longer a constructor parameter, since it's typically set
209 // directly from the data source. It also conains a name for the x-axis,
210 // which the previous constructor form did not.
211 if (labels
!= null) {
212 var new_labels
= ["Date"];
213 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
214 Dygraph
.update(attrs
, { 'labels': new_labels
});
216 this.__init__(div
, file
, attrs
);
220 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
221 * and context <canvas> inside of it. See the constructor for details
223 * @param {Element} div the Element to render the graph into.
224 * @param {String | Function} file Source data
225 * @param {Object} attrs Miscellaneous other options
228 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
229 // Hack for IE: if we're using excanvas and the document hasn't finished
230 // loading yet (and hence may not have initialized whatever it needs to
231 // initialize), then keep calling this routine periodically until it has.
232 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
233 typeof(G_vmlCanvasManager
) != 'undefined' &&
234 document
.readyState
!= 'complete') {
236 setTimeout(function() { self
.__init__(div
, file
, attrs
) }, 100);
239 // Support two-argument constructor
240 if (attrs
== null) { attrs
= {}; }
242 // Copy the important bits into the object
243 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
246 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
247 this.previousVerticalX_
= -1;
248 this.fractions_
= attrs
.fractions
|| false;
249 this.dateWindow_
= attrs
.dateWindow
|| null;
251 this.wilsonInterval_
= attrs
.wilsonInterval
|| true;
252 this.is_initial_draw_
= true;
253 this.annotations_
= [];
255 // Number of digits to use when labeling the x (if numeric) and y axis
257 this.numXDigits_
= 2;
258 this.numYDigits_
= 2;
260 // When labeling x (if numeric) or y values in the legend, there are
261 // numDigits + numExtraDigits of precision used. For axes labels with N
262 // digits of precision, the data should be displayed with at least N+1 digits
263 // of precision. The reason for this is to divide each interval between
264 // successive ticks into tenths (for 1) or hundredths (for 2), etc. For
265 // example, if the labels are [0, 1, 2], we want data to be displayed as
267 this.numExtraDigits_
= 1;
269 // Clear the div. This ensure that, if multiple dygraphs are passed the same
270 // div, then only one will be drawn.
273 // If the div isn't already sized then inherit from our attrs or
274 // give it a default size.
275 if (div
.style
.width
== '') {
276 div
.style
.width
= (attrs
.width
|| Dygraph
.DEFAULT_WIDTH
) + "px";
278 if (div
.style
.height
== '') {
279 div
.style
.height
= (attrs
.height
|| Dygraph
.DEFAULT_HEIGHT
) + "px";
281 this.width_
= parseInt(div
.style
.width
, 10);
282 this.height_
= parseInt(div
.style
.height
, 10);
283 // The div might have been specified as percent of the current window size,
284 // convert that to an appropriate number of pixels.
285 if (div
.style
.width
.indexOf("%") == div
.style
.width
.length
- 1) {
286 this.width_
= div
.offsetWidth
;
288 if (div
.style
.height
.indexOf("%") == div
.style
.height
.length
- 1) {
289 this.height_
= div
.offsetHeight
;
292 if (this.width_
== 0) {
293 this.error("dygraph has zero width. Please specify a width in pixels.");
295 if (this.height_
== 0) {
296 this.error("dygraph has zero height. Please specify a height in pixels.");
299 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
300 if (attrs
['stackedGraph']) {
301 attrs
['fillGraph'] = true;
302 // TODO(nikhilk): Add any other stackedGraph checks here.
305 // Dygraphs has many options, some of which interact with one another.
306 // To keep track of everything, we maintain two sets of options:
308 // this.user_attrs_ only options explicitly set by the user.
309 // this.attrs_ defaults, options derived from user_attrs_, data.
311 // Options are then accessed this.attr_('attr'), which first looks at
312 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
313 // defaults without overriding behavior that the user specifically asks for.
314 this.user_attrs_
= {};
315 Dygraph
.update(this.user_attrs_
, attrs
);
318 Dygraph
.update(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
320 this.boundaryIds_
= [];
322 // Make a note of whether labels will be pulled from the CSV file.
323 this.labelsFromCSV_
= (this.attr_("labels") == null);
325 // Create the containing DIV and other interactive elements
326 this.createInterface_();
331 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
333 typeof(this.user_attrs_
[seriesName
]) != 'undefined' &&
334 this.user_attrs_
[seriesName
] != null &&
335 typeof(this.user_attrs_
[seriesName
][name
]) != 'undefined') {
336 return this.user_attrs_
[seriesName
][name
];
337 } else if (typeof(this.user_attrs_
[name
]) != 'undefined') {
338 return this.user_attrs_
[name
];
339 } else if (typeof(this.attrs_
[name
]) != 'undefined') {
340 return this.attrs_
[name
];
346 // TODO(danvk): any way I can get the line numbers to be this.warn call?
347 Dygraph
.prototype.log
= function(severity
, message
) {
348 if (typeof(console
) != 'undefined') {
351 console
.debug('dygraphs: ' + message
);
354 console
.info('dygraphs: ' + message
);
356 case Dygraph
.WARNING
:
357 console
.warn('dygraphs: ' + message
);
360 console
.error('dygraphs: ' + message
);
365 Dygraph
.prototype.info
= function(message
) {
366 this.log(Dygraph
.INFO
, message
);
368 Dygraph
.prototype.warn
= function(message
) {
369 this.log(Dygraph
.WARNING
, message
);
371 Dygraph
.prototype.error
= function(message
) {
372 this.log(Dygraph
.ERROR
, message
);
376 * Returns the current rolling period, as set by the user or an option.
377 * @return {Number} The number of points in the rolling window
379 Dygraph
.prototype.rollPeriod
= function() {
380 return this.rollPeriod_
;
384 * Returns the currently-visible x-range. This can be affected by zooming,
385 * panning or a call to updateOptions.
386 * Returns a two-element array: [left, right].
387 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
389 Dygraph
.prototype.xAxisRange
= function() {
390 if (this.dateWindow_
) return this.dateWindow_
;
392 // The entire chart is visible.
393 var left
= this.rawData_
[0][0];
394 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
395 return [left
, right
];
399 * Returns the currently-visible y-range for an axis. This can be affected by
400 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
401 * called with no arguments, returns the range of the first axis.
402 * Returns a two-element array: [bottom, top].
404 Dygraph
.prototype.yAxisRange
= function(idx
) {
405 if (typeof(idx
) == "undefined") idx
= 0;
406 if (idx
< 0 || idx
>= this.axes_
.length
) return null;
407 return [ this.axes_
[idx
].computedValueRange
[0],
408 this.axes_
[idx
].computedValueRange
[1] ];
412 * Returns the currently-visible y-ranges for each axis. This can be affected by
413 * zooming, panning, calls to updateOptions, etc.
414 * Returns an array of [bottom, top] pairs, one for each y-axis.
416 Dygraph
.prototype.yAxisRanges
= function() {
418 for (var i
= 0; i
< this.axes_
.length
; i
++) {
419 ret
.push(this.yAxisRange(i
));
424 // TODO(danvk): use these functions throughout dygraphs.
426 * Convert from data coordinates to canvas/div X/Y coordinates.
427 * If specified, do this conversion for the coordinate system of a particular
428 * axis. Uses the first axis by default.
429 * Returns a two-element array: [X, Y]
431 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
432 var ret
= [null, null];
433 var area
= this.plotter_
.area
;
435 var xRange
= this.xAxisRange();
436 ret
[0] = area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
440 var yRange
= this.yAxisRange(axis
);
441 ret
[1] = area
.y
+ (yRange
[1] - y
) / (yRange
[1] - yRange
[0]) * area
.h
;
448 * Convert from canvas/div coords to data coordinates.
449 * If specified, do this conversion for the coordinate system of a particular
450 * axis. Uses the first axis by default.
451 * Returns a two-element array: [X, Y]
453 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
454 var ret
= [null, null];
455 var area
= this.plotter_
.area
;
457 var xRange
= this.xAxisRange();
458 ret
[0] = xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
462 var yRange
= this.yAxisRange(axis
);
463 ret
[1] = yRange
[0] + (area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
470 * Returns the number of columns (including the independent variable).
472 Dygraph
.prototype.numColumns
= function() {
473 return this.rawData_
[0].length
;
477 * Returns the number of rows (excluding any header/label row).
479 Dygraph
.prototype.numRows
= function() {
480 return this.rawData_
.length
;
484 * Returns the value in the given row and column. If the row and column exceed
485 * the bounds on the data, returns null. Also returns null if the value is
488 Dygraph
.prototype.getValue
= function(row
, col
) {
489 if (row
< 0 || row
> this.rawData_
.length
) return null;
490 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
492 return this.rawData_
[row
][col
];
495 Dygraph
.addEvent
= function(el
, evt
, fn
) {
496 var normed_fn
= function(e
) {
497 if (!e
) var e
= window
.event
;
500 if (window
.addEventListener
) { // Mozilla, Netscape, Firefox
501 el
.addEventListener(evt
, normed_fn
, false);
503 el
.attachEvent('on' + evt
, normed_fn
);
508 // Based on the article at
509 // http://www.switchonthecode.com/tutorials
/javascript
-tutorial
-the
-scroll
-wheel
510 Dygraph
.cancelEvent
= function(e
) {
511 e
= e
? e
: window
.event
;
512 if (e
.stopPropagation
) {
515 if (e
.preventDefault
) {
518 e
.cancelBubble
= true;
520 e
.returnValue
= false;
526 * Generates interface elements for the Dygraph: a containing div, a div to
527 * display the current point, and a textbox to adjust the rolling average
528 * period. Also creates the Renderer/Layout elements.
531 Dygraph
.prototype.createInterface_
= function() {
532 // Create the all-enclosing graph div
533 var enclosing
= this.maindiv_
;
535 this.graphDiv
= document
.createElement("div");
536 this.graphDiv
.style
.width
= this.width_
+ "px";
537 this.graphDiv
.style
.height
= this.height_
+ "px";
538 enclosing
.appendChild(this.graphDiv
);
540 // Create the canvas for interactive parts of the chart.
541 this.canvas_
= Dygraph
.createCanvas();
542 this.canvas_
.style
.position
= "absolute";
543 this.canvas_
.width
= this.width_
;
544 this.canvas_
.height
= this.height_
;
545 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
546 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
548 // ... and for static parts of the chart.
549 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
551 // The interactive parts of the graph are drawn on top of the chart.
552 this.graphDiv
.appendChild(this.hidden_
);
553 this.graphDiv
.appendChild(this.canvas_
);
554 this.mouseEventElement_
= this.canvas_
;
557 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', function(e
) {
558 dygraph
.mouseMove_(e
);
560 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', function(e
) {
561 dygraph
.mouseOut_(e
);
564 // Create the grapher
565 // TODO(danvk): why does the Layout need its own set of options?
566 this.layoutOptions_
= { 'xOriginIsZero': false };
567 Dygraph
.update(this.layoutOptions_
, this.attrs_
);
568 Dygraph
.update(this.layoutOptions_
, this.user_attrs_
);
569 Dygraph
.update(this.layoutOptions_
, {
570 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
572 this.layout_
= new DygraphLayout(this, this.layoutOptions_
);
574 // TODO(danvk): why does the Renderer need its own set of options?
575 this.renderOptions_
= { colorScheme
: this.colors_
,
577 axisLineWidth
: Dygraph
.AXIS_LINE_WIDTH
};
578 Dygraph
.update(this.renderOptions_
, this.attrs_
);
579 Dygraph
.update(this.renderOptions_
, this.user_attrs_
);
581 this.createStatusMessage_();
582 this.createDragInterface_();
586 * Detach DOM elements in the dygraph and null out all data references.
587 * Calling this when you're done with a dygraph can dramatically reduce memory
588 * usage. See, e.g., the tests/perf.html example.
590 Dygraph
.prototype.destroy
= function() {
591 var removeRecursive
= function(node
) {
592 while (node
.hasChildNodes()) {
593 removeRecursive(node
.firstChild
);
594 node
.removeChild(node
.firstChild
);
597 removeRecursive(this.maindiv_
);
599 var nullOut
= function(obj
) {
601 if (typeof(obj
[n
]) === 'object') {
607 // These may not all be necessary, but it can't hurt...
608 nullOut(this.layout_
);
609 nullOut(this.plotter_
);
614 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
615 * this particular canvas. All Dygraph work is done on this.canvas_.
616 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
617 * @return {Object} The newly-created canvas
620 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
621 var h
= Dygraph
.createCanvas();
622 h
.style
.position
= "absolute";
623 // TODO(danvk): h should be offset from canvas. canvas needs to include
624 // some extra area to make it easier to zoom in on the far left and far
625 // right. h needs to be precisely the plot area, so that clipping occurs.
626 h
.style
.top
= canvas
.style
.top
;
627 h
.style
.left
= canvas
.style
.left
;
628 h
.width
= this.width_
;
629 h
.height
= this.height_
;
630 h
.style
.width
= this.width_
+ "px"; // for IE
631 h
.style
.height
= this.height_
+ "px"; // for IE
635 // Taken from MochiKit.Color
636 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
640 if (saturation
=== 0) {
645 var i
= Math
.floor(hue
* 6);
646 var f
= (hue
* 6) - i
;
647 var p
= value
* (1 - saturation
);
648 var q
= value
* (1 - (saturation
* f
));
649 var t
= value
* (1 - (saturation
* (1 - f
)));
651 case 1: red
= q
; green
= value
; blue
= p
; break;
652 case 2: red
= p
; green
= value
; blue
= t
; break;
653 case 3: red
= p
; green
= q
; blue
= value
; break;
654 case 4: red
= t
; green
= p
; blue
= value
; break;
655 case 5: red
= value
; green
= p
; blue
= q
; break;
656 case 6: // fall through
657 case 0: red
= value
; green
= t
; blue
= p
; break;
660 red
= Math
.floor(255 * red
+ 0.5);
661 green
= Math
.floor(255 * green
+ 0.5);
662 blue
= Math
.floor(255 * blue
+ 0.5);
663 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
668 * Generate a set of distinct colors for the data series. This is done with a
669 * color wheel. Saturation/Value are customizable, and the hue is
670 * equally-spaced around the color wheel. If a custom set of colors is
671 * specified, that is used instead.
674 Dygraph
.prototype.setColors_
= function() {
675 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
676 // away with this.renderOptions_.
677 var num
= this.attr_("labels").length
- 1;
679 var colors
= this.attr_('colors');
681 var sat
= this.attr_('colorSaturation') || 1.0;
682 var val
= this.attr_('colorValue') || 0.5;
683 var half
= Math
.ceil(num
/ 2);
684 for (var i
= 1; i
<= num
; i
++) {
685 if (!this.visibility()[i
-1]) continue;
686 // alternate colors for high contrast.
687 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
688 var hue
= (1.0 * idx
/ (1 + num
));
689 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
692 for (var i
= 0; i
< num
; i
++) {
693 if (!this.visibility()[i
]) continue;
694 var colorStr
= colors
[i
% colors
.length
];
695 this.colors_
.push(colorStr
);
699 // TODO(danvk): update this w/r
/t/ the
new options system
.
700 this.renderOptions_
.colorScheme
= this.colors_
;
701 Dygraph
.update(this.plotter_
.options
, this.renderOptions_
);
702 Dygraph
.update(this.layoutOptions_
, this.user_attrs_
);
703 Dygraph
.update(this.layoutOptions_
, this.attrs_
);
707 * Return the list of colors. This is either the list of colors passed in the
708 * attributes, or the autogenerated list of rgb(r,g,b) strings.
709 * @return {Array<string>} The list of colors.
711 Dygraph
.prototype.getColors
= function() {
715 // The following functions are from quirksmode.org with a modification for Safari from
716 // http://blog.firetree.net/2005/07/04/javascript-find-position/
717 // http://www.quirksmode.org/js
/findpos
.html
718 Dygraph
.findPosX
= function(obj
) {
723 curleft
+= obj
.offsetLeft
;
724 if(!obj
.offsetParent
)
726 obj
= obj
.offsetParent
;
733 Dygraph
.findPosY
= function(obj
) {
738 curtop
+= obj
.offsetTop
;
739 if(!obj
.offsetParent
)
741 obj
= obj
.offsetParent
;
751 * Create the div that contains information on the selected point(s)
752 * This goes in the top right of the canvas, unless an external div has already
756 Dygraph
.prototype.createStatusMessage_
= function() {
757 var userLabelsDiv
= this.user_attrs_
["labelsDiv"];
758 if (userLabelsDiv
&& null != userLabelsDiv
759 && (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
)) {
760 this.user_attrs_
["labelsDiv"] = document
.getElementById(userLabelsDiv
);
762 if (!this.attr_("labelsDiv")) {
763 var divWidth
= this.attr_('labelsDivWidth');
765 "position": "absolute",
768 "width": divWidth
+ "px",
770 "left": (this.width_
- divWidth
- 2) + "px",
771 "background": "white",
773 "overflow": "hidden"};
774 Dygraph
.update(messagestyle
, this.attr_('labelsDivStyles'));
775 var div
= document
.createElement("div");
776 for (var name
in messagestyle
) {
777 if (messagestyle
.hasOwnProperty(name
)) {
778 div
.style
[name
] = messagestyle
[name
];
781 this.graphDiv
.appendChild(div
);
782 this.attrs_
.labelsDiv
= div
;
787 * Position the labels div so that its right edge is flush with the right edge
788 * of the charting area.
790 Dygraph
.prototype.positionLabelsDiv_
= function() {
791 // Don't touch a user-specified labelsDiv.
792 if (this.user_attrs_
.hasOwnProperty("labelsDiv")) return;
794 var area
= this.plotter_
.area
;
795 var div
= this.attr_("labelsDiv");
796 div
.style
.left
= area
.x
+ area
.w
- this.attr_("labelsDivWidth") - 1 + "px";
800 * Create the text box to adjust the averaging period
803 Dygraph
.prototype.createRollInterface_
= function() {
804 // Create a roller if one doesn't exist already.
806 this.roller_
= document
.createElement("input");
807 this.roller_
.type
= "text";
808 this.roller_
.style
.display
= "none";
809 this.graphDiv
.appendChild(this.roller_
);
812 var display
= this.attr_('showRoller') ? 'block' : 'none';
814 var textAttr
= { "position": "absolute",
816 "top": (this.plotter_
.area
.h
- 25) + "px",
817 "left": (this.plotter_
.area
.x
+ 1) + "px",
820 this.roller_
.size
= "2";
821 this.roller_
.value
= this.rollPeriod_
;
822 for (var name
in textAttr
) {
823 if (textAttr
.hasOwnProperty(name
)) {
824 this.roller_
.style
[name
] = textAttr
[name
];
829 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
832 // These functions are taken from MochiKit.Signal
833 Dygraph
.pageX
= function(e
) {
835 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
838 var b
= document
.body
;
840 (de
.scrollLeft
|| b
.scrollLeft
) -
841 (de
.clientLeft
|| 0);
845 Dygraph
.pageY
= function(e
) {
847 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
850 var b
= document
.body
;
852 (de
.scrollTop
|| b
.scrollTop
) -
857 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
858 return Dygraph
.pageX(e
) - context
.px
861 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
862 return Dygraph
.pageY(e
) - context
.py
865 // Called in response to an interaction model operation that
866 // should start the default panning behavior.
868 // It's used in the default callback for "mousedown" operations.
869 // Custom interaction model builders can use it to provide the default
872 Dygraph
.startPan
= function(event
, g
, context
) {
873 // have to be zoomed in to pan.
874 // TODO(konigsberg): Let's loosen this zoom-to-pan restriction, also
875 // perhaps create panning boundaries? A more flexible pan would make it,
876 // ahem, 'pan-useful'.
878 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
879 if (g
.axes_
[i
].valueWindow
|| g
.axes_
[i
].valueRange
) {
884 if (!g
.dateWindow_
&& !zoomedY
) return;
886 context
.isPanning
= true;
887 var xRange
= g
.xAxisRange();
888 context
.dateRange
= xRange
[1] - xRange
[0];
890 // Record the range of each y-axis at the start of the drag.
891 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
892 context
.is2DPan
= false;
893 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
894 var axis
= g
.axes_
[i
];
895 var yRange
= g
.yAxisRange(i
);
896 axis
.dragValueRange
= yRange
[1] - yRange
[0];
897 var r
= g
.toDataCoords(null, context
.dragStartY
, i
);
898 axis
.draggingValue
= r
[1];
899 if (axis
.valueWindow
|| axis
.valueRange
) context
.is2DPan
= true;
902 // TODO(konigsberg): Switch from all this math to toDataCoords?
903 // Seems to work for the dragging value.
904 context
.draggingDate
= (context
.dragStartX
/ g
.width_
) * context
.dateRange
+ xRange
[0];
907 // Called in response to an interaction model operation that
908 // responds to an event that pans the view.
910 // It's used in the default callback for "mousemove" operations.
911 // Custom interaction model builders can use it to provide the default
914 Dygraph
.movePan
= function(event
, g
, context
) {
915 context
.dragEndX
= g
.dragGetX_(event
, context
);
916 context
.dragEndY
= g
.dragGetY_(event
, context
);
918 // TODO(danvk): update this comment
919 // Want to have it so that:
920 // 1. draggingDate appears at dragEndX, draggingValue appears at dragEndY.
921 // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
922 // 3. draggingValue appears at dragEndY.
923 // 4. valueRange is unaltered.
925 var minDate
= context
.draggingDate
- (context
.dragEndX
/ g
.width_
) * context
.dateRange
;
926 var maxDate
= minDate
+ context
.dateRange
;
927 g
.dateWindow_
= [minDate
, maxDate
];
929 // y-axis scaling is automatic unless this is a full 2D pan.
930 if (context
.is2DPan
) {
931 // Adjust each axis appropriately.
932 var y_frac
= context
.dragEndY
/ g
.height_
;
933 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
934 var axis
= g
.axes_
[i
];
935 var maxValue
= axis
.draggingValue
+ y_frac
* axis
.dragValueRange
;
936 var minValue
= maxValue
- axis
.dragValueRange
;
937 axis
.valueWindow
= [ minValue
, maxValue
];
944 // Called in response to an interaction model operation that
945 // responds to an event that ends panning.
947 // It's used in the default callback for "mouseup" operations.
948 // Custom interaction model builders can use it to provide the default
951 Dygraph
.endPan
= function(event
, g
, context
) {
952 context
.isPanning
= false;
953 context
.is2DPan
= false;
954 context
.draggingDate
= null;
955 context
.dateRange
= null;
956 context
.valueRange
= null;
959 // Called in response to an interaction model operation that
960 // responds to an event that starts zooming.
962 // It's used in the default callback for "mousedown" operations.
963 // Custom interaction model builders can use it to provide the default
966 Dygraph
.startZoom
= function(event
, g
, context
) {
967 context
.isZooming
= true;
970 // Called in response to an interaction model operation that
971 // responds to an event that defines zoom boundaries.
973 // It's used in the default callback for "mousemove" operations.
974 // Custom interaction model builders can use it to provide the default
977 Dygraph
.moveZoom
= function(event
, g
, context
) {
978 context
.dragEndX
= g
.dragGetX_(event
, context
);
979 context
.dragEndY
= g
.dragGetY_(event
, context
);
981 var xDelta
= Math
.abs(context
.dragStartX
- context
.dragEndX
);
982 var yDelta
= Math
.abs(context
.dragStartY
- context
.dragEndY
);
984 // drag direction threshold for y axis is twice as large as x axis
985 context
.dragDirection
= (xDelta
< yDelta
/ 2) ? Dygraph
.VERTICAL
: Dygraph
.HORIZONTAL
;
988 context
.dragDirection
,
993 context
.prevDragDirection
,
997 context
.prevEndX
= context
.dragEndX
;
998 context
.prevEndY
= context
.dragEndY
;
999 context
.prevDragDirection
= context
.dragDirection
;
1002 // Called in response to an interaction model operation that
1003 // responds to an event that performs a zoom based on previously defined
1006 // It's used in the default callback for "mouseup" operations.
1007 // Custom interaction model builders can use it to provide the default
1008 // zooming behavior.
1010 Dygraph
.endZoom
= function(event
, g
, context
) {
1011 context
.isZooming
= false;
1012 context
.dragEndX
= g
.dragGetX_(event
, context
);
1013 context
.dragEndY
= g
.dragGetY_(event
, context
);
1014 var regionWidth
= Math
.abs(context
.dragEndX
- context
.dragStartX
);
1015 var regionHeight
= Math
.abs(context
.dragEndY
- context
.dragStartY
);
1017 if (regionWidth
< 2 && regionHeight
< 2 &&
1018 g
.lastx_
!= undefined
&& g
.lastx_
!= -1) {
1019 // TODO(danvk): pass along more info about the points, e.g. 'x'
1020 if (g
.attr_('clickCallback') != null) {
1021 g
.attr_('clickCallback')(event
, g
.lastx_
, g
.selPoints_
);
1023 if (g
.attr_('pointClickCallback')) {
1024 // check if the click was on a particular point.
1025 var closestIdx
= -1;
1026 var closestDistance
= 0;
1027 for (var i
= 0; i
< g
.selPoints_
.length
; i
++) {
1028 var p
= g
.selPoints_
[i
];
1029 var distance
= Math
.pow(p
.canvasx
- context
.dragEndX
, 2) +
1030 Math
.pow(p
.canvasy
- context
.dragEndY
, 2);
1031 if (closestIdx
== -1 || distance
< closestDistance
) {
1032 closestDistance
= distance
;
1037 // Allow any click within two pixels of the dot.
1038 var radius
= g
.attr_('highlightCircleSize') + 2;
1039 if (closestDistance
<= 5 * 5) {
1040 g
.attr_('pointClickCallback')(event
, g
.selPoints_
[closestIdx
]);
1045 if (regionWidth
>= 10 && context
.dragDirection
== Dygraph
.HORIZONTAL
) {
1046 g
.doZoomX_(Math
.min(context
.dragStartX
, context
.dragEndX
),
1047 Math
.max(context
.dragStartX
, context
.dragEndX
));
1048 } else if (regionHeight
>= 10 && context
.dragDirection
== Dygraph
.VERTICAL
) {
1049 g
.doZoomY_(Math
.min(context
.dragStartY
, context
.dragEndY
),
1050 Math
.max(context
.dragStartY
, context
.dragEndY
));
1052 g
.canvas_
.getContext("2d").clearRect(0, 0,
1056 context
.dragStartX
= null;
1057 context
.dragStartY
= null;
1060 Dygraph
.defaultInteractionModel
= {
1061 // Track the beginning of drag events
1062 mousedown
: function(event
, g
, context
) {
1063 context
.initializeMouseDown(event
, g
, context
);
1065 if (event
.altKey
|| event
.shiftKey
) {
1066 Dygraph
.startPan(event
, g
, context
);
1068 Dygraph
.startZoom(event
, g
, context
);
1072 // Draw zoom rectangles when the mouse is down and the user moves around
1073 mousemove
: function(event
, g
, context
) {
1074 if (context
.isZooming
) {
1075 Dygraph
.moveZoom(event
, g
, context
);
1076 } else if (context
.isPanning
) {
1077 Dygraph
.movePan(event
, g
, context
);
1081 mouseup
: function(event
, g
, context
) {
1082 if (context
.isZooming
) {
1083 Dygraph
.endZoom(event
, g
, context
);
1084 } else if (context
.isPanning
) {
1085 Dygraph
.endPan(event
, g
, context
);
1089 // Temporarily cancel the dragging event when the mouse leaves the graph
1090 mouseout
: function(event
, g
, context
) {
1091 if (context
.isZooming
) {
1092 context
.dragEndX
= null;
1093 context
.dragEndY
= null;
1097 // Disable zooming out if panning.
1098 dblclick
: function(event
, g
, context
) {
1099 if (event
.altKey
|| event
.shiftKey
) {
1102 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1103 // friendlier to public use.
1108 Dygraph
.DEFAULT_ATTRS
.interactionModel
= Dygraph
.defaultInteractionModel
;
1111 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1115 Dygraph
.prototype.createDragInterface_
= function() {
1117 // Tracks whether the mouse is down right now
1119 isPanning
: false, // is this drag part of a pan?
1120 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1125 dragDirection
: null,
1128 prevDragDirection
: null,
1130 // TODO(danvk): update this comment
1131 // draggingDate and draggingValue represent the [date,value] point on the
1132 // graph at which the mouse was pressed. As the mouse moves while panning,
1133 // the viewport must pan so that the mouse position points to
1134 // [draggingDate, draggingValue]
1137 // TODO(danvk): update this comment
1138 // The range in second/value units that the viewport encompasses during a
1139 // panning operation.
1142 // Utility function to convert page-wide coordinates to canvas coords
1146 initializeMouseDown
: function(event
, g
, context
) {
1147 // prevents mouse drags from selecting page text.
1148 if (event
.preventDefault
) {
1149 event
.preventDefault(); // Firefox, Chrome, etc.
1151 event
.returnValue
= false; // IE
1152 event
.cancelBubble
= true;
1155 context
.px
= Dygraph
.findPosX(g
.canvas_
);
1156 context
.py
= Dygraph
.findPosY(g
.canvas_
);
1157 context
.dragStartX
= g
.dragGetX_(event
, context
);
1158 context
.dragStartY
= g
.dragGetY_(event
, context
);
1162 var interactionModel
= this.attr_("interactionModel");
1164 // Self is the graph.
1167 // Function that binds the graph and context to the handler.
1168 var bindHandler
= function(handler
) {
1169 return function(event
) {
1170 handler(event
, self
, context
);
1174 for (var eventName
in interactionModel
) {
1175 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1176 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
1177 bindHandler(interactionModel
[eventName
]));
1180 // If the user releases the mouse button during a drag, but not over the
1181 // canvas, then it doesn't count as a zooming action.
1182 Dygraph
.addEvent(document
, 'mouseup', function(event
) {
1183 if (context
.isZooming
|| context
.isPanning
) {
1184 context
.isZooming
= false;
1185 context
.dragStartX
= null;
1186 context
.dragStartY
= null;
1189 if (context
.isPanning
) {
1190 context
.isPanning
= false;
1191 context
.draggingDate
= null;
1192 context
.dateRange
= null;
1193 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1194 delete self
.axes_
[i
].draggingValue
;
1195 delete self
.axes_
[i
].dragValueRange
;
1203 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1204 * up any previous zoom rectangles that were drawn. This could be optimized to
1205 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1208 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1209 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1210 * @param {Number} startX The X position where the drag started, in canvas
1212 * @param {Number} endX The current X position of the drag, in canvas coords.
1213 * @param {Number} startY The Y position where the drag started, in canvas
1215 * @param {Number} endY The current Y position of the drag, in canvas coords.
1216 * @param {Number} prevDirection the value of direction on the previous call to
1217 * this function. Used to avoid excess redrawing
1218 * @param {Number} prevEndX The value of endX on the previous call to this
1219 * function. Used to avoid excess redrawing
1220 * @param {Number} prevEndY The value of endY on the previous call to this
1221 * function. Used to avoid excess redrawing
1224 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1225 endY
, prevDirection
, prevEndX
,
1227 var ctx
= this.canvas_
.getContext("2d");
1229 // Clean up from the previous rect if necessary
1230 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1231 ctx
.clearRect(Math
.min(startX
, prevEndX
), 0,
1232 Math
.abs(startX
- prevEndX
), this.height_
);
1233 } else if (prevDirection
== Dygraph
.VERTICAL
){
1234 ctx
.clearRect(0, Math
.min(startY
, prevEndY
),
1235 this.width_
, Math
.abs(startY
- prevEndY
));
1238 // Draw a light-grey rectangle to show the new viewing area
1239 if (direction
== Dygraph
.HORIZONTAL
) {
1240 if (endX
&& startX
) {
1241 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1242 ctx
.fillRect(Math
.min(startX
, endX
), 0,
1243 Math
.abs(endX
- startX
), this.height_
);
1246 if (direction
== Dygraph
.VERTICAL
) {
1247 if (endY
&& startY
) {
1248 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1249 ctx
.fillRect(0, Math
.min(startY
, endY
),
1250 this.width_
, Math
.abs(endY
- startY
));
1256 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1257 * the canvas. The exact zoom window may be slightly larger if there are no data
1258 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1259 * which accepts dates that match the raw data. This function redraws the graph.
1261 * @param {Number} lowX The leftmost pixel value that should be visible.
1262 * @param {Number} highX The rightmost pixel value that should be visible.
1265 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1266 // Find the earliest and latest dates contained in this canvasx range.
1267 // Convert the call to date ranges of the raw data.
1268 var r
= this.toDataCoords(lowX
, null);
1270 r
= this.toDataCoords(highX
, null);
1272 this.doZoomXDates_(minDate
, maxDate
);
1276 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1277 * method with doZoomX which accepts pixel coordinates. This function redraws
1280 * @param {Number} minDate The minimum date that should be visible.
1281 * @param {Number} maxDate The maximum date that should be visible.
1284 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1285 this.dateWindow_
= [minDate
, maxDate
];
1287 if (this.attr_("zoomCallback")) {
1288 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1293 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1294 * the canvas. This function redraws the graph.
1296 * @param {Number} lowY The topmost pixel value that should be visible.
1297 * @param {Number} highY The lowest pixel value that should be visible.
1300 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1301 // Find the highest and lowest values in pixel range for each axis.
1302 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1303 // This is because pixels increase as you go down on the screen, whereas data
1304 // coordinates increase as you go up the screen.
1305 var valueRanges
= [];
1306 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1307 var hi
= this.toDataCoords(null, lowY
, i
);
1308 var low
= this.toDataCoords(null, highY
, i
);
1309 this.axes_
[i
].valueWindow
= [low
[1], hi
[1]];
1310 valueRanges
.push([low
[1], hi
[1]]);
1314 if (this.attr_("zoomCallback")) {
1315 var xRange
= this.xAxisRange();
1316 this.attr_("zoomCallback")(xRange
[0], xRange
[1], this.yAxisRanges());
1321 * Reset the zoom to the original view coordinates. This is the same as
1322 * double-clicking on the graph.
1326 Dygraph
.prototype.doUnzoom_
= function() {
1328 if (this.dateWindow_
!= null) {
1330 this.dateWindow_
= null;
1333 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1334 if (this.axes_
[i
].valueWindow
!= null) {
1336 delete this.axes_
[i
].valueWindow
;
1341 // Putting the drawing operation before the callback because it resets
1344 if (this.attr_("zoomCallback")) {
1345 var minDate
= this.rawData_
[0][0];
1346 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1347 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1353 * When the mouse moves in the canvas, display information about a nearby data
1354 * point and draw dots over those points in the data series. This function
1355 * takes care of cleanup of previously-drawn dots.
1356 * @param {Object} event The mousemove event from the browser.
1359 Dygraph
.prototype.mouseMove_
= function(event
) {
1360 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1361 var points
= this.layout_
.points
;
1366 // Loop through all the points and find the date nearest to our current
1368 var minDist
= 1e+100;
1370 for (var i
= 0; i
< points
.length
; i
++) {
1371 var point
= points
[i
];
1372 if (point
== null) continue;
1373 var dist
= Math
.abs(point
.canvasx
- canvasx
);
1374 if (dist
> minDist
) continue;
1378 if (idx
>= 0) lastx
= points
[idx
].xval
;
1379 // Check that you can really highlight the last day's data
1380 var last
= points
[points
.length
-1];
1381 if (last
!= null && canvasx
> last
.canvasx
)
1382 lastx
= points
[points
.length
-1].xval
;
1384 // Extract the points we've selected
1385 this.selPoints_
= [];
1386 var l
= points
.length
;
1387 if (!this.attr_("stackedGraph")) {
1388 for (var i
= 0; i
< l
; i
++) {
1389 if (points
[i
].xval
== lastx
) {
1390 this.selPoints_
.push(points
[i
]);
1394 // Need to 'unstack' points starting from the bottom
1395 var cumulative_sum
= 0;
1396 for (var i
= l
- 1; i
>= 0; i
--) {
1397 if (points
[i
].xval
== lastx
) {
1398 var p
= {}; // Clone the point since we modify it
1399 for (var k
in points
[i
]) {
1400 p
[k
] = points
[i
][k
];
1402 p
.yval
-= cumulative_sum
;
1403 cumulative_sum
+= p
.yval
;
1404 this.selPoints_
.push(p
);
1407 this.selPoints_
.reverse();
1410 if (this.attr_("highlightCallback")) {
1411 var px
= this.lastx_
;
1412 if (px
!== null && lastx
!= px
) {
1413 // only fire if the selected point has changed.
1414 this.attr_("highlightCallback")(event
, lastx
, this.selPoints_
, this.idxToRow_(idx
));
1418 // Save last x position for callbacks.
1419 this.lastx_
= lastx
;
1421 this.updateSelection_();
1425 * Transforms layout_.points index into data row number.
1426 * @param int layout_.points index
1427 * @return int row number, or -1 if none could be found.
1430 Dygraph
.prototype.idxToRow_
= function(idx
) {
1431 if (idx
< 0) return -1;
1433 for (var i
in this.layout_
.datasets
) {
1434 if (idx
< this.layout_
.datasets
[i
].length
) {
1435 return this.boundaryIds_
[0][0]+idx
;
1437 idx
-= this.layout_
.datasets
[i
].length
;
1443 * Draw dots over the selectied points in the data series. This function
1444 * takes care of cleanup of previously-drawn dots.
1447 Dygraph
.prototype.updateSelection_
= function() {
1448 // Clear the previously drawn vertical, if there is one
1449 var ctx
= this.canvas_
.getContext("2d");
1450 if (this.previousVerticalX_
>= 0) {
1451 // Determine the maximum highlight circle size.
1452 var maxCircleSize
= 0;
1453 var labels
= this.attr_('labels');
1454 for (var i
= 1; i
< labels
.length
; i
++) {
1455 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1456 if (r
> maxCircleSize
) maxCircleSize
= r
;
1458 var px
= this.previousVerticalX_
;
1459 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1460 2 * maxCircleSize
+ 2, this.height_
);
1463 var isOK
= function(x
) { return x
&& !isNaN(x
); };
1465 if (this.selPoints_
.length
> 0) {
1466 var canvasx
= this.selPoints_
[0].canvasx
;
1468 // Set the status message to indicate the selected point(s)
1469 var replace
= this.attr_('xValueFormatter')(
1470 this.lastx_
, this.numXDigits_
+ this.numExtraDigits_
) + ":";
1471 var fmtFunc
= this.attr_('yValueFormatter');
1472 var clen
= this.colors_
.length
;
1474 if (this.attr_('showLabelsOnHighlight')) {
1475 // Set the status message to indicate the selected point(s)
1476 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1477 if (!this.attr_("labelsShowZeroValues") && this.selPoints_
[i
].yval
== 0) continue;
1478 if (!isOK(this.selPoints_
[i
].canvasy
)) continue;
1479 if (this.attr_("labelsSeparateLines")) {
1482 var point
= this.selPoints_
[i
];
1483 var c
= new RGBColor(this.plotter_
.colors
[point
.name
]);
1484 var yval
= fmtFunc(point
.yval
, this.numYDigits_
+ this.numExtraDigits_
);
1485 replace
+= " <b><font color='" + c
.toHex() + "'>"
1486 + point
.name
+ "</font></b>:"
1490 this.attr_("labelsDiv").innerHTML
= replace
;
1493 // Draw colored circles over the center of each selected point
1495 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1496 if (!isOK(this.selPoints_
[i
].canvasy
)) continue;
1498 this.attr_('highlightCircleSize', this.selPoints_
[i
].name
);
1500 ctx
.fillStyle
= this.plotter_
.colors
[this.selPoints_
[i
].name
];
1501 ctx
.arc(canvasx
, this.selPoints_
[i
].canvasy
, circleSize
,
1502 0, 2 * Math
.PI
, false);
1507 this.previousVerticalX_
= canvasx
;
1512 * Set manually set selected dots, and display information about them
1513 * @param int row number that should by highlighted
1514 * false value clears the selection
1517 Dygraph
.prototype.setSelection
= function(row
) {
1518 // Extract the points we've selected
1519 this.selPoints_
= [];
1522 if (row
!== false) {
1523 row
= row
-this.boundaryIds_
[0][0];
1526 if (row
!== false && row
>= 0) {
1527 for (var i
in this.layout_
.datasets
) {
1528 if (row
< this.layout_
.datasets
[i
].length
) {
1529 var point
= this.layout_
.points
[pos
+row
];
1531 if (this.attr_("stackedGraph")) {
1532 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
1535 this.selPoints_
.push(point
);
1537 pos
+= this.layout_
.datasets
[i
].length
;
1541 if (this.selPoints_
.length
) {
1542 this.lastx_
= this.selPoints_
[0].xval
;
1543 this.updateSelection_();
1546 this.clearSelection();
1552 * The mouse has left the canvas. Clear out whatever artifacts remain
1553 * @param {Object} event the mouseout event from the browser.
1556 Dygraph
.prototype.mouseOut_
= function(event
) {
1557 if (this.attr_("unhighlightCallback")) {
1558 this.attr_("unhighlightCallback")(event
);
1561 if (this.attr_("hideOverlayOnMouseOut")) {
1562 this.clearSelection();
1567 * Remove all selection from the canvas
1570 Dygraph
.prototype.clearSelection
= function() {
1571 // Get rid of the overlay data
1572 var ctx
= this.canvas_
.getContext("2d");
1573 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1574 this.attr_("labelsDiv").innerHTML
= "";
1575 this.selPoints_
= [];
1580 * Returns the number of the currently selected row
1581 * @return int row number, of -1 if nothing is selected
1584 Dygraph
.prototype.getSelection
= function() {
1585 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1589 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
1590 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
1591 return row
+ this.boundaryIds_
[0][0];
1597 Dygraph
.zeropad
= function(x
) {
1598 if (x
< 10) return "0" + x
; else return "" + x
;
1602 * Return a string version of the hours, minutes and seconds portion of a date.
1603 * @param {Number} date The JavaScript date (ms since epoch)
1604 * @return {String} A time of the form "HH:MM:SS"
1607 Dygraph
.hmsString_
= function(date
) {
1608 var zeropad
= Dygraph
.zeropad
;
1609 var d
= new Date(date
);
1610 if (d
.getSeconds()) {
1611 return zeropad(d
.getHours()) + ":" +
1612 zeropad(d
.getMinutes()) + ":" +
1613 zeropad(d
.getSeconds());
1615 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
1620 * Convert a JS date to a string appropriate to display on an axis that
1621 * is displaying values at the stated granularity.
1622 * @param {Date} date The date to format
1623 * @param {Number} granularity One of the Dygraph granularity constants
1624 * @return {String} The formatted date
1627 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
1628 if (granularity
>= Dygraph
.DECADAL
) {
1629 return date
.strftime('%Y');
1630 } else if (granularity
>= Dygraph
.MONTHLY
) {
1631 return date
.strftime('%b %y');
1633 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
1634 if (frac
== 0 || granularity
>= Dygraph
.DAILY
) {
1635 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
1637 return Dygraph
.hmsString_(date
.getTime());
1643 * Convert a JS date (millis since epoch) to YYYY/MM/DD
1644 * @param {Number} date The JavaScript date (ms since epoch)
1645 * @return {String} A date of the form "YYYY/MM/DD"
1648 Dygraph
.dateString_
= function(date
) {
1649 var zeropad
= Dygraph
.zeropad
;
1650 var d
= new Date(date
);
1653 var year
= "" + d
.getFullYear();
1654 // Get a 0 padded month string
1655 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
1656 // Get a 0 padded day string
1657 var day
= zeropad(d
.getDate());
1660 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
1661 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
1663 return year
+ "/" + month + "/" + day
+ ret
;
1667 * Fires when there's data available to be graphed.
1668 * @param {String} data Raw CSV data to be plotted
1671 Dygraph
.prototype.loadedEvent_
= function(data
) {
1672 this.rawData_
= this.parseCSV_(data
);
1676 Dygraph
.prototype.months
= ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
1677 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1678 Dygraph
.prototype.quarters
= ["Jan", "Apr", "Jul", "Oct"];
1681 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1684 Dygraph
.prototype.addXTicks_
= function() {
1685 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1687 if (this.dateWindow_
) {
1688 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
1690 range
= [this.rawData_
[0][0], this.rawData_
[this.rawData_
.length
- 1][0]];
1693 var formatter
= this.attr_('xTicker');
1694 var ret
= formatter(range
[0], range
[1], this);
1697 if (ret
.ticks
!== undefined
) {
1698 // numericTicks() returns multiple values.
1700 this.numXDigits_
= ret
.numDigits
;
1705 this.layout_
.updateOptions({xTicks
: xTicks
});
1708 // Time granularity enumeration
1709 Dygraph
.SECONDLY
= 0;
1710 Dygraph
.TWO_SECONDLY
= 1;
1711 Dygraph
.FIVE_SECONDLY
= 2;
1712 Dygraph
.TEN_SECONDLY
= 3;
1713 Dygraph
.THIRTY_SECONDLY
= 4;
1714 Dygraph
.MINUTELY
= 5;
1715 Dygraph
.TWO_MINUTELY
= 6;
1716 Dygraph
.FIVE_MINUTELY
= 7;
1717 Dygraph
.TEN_MINUTELY
= 8;
1718 Dygraph
.THIRTY_MINUTELY
= 9;
1719 Dygraph
.HOURLY
= 10;
1720 Dygraph
.TWO_HOURLY
= 11;
1721 Dygraph
.SIX_HOURLY
= 12;
1723 Dygraph
.WEEKLY
= 14;
1724 Dygraph
.MONTHLY
= 15;
1725 Dygraph
.QUARTERLY
= 16;
1726 Dygraph
.BIANNUAL
= 17;
1727 Dygraph
.ANNUAL
= 18;
1728 Dygraph
.DECADAL
= 19;
1729 Dygraph
.CENTENNIAL
= 20;
1730 Dygraph
.NUM_GRANULARITIES
= 21;
1732 Dygraph
.SHORT_SPACINGS
= [];
1733 Dygraph
.SHORT_SPACINGS
[Dygraph
.SECONDLY
] = 1000 * 1;
1734 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_SECONDLY
] = 1000 * 2;
1735 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_SECONDLY
] = 1000 * 5;
1736 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_SECONDLY
] = 1000 * 10;
1737 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_SECONDLY
] = 1000 * 30;
1738 Dygraph
.SHORT_SPACINGS
[Dygraph
.MINUTELY
] = 1000 * 60;
1739 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_MINUTELY
] = 1000 * 60 * 2;
1740 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_MINUTELY
] = 1000 * 60 * 5;
1741 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_MINUTELY
] = 1000 * 60 * 10;
1742 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_MINUTELY
] = 1000 * 60 * 30;
1743 Dygraph
.SHORT_SPACINGS
[Dygraph
.HOURLY
] = 1000 * 3600;
1744 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_HOURLY
] = 1000 * 3600 * 2;
1745 Dygraph
.SHORT_SPACINGS
[Dygraph
.SIX_HOURLY
] = 1000 * 3600 * 6;
1746 Dygraph
.SHORT_SPACINGS
[Dygraph
.DAILY
] = 1000 * 86400;
1747 Dygraph
.SHORT_SPACINGS
[Dygraph
.WEEKLY
] = 1000 * 604800;
1751 // If we used this time granularity, how many ticks would there be?
1752 // This is only an approximation, but it's generally good enough.
1754 Dygraph
.prototype.NumXTicks
= function(start_time
, end_time
, granularity
) {
1755 if (granularity
< Dygraph
.MONTHLY
) {
1756 // Generate one tick mark for every fixed interval of time.
1757 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
1758 return Math
.floor(0.5 + 1.0 * (end_time
- start_time
) / spacing
);
1760 var year_mod
= 1; // e.g. to only print one point every 10 years.
1761 var num_months
= 12;
1762 if (granularity
== Dygraph
.QUARTERLY
) num_months
= 3;
1763 if (granularity
== Dygraph
.BIANNUAL
) num_months
= 2;
1764 if (granularity
== Dygraph
.ANNUAL
) num_months
= 1;
1765 if (granularity
== Dygraph
.DECADAL
) { num_months
= 1; year_mod
= 10; }
1766 if (granularity
== Dygraph
.CENTENNIAL
) { num_months
= 1; year_mod
= 100; }
1768 var msInYear
= 365.2524 * 24 * 3600 * 1000;
1769 var num_years
= 1.0 * (end_time
- start_time
) / msInYear
;
1770 return Math
.floor(0.5 + 1.0 * num_years
* num_months
/ year_mod
);
1776 // Construct an x-axis of nicely-formatted times on meaningful boundaries
1777 // (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1779 // Returns an array containing {v: millis, label: label} dictionaries.
1781 Dygraph
.prototype.GetXAxis
= function(start_time
, end_time
, granularity
) {
1782 var formatter
= this.attr_("xAxisLabelFormatter");
1784 if (granularity
< Dygraph
.MONTHLY
) {
1785 // Generate one tick mark for every fixed interval of time.
1786 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
1787 var format
= '%d%b'; // e.g. "1Jan"
1789 // Find a time less than start_time which occurs on a "nice" time boundary
1790 // for this granularity.
1791 var g
= spacing
/ 1000;
1792 var d
= new Date(start_time
);
1793 if (g
<= 60) { // seconds
1794 var x
= d
.getSeconds(); d
.setSeconds(x
- x
% g
);
1798 if (g
<= 60) { // minutes
1799 var x
= d
.getMinutes(); d
.setMinutes(x
- x
% g
);
1804 if (g
<= 24) { // days
1805 var x
= d
.getHours(); d
.setHours(x
- x
% g
);
1810 if (g
== 7) { // one week
1811 d
.setDate(d
.getDate() - d
.getDay());
1816 start_time
= d
.getTime();
1818 for (var t
= start_time
; t
<= end_time
; t
+= spacing
) {
1819 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
1822 // Display a tick mark on the first of a set of months of each year.
1823 // Years get a tick mark iff y % year_mod == 0. This is useful for
1824 // displaying a tick mark once every 10 years, say, on long time scales.
1826 var year_mod
= 1; // e.g. to only print one point every 10 years.
1828 if (granularity
== Dygraph
.MONTHLY
) {
1829 months
= [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
1830 } else if (granularity
== Dygraph
.QUARTERLY
) {
1831 months
= [ 0, 3, 6, 9 ];
1832 } else if (granularity
== Dygraph
.BIANNUAL
) {
1834 } else if (granularity
== Dygraph
.ANNUAL
) {
1836 } else if (granularity
== Dygraph
.DECADAL
) {
1839 } else if (granularity
== Dygraph
.CENTENNIAL
) {
1843 this.warn("Span of dates is too long");
1846 var start_year
= new Date(start_time
).getFullYear();
1847 var end_year
= new Date(end_time
).getFullYear();
1848 var zeropad
= Dygraph
.zeropad
;
1849 for (var i
= start_year
; i
<= end_year
; i
++) {
1850 if (i
% year_mod
!= 0) continue;
1851 for (var j
= 0; j
< months
.length
; j
++) {
1852 var date_str
= i
+ "/" + zeropad(1 + months[j]) + "/01";
1853 var t
= Date
.parse(date_str
);
1854 if (t
< start_time
|| t
> end_time
) continue;
1855 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
1865 * Add ticks to the x-axis based on a date range.
1866 * @param {Number} startDate Start of the date window (millis since epoch)
1867 * @param {Number} endDate End of the date window (millis since epoch)
1868 * @return {Array.<Object>} Array of {label, value} tuples.
1871 Dygraph
.dateTicker
= function(startDate
, endDate
, self
) {
1873 for (var i
= 0; i
< Dygraph
.NUM_GRANULARITIES
; i
++) {
1874 var num_ticks
= self
.NumXTicks(startDate
, endDate
, i
);
1875 if (self
.width_
/ num_ticks
>= self
.attr_('pixelsPerXLabel')) {
1882 return self
.GetXAxis(startDate
, endDate
, chosen
);
1884 // TODO(danvk): signal error.
1889 * Determine the number of significant figures in a Number up to the specified
1890 * precision. Note that there is no way to determine if a trailing '0' is
1891 * significant or not, so by convention we return 1 for all of the following
1892 * inputs: 1, 1.0, 1.00, 1.000 etc.
1893 * @param {Number} x The input value.
1894 * @param {Number} opt_maxPrecision Optional maximum precision to consider.
1895 * Default and maximum allowed value is 13.
1896 * @return {Number} The number of significant figures which is >= 1.
1898 Dygraph
.significantFigures
= function(x
, opt_maxPrecision
) {
1899 var precision
= Math
.max(opt_maxPrecision
|| 13, 13);
1901 // Convert the number to its exponential notation form and work backwards,
1902 // ignoring the 'e+xx' bit. This may seem like a hack, but doing a loop and
1903 // dividing by 10 leads to roundoff errors. By using toExponential(), we let
1904 // the JavaScript interpreter handle the low level bits of the Number for us.
1905 var s
= x
.toExponential(precision
);
1906 var ePos
= s
.lastIndexOf('e'); // -1 case handled by return below.
1908 for (var i
= ePos
- 1; i
>= 0; i
--) {
1910 // Got to the decimal place. We'll call this 1 digit of precision because
1911 // we can't know for sure how many trailing 0s are significant.
1913 } else if (s
[i
] != '0') {
1914 // Found the first non-zero digit. Return the number of characters
1915 // except for the '.'.
1916 return i
; // This is i - 1 + 1 (-1 is for '.', +1 is for 0 based index).
1920 // Occurs if toExponential() doesn't return a string containing 'e', which
1921 // should never happen.
1926 * Add ticks when the x axis has numbers on it (instead of dates)
1927 * @param {Number} startDate Start of the date window (millis since epoch)
1928 * @param {Number} endDate End of the date window (millis since epoch)
1930 * @param {function} attribute accessor function.
1931 * @return {Array.<Object>} Array of {label, value} tuples.
1934 Dygraph
.numericTicks
= function(minV
, maxV
, self
, axis_props
, vals
) {
1935 var attr
= function(k
) {
1936 if (axis_props
&& axis_props
.hasOwnProperty(k
)) return axis_props
[k
];
1937 return self
.attr_(k
);
1942 for (var i
= 0; i
< vals
.length
; i
++) {
1943 ticks
[i
].push({v
: vals
[i
]});
1947 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
1948 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks
).
1949 // The first spacing greater than pixelsPerYLabel is what we use.
1950 // TODO(danvk): version that works on a log scale.
1951 if (attr("labelsKMG2")) {
1952 var mults
= [1, 2, 4, 8];
1954 var mults
= [1, 2, 5];
1956 var scale
, low_val
, high_val
, nTicks
;
1957 // TODO(danvk): make it possible to set this for x- and y-axes independently.
1958 var pixelsPerTick
= attr('pixelsPerYLabel');
1959 for (var i
= -10; i
< 50; i
++) {
1960 if (attr("labelsKMG2")) {
1961 var base_scale
= Math
.pow(16, i
);
1963 var base_scale
= Math
.pow(10, i
);
1965 for (var j
= 0; j
< mults
.length
; j
++) {
1966 scale
= base_scale
* mults
[j
];
1967 low_val
= Math
.floor(minV
/ scale
) * scale
;
1968 high_val
= Math
.ceil(maxV
/ scale
) * scale
;
1969 nTicks
= Math
.abs(high_val
- low_val
) / scale
;
1970 var spacing
= self
.height_
/ nTicks
;
1971 // wish I could break out of both loops at once...
1972 if (spacing
> pixelsPerTick
) break;
1974 if (spacing
> pixelsPerTick
) break;
1977 // Construct the set of ticks.
1978 // Allow reverse y-axis if it's explicitly requested.
1979 if (low_val
> high_val
) scale
*= -1;
1980 for (var i
= 0; i
< nTicks
; i
++) {
1981 var tickV
= low_val
+ i
* scale
;
1982 ticks
.push( {v
: tickV
} );
1986 // Add formatted labels to the ticks.
1989 if (attr("labelsKMB")) {
1991 k_labels
= [ "K", "M", "B", "T" ];
1993 if (attr("labelsKMG2")) {
1994 if (k
) self
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1996 k_labels
= [ "k", "M", "G", "T" ];
1998 var formatter
= attr('yAxisLabelFormatter') ?
1999 attr('yAxisLabelFormatter') : attr('yValueFormatter');
2001 // Determine the number of decimal places needed for the labels below by
2002 // taking the maximum number of significant figures for any label. We must
2003 // take the max because we can't tell if trailing 0s are significant.
2005 for (var i
= 0; i
< ticks
.length
; i
++) {
2006 numDigits
= Math
.max(Dygraph
.significantFigures(ticks
[i
].v
), numDigits
);
2009 for (var i
= 0; i
< ticks
.length
; i
++) {
2010 var tickV
= ticks
[i
].v
;
2011 var absTickV
= Math
.abs(tickV
);
2012 var label
= (formatter
!== undefined
) ?
2013 formatter(tickV
, numDigits
) : tickV
.toPrecision(numDigits
);
2014 if (k_labels
.length
> 0) {
2015 // Round up to an appropriate unit.
2017 for (var j
= 3; j
>= 0; j
--, n
/= k
) {
2018 if (absTickV
>= n
) {
2019 label
= (tickV
/ n
).toPrecision(numDigits
) + k_labels
[j
];
2024 ticks
[i
].label
= label
;
2026 return {ticks
: ticks
, numDigits
: numDigits
};
2029 // Computes the range of the data series (including confidence intervals).
2030 // series is either [ [x1, y1], [x2, y2], ... ] or
2031 // [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2032 // Returns [low, high]
2033 Dygraph
.prototype.extremeValues_
= function(series
) {
2034 var minY
= null, maxY
= null;
2036 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2038 // With custom bars, maxY is the max of the high values.
2039 for (var j
= 0; j
< series
.length
; j
++) {
2040 var y
= series
[j
][1][0];
2042 var low
= y
- series
[j
][1][1];
2043 var high
= y
+ series
[j
][1][2];
2044 if (low
> y
) low
= y
; // this can happen with custom bars,
2045 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2046 if (maxY
== null || high
> maxY
) {
2049 if (minY
== null || low
< minY
) {
2054 for (var j
= 0; j
< series
.length
; j
++) {
2055 var y
= series
[j
][1];
2056 if (y
=== null || isNaN(y
)) continue;
2057 if (maxY
== null || y
> maxY
) {
2060 if (minY
== null || y
< minY
) {
2066 return [minY
, maxY
];
2070 * This function is called once when the chart's data is changed or the options
2071 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2072 * idea is that values derived from the chart's data can be computed here,
2073 * rather than every time the chart is drawn. This includes things like the
2074 * number of axes, rolling averages, etc.
2076 Dygraph
.prototype.predraw_
= function() {
2077 // TODO(danvk): move more computations out of drawGraph_ and into here.
2078 this.computeYAxes_();
2080 // Create a new plotter.
2081 if (this.plotter_
) this.plotter_
.clear();
2082 this.plotter_
= new DygraphCanvasRenderer(this,
2083 this.hidden_
, this.layout_
,
2084 this.renderOptions_
);
2086 // The roller sits in the bottom left corner of the chart. We don't know where
2087 // this will be until the options are available, so it's positioned here.
2088 this.createRollInterface_();
2090 // Same thing applies for the labelsDiv. It's right edge should be flush with
2091 // the right edge of the charting area (which may not be the same as the right
2092 // edge of the div, if we have two y-axes.
2093 this.positionLabelsDiv_();
2095 // If the data or options have changed, then we'd better redraw.
2101 * Update the graph with new data. This method is called when the viewing area
2102 * has changed. If the underlying data or options have changed, predraw_ will
2103 * be called before drawGraph_ is called.
2106 Dygraph
.prototype.drawGraph_
= function() {
2107 var data
= this.rawData_
;
2109 // This is used to set the second parameter to drawCallback, below.
2110 var is_initial_draw
= this.is_initial_draw_
;
2111 this.is_initial_draw_
= false;
2113 var minY
= null, maxY
= null;
2114 this.layout_
.removeAllDatasets();
2116 this.attrs_
['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
2118 // Loop over the fields (series). Go from the last to the first,
2119 // because if they're stacked that's how we accumulate the values.
2121 var cumulative_y
= []; // For stacked series.
2124 var extremes
= {}; // series name -> [low, high]
2126 // Loop over all fields and create datasets
2127 for (var i
= data
[0].length
- 1; i
>= 1; i
--) {
2128 if (!this.visibility()[i
- 1]) continue;
2130 var seriesName
= this.attr_("labels")[i
];
2131 var connectSeparatedPoints
= this.attr_('connectSeparatedPoints', i
);
2134 for (var j
= 0; j
< data
.length
; j
++) {
2135 if (data
[j
][i
] != null || !connectSeparatedPoints
) {
2136 var date
= data
[j
][0];
2137 series
.push([date
, data
[j
][i
]]);
2141 // TODO(danvk): move this into predraw_. It's insane to do it here.
2142 series
= this.rollingAverage(series
, this.rollPeriod_
);
2144 // Prune down to the desired range, if necessary (for zooming)
2145 // Because there can be lines going to points outside of the visible area,
2146 // we actually prune to visible points, plus one on either side.
2147 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2148 if (this.dateWindow_
) {
2149 var low
= this.dateWindow_
[0];
2150 var high
= this.dateWindow_
[1];
2152 // TODO(danvk): do binary search instead of linear search.
2153 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2154 var firstIdx
= null, lastIdx
= null;
2155 for (var k
= 0; k
< series
.length
; k
++) {
2156 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2159 if (series
[k
][0] <= high
) {
2163 if (firstIdx
=== null) firstIdx
= 0;
2164 if (firstIdx
> 0) firstIdx
--;
2165 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2166 if (lastIdx
< series
.length
- 1) lastIdx
++;
2167 this.boundaryIds_
[i
-1] = [firstIdx
, lastIdx
];
2168 for (var k
= firstIdx
; k
<= lastIdx
; k
++) {
2169 pruned
.push(series
[k
]);
2173 this.boundaryIds_
[i
-1] = [0, series
.length
-1];
2176 var seriesExtremes
= this.extremeValues_(series
);
2179 for (var j
=0; j
<series
.length
; j
++) {
2180 val
= [series
[j
][0], series
[j
][1][0], series
[j
][1][1], series
[j
][1][2]];
2183 } else if (this.attr_("stackedGraph")) {
2184 var l
= series
.length
;
2186 for (var j
= 0; j
< l
; j
++) {
2187 // If one data set has a NaN, let all subsequent stacked
2188 // sets inherit the NaN -- only start at 0 for the first set.
2189 var x
= series
[j
][0];
2190 if (cumulative_y
[x
] === undefined
) {
2191 cumulative_y
[x
] = 0;
2194 actual_y
= series
[j
][1];
2195 cumulative_y
[x
] += actual_y
;
2197 series
[j
] = [x
, cumulative_y
[x
]]
2199 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2200 seriesExtremes
[1] = cumulative_y
[x
];
2202 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2203 seriesExtremes
[0] = cumulative_y
[x
];
2207 extremes
[seriesName
] = seriesExtremes
;
2209 datasets
[i
] = series
;
2212 for (var i
= 1; i
< datasets
.length
; i
++) {
2213 if (!this.visibility()[i
- 1]) continue;
2214 this.layout_
.addDataset(this.attr_("labels")[i
], datasets
[i
]);
2217 this.computeYAxisRanges_(extremes
);
2218 this.layout_
.updateOptions( { yAxes
: this.axes_
,
2219 seriesToAxisMap
: this.seriesToAxisMap_
2224 // Tell PlotKit to use this new data and render itself
2225 this.layout_
.updateOptions({dateWindow
: this.dateWindow_
});
2226 this.layout_
.evaluateWithError();
2227 this.plotter_
.clear();
2228 this.plotter_
.render();
2229 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2230 this.canvas_
.height
);
2232 if (this.attr_("drawCallback") !== null) {
2233 this.attr_("drawCallback")(this, is_initial_draw
);
2238 * Determine properties of the y-axes which are independent of the data
2239 * currently being displayed. This includes things like the number of axes and
2240 * the style of the axes. It does not include the range of each axis and its
2242 * This fills in this.axes_ and this.seriesToAxisMap_.
2243 * axes_ = [ { options } ]
2244 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2245 * indices are into the axes_ array.
2247 Dygraph
.prototype.computeYAxes_
= function() {
2248 this.axes_
= [{}]; // always have at least one y-axis.
2249 this.seriesToAxisMap_
= {};
2251 // Get a list of series names.
2252 var labels
= this.attr_("labels");
2254 for (var i
= 1; i
< labels
.length
; i
++) series
[labels
[i
]] = (i
- 1);
2256 // all options which could be applied per-axis:
2264 'axisLabelFontSize',
2268 // Copy global axis options over to the first axis.
2269 for (var i
= 0; i
< axisOptions
.length
; i
++) {
2270 var k
= axisOptions
[i
];
2271 var v
= this.attr_(k
);
2272 if (v
) this.axes_
[0][k
] = v
;
2275 // Go through once and add all the axes.
2276 for (var seriesName
in series
) {
2277 if (!series
.hasOwnProperty(seriesName
)) continue;
2278 var axis
= this.attr_("axis", seriesName
);
2280 this.seriesToAxisMap_
[seriesName
] = 0;
2283 if (typeof(axis
) == 'object') {
2284 // Add a new axis, making a copy of its per-axis options.
2286 Dygraph
.update(opts
, this.axes_
[0]);
2287 Dygraph
.update(opts
, { valueRange
: null }); // shouldn't inherit this.
2288 Dygraph
.update(opts
, axis
);
2289 this.axes_
.push(opts
);
2290 this.seriesToAxisMap_
[seriesName
] = this.axes_
.length
- 1;
2294 // Go through one more time and assign series to an axis defined by another
2295 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2296 for (var seriesName
in series
) {
2297 if (!series
.hasOwnProperty(seriesName
)) continue;
2298 var axis
= this.attr_("axis", seriesName
);
2299 if (typeof(axis
) == 'string') {
2300 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
2301 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
2302 "series " + axis
+ ", which does not define its own axis.");
2305 var idx
= this.seriesToAxisMap_
[axis
];
2306 this.seriesToAxisMap_
[seriesName
] = idx
;
2310 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2311 // this last so that hiding the first series doesn't destroy the axis
2312 // properties of the primary axis.
2313 var seriesToAxisFiltered
= {};
2314 var vis
= this.visibility();
2315 for (var i
= 1; i
< labels
.length
; i
++) {
2317 if (vis
[i
- 1]) seriesToAxisFiltered
[s
] = this.seriesToAxisMap_
[s
];
2319 this.seriesToAxisMap_
= seriesToAxisFiltered
;
2323 * Returns the number of y-axes on the chart.
2324 * @return {Number} the number of axes.
2326 Dygraph
.prototype.numAxes
= function() {
2328 for (var series
in this.seriesToAxisMap_
) {
2329 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2330 var idx
= this.seriesToAxisMap_
[series
];
2331 if (idx
> last_axis
) last_axis
= idx
;
2333 return 1 + last_axis
;
2337 * Determine the value range and tick marks for each axis.
2338 * @param {Object} extremes A mapping from seriesName -> [low, high]
2339 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2341 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2342 // Build a map from axis number -> [list of series names]
2343 var seriesForAxis
= [];
2344 for (var series
in this.seriesToAxisMap_
) {
2345 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2346 var idx
= this.seriesToAxisMap_
[series
];
2347 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2348 seriesForAxis
[idx
].push(series
);
2351 // Compute extreme values, a span and tick marks for each axis.
2352 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2353 var axis
= this.axes_
[i
];
2354 if (axis
.valueWindow
) {
2355 // This is only set if the user has zoomed on the y-axis. It is never set
2356 // by a user. It takes precedence over axis.valueRange because, if you set
2357 // valueRange, you'd still expect to be able to pan.
2358 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2359 } else if (axis
.valueRange
) {
2360 // This is a user-set value range for this axis.
2361 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
2363 // Calculate the extremes of extremes.
2364 var series
= seriesForAxis
[i
];
2365 var minY
= Infinity
; // extremes[series[0]][0];
2366 var maxY
= -Infinity
; // extremes[series[0]][1];
2367 for (var j
= 0; j
< series
.length
; j
++) {
2368 minY
= Math
.min(extremes
[series
[j
]][0], minY
);
2369 maxY
= Math
.max(extremes
[series
[j
]][1], maxY
);
2371 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2373 // Add some padding and round up to an integer to be human-friendly.
2374 var span
= maxY
- minY
;
2375 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2376 if (span
== 0) { span
= maxY
; }
2377 var maxAxisY
= maxY
+ 0.1 * span
;
2378 var minAxisY
= minY
- 0.1 * span
;
2380 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2381 if (!this.attr_("avoidMinZero")) {
2382 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2383 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2386 if (this.attr_("includeZero")) {
2387 if (maxY
< 0) maxAxisY
= 0;
2388 if (minY
> 0) minAxisY
= 0;
2391 axis
.computedValueRange
= [minAxisY
, maxAxisY
];
2394 // Add ticks. By default, all axes inherit the tick positions of the
2395 // primary axis. However, if an axis is specifically marked as having
2396 // independent ticks, then that is permissible as well.
2397 if (i
== 0 || axis
.independentTicks
) {
2399 Dygraph
.numericTicks(axis
.computedValueRange
[0],
2400 axis
.computedValueRange
[1],
2403 axis
.ticks
= ret
.ticks
;
2404 this.numYDigits_
= ret
.numDigits
;
2406 var p_axis
= this.axes_
[0];
2407 var p_ticks
= p_axis
.ticks
;
2408 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2409 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2410 var tick_values
= [];
2411 for (var i
= 0; i
< p_ticks
.length
; i
++) {
2412 var y_frac
= (p_ticks
[i
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2413 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2414 tick_values
.push(y_val
);
2418 Dygraph
.numericTicks(axis
.computedValueRange
[0],
2419 axis
.computedValueRange
[1],
2420 this, axis
, tick_values
);
2421 axis
.ticks
= ret
.ticks
;
2422 this.numYDigits_
= ret
.numDigits
;
2428 * Calculates the rolling average of a data set.
2429 * If originalData is [label, val], rolls the average of those.
2430 * If originalData is [label, [, it's interpreted as [value, stddev]
2431 * and the roll is returned in the same form, with appropriately reduced
2432 * stddev for each value.
2433 * Note that this is where fractional input (i.e. '5/10') is converted into
2435 * @param {Array} originalData The data in the appropriate format (see above)
2436 * @param {Number} rollPeriod The number of points over which to average the
2439 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2440 if (originalData
.length
< 2)
2441 return originalData
;
2442 var rollPeriod
= Math
.min(rollPeriod
, originalData
.length
- 1);
2443 var rollingData
= [];
2444 var sigma
= this.attr_("sigma");
2446 if (this.fractions_
) {
2448 var den
= 0; // numerator/denominator
2450 for (var i
= 0; i
< originalData
.length
; i
++) {
2451 num
+= originalData
[i
][1][0];
2452 den
+= originalData
[i
][1][1];
2453 if (i
- rollPeriod
>= 0) {
2454 num
-= originalData
[i
- rollPeriod
][1][0];
2455 den
-= originalData
[i
- rollPeriod
][1][1];
2458 var date
= originalData
[i
][0];
2459 var value
= den
? num
/ den
: 0.0;
2460 if (this.attr_("errorBars")) {
2461 if (this.wilsonInterval_
) {
2462 // For more details on this confidence interval, see:
2463 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2465 var p
= value
< 0 ? 0 : value
, n
= den
;
2466 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2467 var denom
= 1 + sigma
* sigma
/ den
;
2468 var low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2469 var high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2470 rollingData
[i
] = [date
,
2471 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2473 rollingData
[i
] = [date
, [0, 0, 0]];
2476 var stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2477 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2480 rollingData
[i
] = [date
, mult
* value
];
2483 } else if (this.attr_("customBars")) {
2488 for (var i
= 0; i
< originalData
.length
; i
++) {
2489 var data
= originalData
[i
][1];
2491 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2493 if (y
!= null && !isNaN(y
)) {
2499 if (i
- rollPeriod
>= 0) {
2500 var prev
= originalData
[i
- rollPeriod
];
2501 if (prev
[1][1] != null && !isNaN(prev
[1][1])) {
2508 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2509 1.0 * (mid
- low
) / count
,
2510 1.0 * (high
- mid
) / count
]];
2513 // Calculate the rolling average for the first rollPeriod - 1 points where
2514 // there is not enough data to roll over the full number of points
2515 var num_init_points
= Math
.min(rollPeriod
- 1, originalData
.length
- 2);
2516 if (!this.attr_("errorBars")){
2517 if (rollPeriod
== 1) {
2518 return originalData
;
2521 for (var i
= 0; i
< originalData
.length
; i
++) {
2524 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2525 var y
= originalData
[j
][1];
2526 if (y
== null || isNaN(y
)) continue;
2528 sum
+= originalData
[j
][1];
2531 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2533 rollingData
[i
] = [originalData
[i
][0], null];
2538 for (var i
= 0; i
< originalData
.length
; i
++) {
2542 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2543 var y
= originalData
[j
][1][0];
2544 if (y
== null || isNaN(y
)) continue;
2546 sum
+= originalData
[j
][1][0];
2547 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2550 var stddev
= Math
.sqrt(variance
) / num_ok
;
2551 rollingData
[i
] = [originalData
[i
][0],
2552 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2554 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2564 * Parses a date, returning the number of milliseconds since epoch. This can be
2565 * passed in as an xValueParser in the Dygraph constructor.
2566 * TODO(danvk): enumerate formats that this understands.
2567 * @param {String} A date in YYYYMMDD format.
2568 * @return {Number} Milliseconds since epoch.
2571 Dygraph
.dateParser
= function(dateStr
, self
) {
2574 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
2575 dateStrSlashed
= dateStr
.replace("-", "/", "g");
2576 while (dateStrSlashed
.search("-") != -1) {
2577 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
2579 d
= Date
.parse(dateStrSlashed
);
2580 } else if (dateStr
.length
== 8) { // e.g. '20090712'
2581 // TODO(danvk): remove support for this format. It's confusing.
2582 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr
.substr(4,2)
2583 + "/" + dateStr
.substr(6,2);
2584 d
= Date
.parse(dateStrSlashed
);
2586 // Any format that Date.parse will accept, e.g. "2009/07/12" or
2587 // "2009/07/12 12:34:56"
2588 d
= Date
.parse(dateStr
);
2591 if (!d
|| isNaN(d
)) {
2592 self
.error("Couldn't parse " + dateStr
+ " as a date");
2598 * Detects the type of the str (date or numeric) and sets the various
2599 * formatting attributes in this.attrs_ based on this type.
2600 * @param {String} str An x value.
2603 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2605 if (str
.indexOf('-') >= 0 ||
2606 str
.indexOf('/') >= 0 ||
2607 isNaN(parseFloat(str
))) {
2609 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2610 // TODO(danvk): remove support for this format.
2615 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
2616 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2617 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
2618 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2620 this.attrs_
.xValueFormatter
= this.attrs_
.xValueFormatter
;
2621 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2622 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2623 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
2628 * Parses a string in a special csv format. We expect a csv file where each
2629 * line is a date point, and the first field in each line is the date string.
2630 * We also expect that all remaining fields represent series.
2631 * if the errorBars attribute is set, then interpret the fields as:
2632 * date, series1, stddev1, series2, stddev2, ...
2633 * @param {Array.<Object>} data See above.
2636 * @return Array.<Object> An array with one entry for each row. These entries
2637 * are an array of cells in that row. The first entry is the parsed x-value for
2638 * the row. The second, third, etc. are the y-values. These can take on one of
2639 * three forms, depending on the CSV and constructor parameters:
2641 * 2. [ value, stddev ]
2642 * 3. [ low value, center value, high value ]
2644 Dygraph
.prototype.parseCSV_
= function(data
) {
2646 var lines
= data
.split("\n");
2648 // Use the default delimiter or fall back to a tab if that makes sense.
2649 var delim
= this.attr_('delimiter');
2650 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2655 if (this.labelsFromCSV_
) {
2657 this.attrs_
.labels
= lines
[0].split(delim
);
2660 // Parse the x as a float or return null if it's not a number.
2661 var parseFloatOrNull
= function(x
) {
2662 var val
= parseFloat(x
);
2663 // isFinite() returns false for NaN and +/-Infinity
.
2664 return isFinite(val
) ? val
: null;
2668 var defaultParserSet
= false; // attempt to auto-detect x value type
2669 var expectedCols
= this.attr_("labels").length
;
2670 var outOfOrder
= false;
2671 for (var i
= start
; i
< lines
.length
; i
++) {
2672 var line
= lines
[i
];
2673 if (line
.length
== 0) continue; // skip blank lines
2674 if (line
[0] == '#') continue; // skip comment lines
2675 var inFields
= line
.split(delim
);
2676 if (inFields
.length
< 2) continue;
2679 if (!defaultParserSet
) {
2680 this.detectTypeFromString_(inFields
[0]);
2681 xParser
= this.attr_("xValueParser");
2682 defaultParserSet
= true;
2684 fields
[0] = xParser(inFields
[0], this);
2686 // If fractions are expected, parse the numbers as "A/B
"
2687 if (this.fractions_) {
2688 for (var j = 1; j < inFields.length; j++) {
2689 // TODO(danvk): figure out an appropriate way to flag parse errors.
2690 var vals = inFields[j].split("/");
2691 fields[j] = [parseFloatOrNull(vals[0]), parseFloatOrNull(vals[1])];
2693 } else if (this.attr_("errorBars
")) {
2694 // If there are error bars, values are (value, stddev) pairs
2695 for (var j = 1; j < inFields.length; j += 2)
2696 fields[(j + 1) / 2] = [parseFloatOrNull(inFields[j]),
2697 parseFloatOrNull(inFields[j + 1])];
2698 } else if (this.attr_("customBars
")) {
2699 // Bars are a low;center;high tuple
2700 for (var j = 1; j < inFields.length; j++) {
2701 var vals = inFields[j].split(";");
2702 fields[j] = [ parseFloatOrNull(vals[0]),
2703 parseFloatOrNull(vals[1]),
2704 parseFloatOrNull(vals[2]) ];
2707 // Values are just numbers
2708 for (var j = 1; j < inFields.length; j++) {
2709 fields[j] = parseFloatOrNull(inFields[j]);
2712 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2717 if (fields.length != expectedCols) {
2718 this.error("Number of columns
in line
" + i + " (" + fields.length +
2719 ") does not agree
with number of
labels (" + expectedCols +
2725 this.warn("CSV is out of order
; order it correctly to speed loading
.");
2726 ret.sort(function(a,b) { return a[0] - b[0] });
2733 * The user has provided their data as a pre-packaged JS array. If the x values
2734 * are numeric, this is the same as dygraphs' internal format. If the x values
2735 * are dates, we need to convert them from Date objects to ms since epoch.
2736 * @param {Array.<Object>} data
2737 * @return {Array.<Object>} data with numeric x values.
2739 Dygraph.prototype.parseArray_ = function(data) {
2740 // Peek at the first x value to see if it's numeric.
2741 if (data.length == 0) {
2742 this.error("Can
't plot empty data set");
2745 if (data[0].length == 0) {
2746 this.error("Data set cannot contain an empty row");
2750 if (this.attr_("labels") == null) {
2751 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
2752 "in the options parameter");
2753 this.attrs_.labels = [ "X" ];
2754 for (var i = 1; i < data[0].length; i++) {
2755 this.attrs_.labels.push("Y" + i);
2759 if (Dygraph.isDateLike(data[0][0])) {
2760 // Some intelligent defaults for a date x-axis.
2761 this.attrs_.xValueFormatter = Dygraph.dateString_;
2762 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
2763 this.attrs_.xTicker = Dygraph.dateTicker;
2765 // Assume they're all dates
.
2766 var parsedData
= Dygraph
.clone(data
);
2767 for (var i
= 0; i
< data
.length
; i
++) {
2768 if (parsedData
[i
].length
== 0) {
2769 this.error("Row " + (1 + i
) + " of data is empty");
2772 if (parsedData
[i
][0] == null
2773 || typeof(parsedData
[i
][0].getTime
) != 'function'
2774 || isNaN(parsedData
[i
][0].getTime())) {
2775 this.error("x value in row " + (1 + i
) + " is not a Date");
2778 parsedData
[i
][0] = parsedData
[i
][0].getTime();
2782 // Some intelligent defaults for a numeric x-axis.
2783 this.attrs_
.xValueFormatter
= this.attrs_
.yValueFormatter
;
2784 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2790 * Parses a DataTable object from gviz.
2791 * The data is expected to have a first column that is either a date or a
2792 * number. All subsequent columns must be numbers. If there is a clear mismatch
2793 * between this.xValueParser_ and the type of the first column, it will be
2794 * fixed. Fills out rawData_.
2795 * @param {Array.<Object>} data See above.
2798 Dygraph
.prototype.parseDataTable_
= function(data
) {
2799 var cols
= data
.getNumberOfColumns();
2800 var rows
= data
.getNumberOfRows();
2802 var indepType
= data
.getColumnType(0);
2803 if (indepType
== 'date' || indepType
== 'datetime') {
2804 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
2805 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2806 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
2807 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2808 } else if (indepType
== 'number') {
2809 this.attrs_
.xValueFormatter
= this.attrs_
.yValueFormatter
;
2810 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2811 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2812 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
2814 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2815 "column 1 of DataTable input (Got '" + indepType
+ "')");
2819 // Array of the column indices which contain data (and not annotations).
2821 var annotationCols
= {}; // data index -> [annotation cols]
2822 var hasAnnotations
= false;
2823 for (var i
= 1; i
< cols
; i
++) {
2824 var type
= data
.getColumnType(i
);
2825 if (type
== 'number') {
2827 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
2828 // This is OK -- it's an annotation column.
2829 var dataIdx
= colIdx
[colIdx
.length
- 1];
2830 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
2831 annotationCols
[dataIdx
] = [i
];
2833 annotationCols
[dataIdx
].push(i
);
2835 hasAnnotations
= true;
2837 this.error("Only 'number' is supported as a dependent type with Gviz." +
2838 " 'string' is only supported if displayAnnotations is true");
2842 // Read column labels
2843 // TODO(danvk): add support back for errorBars
2844 var labels
= [data
.getColumnLabel(0)];
2845 for (var i
= 0; i
< colIdx
.length
; i
++) {
2846 labels
.push(data
.getColumnLabel(colIdx
[i
]));
2847 if (this.attr_("errorBars")) i
+= 1;
2849 this.attrs_
.labels
= labels
;
2850 cols
= labels
.length
;
2853 var outOfOrder
= false;
2854 var annotations
= [];
2855 for (var i
= 0; i
< rows
; i
++) {
2857 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
2858 data
.getValue(i
, 0) === null) {
2859 this.warn("Ignoring row " + i
+
2860 " of DataTable because of undefined or null first column.");
2864 if (indepType
== 'date' || indepType
== 'datetime') {
2865 row
.push(data
.getValue(i
, 0).getTime());
2867 row
.push(data
.getValue(i
, 0));
2869 if (!this.attr_("errorBars")) {
2870 for (var j
= 0; j
< colIdx
.length
; j
++) {
2871 var col
= colIdx
[j
];
2872 row
.push(data
.getValue(i
, col
));
2873 if (hasAnnotations
&&
2874 annotationCols
.hasOwnProperty(col
) &&
2875 data
.getValue(i
, annotationCols
[col
][0]) != null) {
2877 ann
.series
= data
.getColumnLabel(col
);
2879 ann
.shortText
= String
.fromCharCode(65 /* A */ + annotations
.length
)
2881 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
2882 if (k
) ann
.text
+= "\n";
2883 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
2885 annotations
.push(ann
);
2889 for (var j
= 0; j
< cols
- 1; j
++) {
2890 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
2893 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
2897 // Strip out infinities, which give dygraphs problems later on.
2898 for (var j
= 0; j
< row
.length
; j
++) {
2899 if (!isFinite(row
[j
])) row
[j
] = null;
2905 this.warn("DataTable is out of order; order it correctly to speed loading.");
2906 ret
.sort(function(a
,b
) { return a
[0] - b
[0] });
2908 this.rawData_
= ret
;
2910 if (annotations
.length
> 0) {
2911 this.setAnnotations(annotations
, true);
2915 // These functions are all based on MochiKit.
2916 Dygraph
.update
= function (self
, o
) {
2917 if (typeof(o
) != 'undefined' && o
!== null) {
2919 if (o
.hasOwnProperty(k
)) {
2927 Dygraph
.isArrayLike
= function (o
) {
2928 var typ
= typeof(o
);
2930 (typ
!= 'object' && !(typ
== 'function' &&
2931 typeof(o
.item
) == 'function')) ||
2933 typeof(o
.length
) != 'number' ||
2941 Dygraph
.isDateLike
= function (o
) {
2942 if (typeof(o
) != "object" || o
=== null ||
2943 typeof(o
.getTime
) != 'function') {
2949 Dygraph
.clone
= function(o
) {
2950 // TODO(danvk): figure out how MochiKit's version works
2952 for (var i
= 0; i
< o
.length
; i
++) {
2953 if (Dygraph
.isArrayLike(o
[i
])) {
2954 r
.push(Dygraph
.clone(o
[i
]));
2964 * Get the CSV data. If it's in a function, call that function. If it's in a
2965 * file, do an XMLHttpRequest to get it.
2968 Dygraph
.prototype.start_
= function() {
2969 if (typeof this.file_
== 'function') {
2970 // CSV string. Pretend we got it via XHR.
2971 this.loadedEvent_(this.file_());
2972 } else if (Dygraph
.isArrayLike(this.file_
)) {
2973 this.rawData_
= this.parseArray_(this.file_
);
2975 } else if (typeof this.file_
== 'object' &&
2976 typeof this.file_
.getColumnRange
== 'function') {
2977 // must be a DataTable from gviz.
2978 this.parseDataTable_(this.file_
);
2980 } else if (typeof this.file_
== 'string') {
2981 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2982 if (this.file_
.indexOf('\n') >= 0) {
2983 this.loadedEvent_(this.file_
);
2985 var req
= new XMLHttpRequest();
2987 req
.onreadystatechange
= function () {
2988 if (req
.readyState
== 4) {
2989 if (req
.status
== 200) {
2990 caller
.loadedEvent_(req
.responseText
);
2995 req
.open("GET", this.file_
, true);
2999 this.error("Unknown data format: " + (typeof this.file_
));
3004 * Changes various properties of the graph. These can include:
3006 * <li>file: changes the source data for the graph</li>
3007 * <li>errorBars: changes whether the data contains stddev</li>
3009 * @param {Object} attrs The new properties and values
3011 Dygraph
.prototype.updateOptions
= function(attrs
) {
3012 // TODO(danvk): this is a mess. Rethink this function.
3013 if ('rollPeriod' in attrs
) {
3014 this.rollPeriod_
= attrs
.rollPeriod
;
3016 if ('dateWindow' in attrs
) {
3017 this.dateWindow_
= attrs
.dateWindow
;
3020 // TODO(danvk): validate per-series options.
3025 // highlightCircleSize
3027 Dygraph
.update(this.user_attrs_
, attrs
);
3028 Dygraph
.update(this.renderOptions_
, attrs
);
3030 this.labelsFromCSV_
= (this.attr_("labels") == null);
3032 // TODO(danvk): this doesn't match the constructor logic
3033 this.layout_
.updateOptions({ 'errorBars': this.attr_("errorBars") });
3034 if (attrs
['file']) {
3035 this.file_
= attrs
['file'];
3043 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3044 * containing div (which has presumably changed size since the dygraph was
3045 * instantiated. If the width/height are specified, the div will be resized.
3047 * This is far more efficient than destroying and re-instantiating a
3048 * Dygraph, since it doesn't have to reparse the underlying data.
3050 * @param {Number} width Width (in pixels)
3051 * @param {Number} height Height (in pixels)
3053 Dygraph
.prototype.resize
= function(width
, height
) {
3054 if (this.resize_lock
) {
3057 this.resize_lock
= true;
3059 if ((width
=== null) != (height
=== null)) {
3060 this.warn("Dygraph.resize() should be called with zero parameters or " +
3061 "two non-NULL parameters. Pretending it was zero.");
3062 width
= height
= null;
3065 // TODO(danvk): there should be a clear() method.
3066 this.maindiv_
.innerHTML
= "";
3067 this.attrs_
.labelsDiv
= null;
3070 this.maindiv_
.style
.width
= width
+ "px";
3071 this.maindiv_
.style
.height
= height
+ "px";
3072 this.width_
= width
;
3073 this.height_
= height
;
3075 this.width_
= this.maindiv_
.offsetWidth
;
3076 this.height_
= this.maindiv_
.offsetHeight
;
3079 this.createInterface_();
3082 this.resize_lock
= false;
3086 * Adjusts the number of points in the rolling average. Updates the graph to
3087 * reflect the new averaging period.
3088 * @param {Number} length Number of points over which to average the data.
3090 Dygraph
.prototype.adjustRoll
= function(length
) {
3091 this.rollPeriod_
= length
;
3096 * Returns a boolean array of visibility statuses.
3098 Dygraph
.prototype.visibility
= function() {
3099 // Do lazy-initialization, so that this happens after we know the number of
3101 if (!this.attr_("visibility")) {
3102 this.attrs_
["visibility"] = [];
3104 while (this.attr_("visibility").length
< this.rawData_
[0].length
- 1) {
3105 this.attr_("visibility").push(true);
3107 return this.attr_("visibility");
3111 * Changes the visiblity of a series.
3113 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3114 var x
= this.visibility();
3115 if (num
< 0 || num
>= x
.length
) {
3116 this.warn("invalid series number in setVisibility: " + num
);
3124 * Update the list of annotations and redraw the chart.
3126 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3127 // Only add the annotation CSS rule once we know it will be used.
3128 Dygraph
.addAnnotationRule();
3129 this.annotations_
= ann
;
3130 this.layout_
.setAnnotations(this.annotations_
);
3131 if (!suppressDraw
) {
3137 * Return the list of annotations.
3139 Dygraph
.prototype.annotations
= function() {
3140 return this.annotations_
;
3144 * Get the index of a series (column) given its name. The first column is the
3145 * x-axis, so the data series start with index 1.
3147 Dygraph
.prototype.indexFromSetName
= function(name
) {
3148 var labels
= this.attr_("labels");
3149 for (var i
= 0; i
< labels
.length
; i
++) {
3150 if (labels
[i
] == name
) return i
;
3155 Dygraph
.addAnnotationRule
= function() {
3156 if (Dygraph
.addedAnnotationCSS
) return;
3158 var rule
= "border: 1px solid black; " +
3159 "background-color: white; " +
3160 "text-align: center;";
3162 var styleSheetElement
= document
.createElement("style");
3163 styleSheetElement
.type
= "text/css";
3164 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3166 // Find the first style sheet that we can access.
3167 // We may not add a rule to a style sheet from another domain for security
3168 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3169 // adds its own style sheets from google.com.
3170 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3171 if (document
.styleSheets
[i
].disabled
) continue;
3172 var mysheet
= document
.styleSheets
[i
];
3174 if (mysheet
.insertRule
) { // Firefox
3175 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3176 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3177 } else if (mysheet
.addRule
) { // IE
3178 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3180 Dygraph
.addedAnnotationCSS
= true;
3183 // Was likely a security exception.
3187 this.warn("Unable to add default annotation CSS rule; display may be off.");
3191 * Create a new canvas element. This is more complex than a simple
3192 * document.createElement("canvas") because of IE and excanvas.
3194 Dygraph
.createCanvas
= function() {
3195 var canvas
= document
.createElement("canvas");
3197 isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
3198 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
3199 canvas
= G_vmlCanvasManager
.initElement(canvas
);
3207 * A wrapper around Dygraph that implements the gviz API.
3208 * @param {Object} container The DOM object the visualization should live in.
3210 Dygraph
.GVizChart
= function(container
) {
3211 this.container
= container
;
3214 Dygraph
.GVizChart
.prototype.draw
= function(data
, options
) {
3215 // Clear out any existing dygraph.
3216 // TODO(danvk): would it make more sense to simply redraw using the current
3217 // date_graph object?
3218 this.container
.innerHTML
= '';
3219 if (typeof(this.date_graph
) != 'undefined') {
3220 this.date_graph
.destroy();
3223 this.date_graph
= new Dygraph(this.container
, data
, options
);
3227 * Google charts compatible setSelection
3228 * Only row selection is supported, all points in the row will be highlighted
3229 * @param {Array} array of the selected cells
3232 Dygraph
.GVizChart
.prototype.setSelection
= function(selection_array
) {
3234 if (selection_array
.length
) {
3235 row
= selection_array
[0].row
;
3237 this.date_graph
.setSelection(row
);
3241 * Google charts compatible getSelection implementation
3242 * @return {Array} array of the selected cells
3245 Dygraph
.GVizChart
.prototype.getSelection
= function() {
3248 var row
= this.date_graph
.getSelection();
3250 if (row
< 0) return selection
;
3253 for (var i
in this.date_graph
.layout_
.datasets
) {
3254 selection
.push({row
: row
, column
: col
});
3261 // Older pages may still use this name.
3262 DateGraph
= Dygraph
;