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
27 Date,SeriesA,SeriesB,...
28 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
29 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
31 If the 'fractions' option is set, the input should be of the form:
33 Date,SeriesA,SeriesB,...
34 YYYYMMDD,A1/B1,A2/B2,...
35 YYYYMMDD,A1/B1,A2/B2,...
37 And error bars will be calculated automatically using a binomial distribution.
39 For further documentation and examples, see http://dygraphs.com/
44 * Creates an interactive, zoomable chart.
47 * @param {div | String} div A div or the id of a div into which to construct
49 * @param {String | Function} file A file containing CSV data or a function
50 * that returns this data. The most basic expected format for each line is
51 * "YYYY/MM/DD,val1,val2,...". For more information, see
52 * http://dygraphs.com/data.html.
53 * @param {Object} attrs Various other attributes, e.g. errorBars determines
54 * whether the input data contains error ranges. For a complete list of
55 * options, see http://dygraphs.com/options.html.
57 Dygraph
= function(div
, data
, opts
) {
58 if (arguments
.length
> 0) {
59 if (arguments
.length
== 4) {
60 // Old versions of dygraphs took in the series labels as a constructor
61 // parameter. This doesn't make sense anymore, but it's easy to continue
62 // to support this usage.
63 this.warn("Using deprecated four-argument dygraph constructor");
64 this.__old_init__(div
, data
, arguments
[2], arguments
[3]);
66 this.__init__(div
, data
, opts
);
71 Dygraph
.NAME
= "Dygraph";
72 Dygraph
.VERSION
= "1.2";
73 Dygraph
.__repr__
= function() {
74 return "[" + this.NAME
+ " " + this.VERSION
+ "]";
78 * Returns information about the Dygraph class.
80 Dygraph
.toString
= function() {
81 return this.__repr__();
84 // Various default values
85 Dygraph
.DEFAULT_ROLL_PERIOD
= 1;
86 Dygraph
.DEFAULT_WIDTH
= 480;
87 Dygraph
.DEFAULT_HEIGHT
= 320;
89 Dygraph
.LOG_SCALE
= 10;
90 Dygraph
.LN_TEN
= Math
.log(Dygraph
.LOG_SCALE
);
92 Dygraph
.log10
= function(x
) {
93 return Math
.log(x
) / Dygraph
.LN_TEN
;
96 // Default attribute values.
97 Dygraph
.DEFAULT_ATTRS
= {
98 highlightCircleSize
: 3,
104 // TODO(danvk): move defaults from createStatusMessage_ here.
106 labelsSeparateLines
: false,
107 labelsShowZeroValues
: true,
110 showLabelsOnHighlight
: true,
112 yValueFormatter
: function(a
,b
) { return Dygraph
.numberFormatter(a
,b
); },
113 digitsAfterDecimal
: 2,
120 axisLabelFontSize
: 14,
123 xAxisLabelFormatter
: Dygraph
.dateAxisFormatter
,
127 xValueFormatter
: Dygraph
.dateString_
,
128 xValueParser
: Dygraph
.dateParser
,
129 xTicker
: Dygraph
.dateTicker
,
136 wilsonInterval
: true, // only relevant if fractions is true
140 connectSeparatedPoints
: false,
143 hideOverlayOnMouseOut
: true,
145 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
146 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
151 // Sizes of the various chart labels.
158 axisLineColor
: "black",
161 axisLabelColor
: "black",
162 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
166 gridLineColor
: "rgb(128,128,128)",
168 interactionModel
: null // will be set to Dygraph.defaultInteractionModel.
171 // Various logging levels.
177 // Directions for panning and zooming. Use bit operations when combined
178 // values are possible.
179 Dygraph
.HORIZONTAL
= 1;
180 Dygraph
.VERTICAL
= 2;
182 // Used for initializing annotation CSS rules only once.
183 Dygraph
.addedAnnotationCSS
= false;
187 * Return the 2d context for a dygraph canvas.
189 * This method is only exposed for the sake of replacing the function in
190 * automated tests, e.g.
192 * var oldFunc = Dygraph.getContext();
193 * Dygraph.getContext = function(canvas) {
194 * var realContext = oldFunc(canvas);
195 * return new Proxy(realContext);
198 Dygraph
.getContext
= function(canvas
) {
199 return canvas
.getContext("2d");
202 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
203 // Labels is no longer a constructor parameter, since it's typically set
204 // directly from the data source. It also conains a name for the x-axis,
205 // which the previous constructor form did not.
206 if (labels
!= null) {
207 var new_labels
= ["Date"];
208 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
209 Dygraph
.update(attrs
, { 'labels': new_labels
});
211 this.__init__(div
, file
, attrs
);
215 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
216 * and context <canvas> inside of it. See the constructor for details.
218 * @param {Element} div the Element to render the graph into.
219 * @param {String | Function} file Source data
220 * @param {Object} attrs Miscellaneous other options
223 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
224 // Hack for IE: if we're using excanvas and the document hasn't finished
225 // loading yet (and hence may not have initialized whatever it needs to
226 // initialize), then keep calling this routine periodically until it has.
227 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
228 typeof(G_vmlCanvasManager
) != 'undefined' &&
229 document
.readyState
!= 'complete') {
231 setTimeout(function() { self
.__init__(div
, file
, attrs
) }, 100);
234 // Support two-argument constructor
235 if (attrs
== null) { attrs
= {}; }
237 // Copy the important bits into the object
238 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
241 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
242 this.previousVerticalX_
= -1;
243 this.fractions_
= attrs
.fractions
|| false;
244 this.dateWindow_
= attrs
.dateWindow
|| null;
246 this.wilsonInterval_
= attrs
.wilsonInterval
|| true;
247 this.is_initial_draw_
= true;
248 this.annotations_
= [];
250 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
251 this.zoomed_x_
= false;
252 this.zoomed_y_
= false;
254 // Clear the div. This ensure that, if multiple dygraphs are passed the same
255 // div, then only one will be drawn.
258 // If the div isn't already sized then inherit from our attrs or
259 // give it a default size.
260 if (div
.style
.width
== '') {
261 div
.style
.width
= (attrs
.width
|| Dygraph
.DEFAULT_WIDTH
) + "px";
263 if (div
.style
.height
== '') {
264 div
.style
.height
= (attrs
.height
|| Dygraph
.DEFAULT_HEIGHT
) + "px";
266 this.width_
= parseInt(div
.style
.width
, 10);
267 this.height_
= parseInt(div
.style
.height
, 10);
268 // The div might have been specified as percent of the current window size,
269 // convert that to an appropriate number of pixels.
270 if (div
.style
.width
.indexOf("%") == div
.style
.width
.length
- 1) {
271 this.width_
= div
.offsetWidth
;
273 if (div
.style
.height
.indexOf("%") == div
.style
.height
.length
- 1) {
274 this.height_
= div
.offsetHeight
;
277 if (this.width_
== 0) {
278 this.error("dygraph has zero width. Please specify a width in pixels.");
280 if (this.height_
== 0) {
281 this.error("dygraph has zero height. Please specify a height in pixels.");
284 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
285 if (attrs
['stackedGraph']) {
286 attrs
['fillGraph'] = true;
287 // TODO(nikhilk): Add any other stackedGraph checks here.
290 // Dygraphs has many options, some of which interact with one another.
291 // To keep track of everything, we maintain two sets of options:
293 // this.user_attrs_ only options explicitly set by the user.
294 // this.attrs_ defaults, options derived from user_attrs_, data.
296 // Options are then accessed this.attr_('attr'), which first looks at
297 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
298 // defaults without overriding behavior that the user specifically asks for.
299 this.user_attrs_
= {};
300 Dygraph
.update(this.user_attrs_
, attrs
);
303 Dygraph
.update(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
305 this.boundaryIds_
= [];
307 // Create the containing DIV and other interactive elements
308 this.createInterface_();
314 * Returns the zoomed status of the chart for one or both axes.
316 * Axis is an optional parameter. Can be set to 'x' or 'y'.
318 * The zoomed status for an axis is set whenever a user zooms using the mouse
319 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
320 * option is also specified).
322 Dygraph
.prototype.isZoomed
= function(axis
) {
323 if (axis
== null) return this.zoomed_x_
|| this.zoomed_y_
;
324 if (axis
== 'x') return this.zoomed_x_
;
325 if (axis
== 'y') return this.zoomed_y_
;
326 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
330 * Returns information about the Dygraph object, including its containing ID.
332 Dygraph
.prototype.toString
= function() {
333 var maindiv
= this.maindiv_
;
334 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
335 return "[Dygraph " + id
+ "]";
340 * Returns the value of an option. This may be set by the user (either in the
341 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
343 * @param { String } name The name of the option, e.g. 'rollPeriod'.
344 * @param { String } [seriesName] The name of the series to which the option
345 * will be applied. If no per-series value of this option is available, then
346 * the global value is returned. This is optional.
347 * @return { ... } The value of the option.
349 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
350 // <REMOVE_FOR_COMBINED>
351 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
352 this.error('Must include options reference JS for testing');
353 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
354 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
355 'in the Dygraphs.OPTIONS_REFERENCE listing.');
356 // Only log this error once.
357 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
359 // </REMOVE_FOR_COMBINED
>
361 typeof(this.user_attrs_
[seriesName
]) != 'undefined' &&
362 this.user_attrs_
[seriesName
] != null &&
363 typeof(this.user_attrs_
[seriesName
][name
]) != 'undefined') {
364 return this.user_attrs_
[seriesName
][name
];
365 } else if (typeof(this.user_attrs_
[name
]) != 'undefined') {
366 return this.user_attrs_
[name
];
367 } else if (typeof(this.attrs_
[name
]) != 'undefined') {
368 return this.attrs_
[name
];
374 // TODO(danvk): any way I can get the line numbers to be this.warn call?
377 * Log an error on the JS console at the given severity.
378 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
379 * @param { String } The message to log.
381 Dygraph
.prototype.log
= function(severity
, message
) {
382 if (typeof(console
) != 'undefined') {
385 console
.debug('dygraphs: ' + message
);
388 console
.info('dygraphs: ' + message
);
390 case Dygraph
.WARNING
:
391 console
.warn('dygraphs: ' + message
);
394 console
.error('dygraphs: ' + message
);
401 Dygraph
.prototype.info
= function(message
) {
402 this.log(Dygraph
.INFO
, message
);
406 Dygraph
.prototype.warn
= function(message
) {
407 this.log(Dygraph
.WARNING
, message
);
411 Dygraph
.prototype.error
= function(message
) {
412 this.log(Dygraph
.ERROR
, message
);
416 * Returns the current rolling period, as set by the user or an option.
417 * @return {Number} The number of points in the rolling window
419 Dygraph
.prototype.rollPeriod
= function() {
420 return this.rollPeriod_
;
424 * Returns the currently-visible x-range. This can be affected by zooming,
425 * panning or a call to updateOptions.
426 * Returns a two-element array: [left, right].
427 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
429 Dygraph
.prototype.xAxisRange
= function() {
430 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
434 * Returns the lower- and upper-bound x-axis values of the
437 Dygraph
.prototype.xAxisExtremes
= function() {
438 var left
= this.rawData_
[0][0];
439 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
440 return [left
, right
];
444 * Returns the currently-visible y-range for an axis. This can be affected by
445 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
446 * called with no arguments, returns the range of the first axis.
447 * Returns a two-element array: [bottom, top].
449 Dygraph
.prototype.yAxisRange
= function(idx
) {
450 if (typeof(idx
) == "undefined") idx
= 0;
451 if (idx
< 0 || idx
>= this.axes_
.length
) return null;
452 return [ this.axes_
[idx
].computedValueRange
[0],
453 this.axes_
[idx
].computedValueRange
[1] ];
457 * Returns the currently-visible y-ranges for each axis. This can be affected by
458 * zooming, panning, calls to updateOptions, etc.
459 * Returns an array of [bottom, top] pairs, one for each y-axis.
461 Dygraph
.prototype.yAxisRanges
= function() {
463 for (var i
= 0; i
< this.axes_
.length
; i
++) {
464 ret
.push(this.yAxisRange(i
));
469 // TODO(danvk): use these functions throughout dygraphs.
471 * Convert from data coordinates to canvas/div X/Y coordinates.
472 * If specified, do this conversion for the coordinate system of a particular
473 * axis. Uses the first axis by default.
474 * Returns a two-element array: [X, Y]
476 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
477 * instead of toDomCoords(null, y, axis).
479 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
480 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
484 * Convert from data x coordinates to canvas/div X coordinate.
485 * If specified, do this conversion for the coordinate system of a particular
487 * Returns a single value or null if x is null.
489 Dygraph
.prototype.toDomXCoord
= function(x
) {
494 var area
= this.plotter_
.area
;
495 var xRange
= this.xAxisRange();
496 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
500 * Convert from data x coordinates to canvas/div Y coordinate and optional
501 * axis. Uses the first axis by default.
503 * returns a single value or null if y is null.
505 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
506 var pct
= this.toPercentYCoord(y
, axis
);
511 var area
= this.plotter_
.area
;
512 return area
.y
+ pct
* area
.h
;
516 * Convert from canvas/div coords to data coordinates.
517 * If specified, do this conversion for the coordinate system of a particular
518 * axis. Uses the first axis by default.
519 * Returns a two-element array: [X, Y].
521 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
522 * instead of toDataCoords(null, y, axis).
524 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
525 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
529 * Convert from canvas/div x coordinate to data coordinate.
531 * If x is null, this returns null.
533 Dygraph
.prototype.toDataXCoord
= function(x
) {
538 var area
= this.plotter_
.area
;
539 var xRange
= this.xAxisRange();
540 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
544 * Convert from canvas/div y coord to value.
546 * If y is null, this returns null.
547 * if axis is null, this uses the first axis.
549 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
554 var area
= this.plotter_
.area
;
555 var yRange
= this.yAxisRange(axis
);
557 if (typeof(axis
) == "undefined") axis
= 0;
558 if (!this.axes_
[axis
].logscale
) {
559 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
561 // Computing the inverse of toDomCoord.
562 var pct
= (y
- area
.y
) / area
.h
564 // Computing the inverse of toPercentYCoord. The function was arrived at with
565 // the following steps:
567 // Original calcuation:
568 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
570 // Move denominator to both sides:
571 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
573 // subtract logr1, and take the negative value.
574 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
576 // Swap both sides of the equation, and we can compute the log of the
577 // return value. Which means we just need to use that as the exponent in
579 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
581 var logr1
= Dygraph
.log10(yRange
[1]);
582 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
583 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
589 * Converts a y for an axis to a percentage from the top to the
590 * bottom of the drawing area.
592 * If the coordinate represents a value visible on the canvas, then
593 * the value will be between 0 and 1, where 0 is the top of the canvas.
594 * However, this method will return values outside the range, as
595 * values can fall outside the canvas.
597 * If y is null, this returns null.
598 * if axis is null, this uses the first axis.
600 * @param { Number } y The data y-coordinate.
601 * @param { Number } [axis] The axis number on which the data coordinate lives.
602 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
604 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
608 if (typeof(axis
) == "undefined") axis
= 0;
610 var area
= this.plotter_
.area
;
611 var yRange
= this.yAxisRange(axis
);
614 if (!this.axes_
[axis
].logscale
) {
615 // yRange[1] - y is unit distance from the bottom.
616 // yRange[1] - yRange[0] is the scale of the range.
617 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
618 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
620 var logr1
= Dygraph
.log10(yRange
[1]);
621 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
627 * Converts an x value to a percentage from the left to the right of
630 * If the coordinate represents a value visible on the canvas, then
631 * the value will be between 0 and 1, where 0 is the left of the canvas.
632 * However, this method will return values outside the range, as
633 * values can fall outside the canvas.
635 * If x is null, this returns null.
636 * @param { Number } x The data x-coordinate.
637 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
639 Dygraph
.prototype.toPercentXCoord
= function(x
) {
644 var xRange
= this.xAxisRange();
645 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
649 * Returns the number of columns (including the independent variable).
650 * @return { Integer } The number of columns.
652 Dygraph
.prototype.numColumns
= function() {
653 return this.rawData_
[0].length
;
657 * Returns the number of rows (excluding any header/label row).
658 * @return { Integer } The number of rows, less any header.
660 Dygraph
.prototype.numRows
= function() {
661 return this.rawData_
.length
;
665 * Returns the value in the given row and column. If the row and column exceed
666 * the bounds on the data, returns null. Also returns null if the value is
668 * @param { Number} row The row number of the data (0-based). Row 0 is the
669 * first row of data, not a header row.
670 * @param { Number} col The column number of the data (0-based)
671 * @return { Number } The value in the specified cell or null if the row/col
674 Dygraph
.prototype.getValue
= function(row
, col
) {
675 if (row
< 0 || row
> this.rawData_
.length
) return null;
676 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
678 return this.rawData_
[row
][col
];
683 * Add an event handler. This smooths a difference between IE and the rest of
685 * @param { DOM element } el The element to add the event to.
686 * @param { String } evt The name of the event, e.g. 'click' or 'mousemove'.
687 * @param { Function } fn The function to call on the event. The function takes
688 * one parameter: the event object.
690 Dygraph
.addEvent
= function(el
, evt
, fn
) {
691 var normed_fn
= function(e
) {
692 if (!e
) var e
= window
.event
;
695 if (window
.addEventListener
) { // Mozilla, Netscape, Firefox
696 el
.addEventListener(evt
, normed_fn
, false);
698 el
.attachEvent('on' + evt
, normed_fn
);
705 * Cancels further processing of an event. This is useful to prevent default
706 * browser actions, e.g. highlighting text on a double-click.
707 * Based on the article at
708 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
709 * @param { Event } e The event whose normal behavior should be canceled.
711 Dygraph
.cancelEvent
= function(e
) {
712 e
= e
? e
: window
.event
;
713 if (e
.stopPropagation
) {
716 if (e
.preventDefault
) {
719 e
.cancelBubble
= true;
721 e
.returnValue
= false;
727 * Generates interface elements for the Dygraph: a containing div, a div to
728 * display the current point, and a textbox to adjust the rolling average
729 * period. Also creates the Renderer/Layout elements.
732 Dygraph
.prototype.createInterface_
= function() {
733 // Create the all-enclosing graph div
734 var enclosing
= this.maindiv_
;
736 this.graphDiv
= document
.createElement("div");
737 this.graphDiv
.style
.width
= this.width_
+ "px";
738 this.graphDiv
.style
.height
= this.height_
+ "px";
739 enclosing
.appendChild(this.graphDiv
);
741 // Create the canvas for interactive parts of the chart.
742 this.canvas_
= Dygraph
.createCanvas();
743 this.canvas_
.style
.position
= "absolute";
744 this.canvas_
.width
= this.width_
;
745 this.canvas_
.height
= this.height_
;
746 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
747 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
749 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
751 // ... and for static parts of the chart.
752 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
753 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
755 // The interactive parts of the graph are drawn on top of the chart.
756 this.graphDiv
.appendChild(this.hidden_
);
757 this.graphDiv
.appendChild(this.canvas_
);
758 this.mouseEventElement_
= this.canvas_
;
761 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', function(e
) {
762 dygraph
.mouseMove_(e
);
764 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', function(e
) {
765 dygraph
.mouseOut_(e
);
768 // Create the grapher
769 this.layout_
= new DygraphLayout(this);
771 this.createStatusMessage_();
772 this.createDragInterface_();
776 * Detach DOM elements in the dygraph and null out all data references.
777 * Calling this when you're done with a dygraph can dramatically reduce memory
778 * usage. See, e.g., the tests/perf.html example.
780 Dygraph
.prototype.destroy
= function() {
781 var removeRecursive
= function(node
) {
782 while (node
.hasChildNodes()) {
783 removeRecursive(node
.firstChild
);
784 node
.removeChild(node
.firstChild
);
787 removeRecursive(this.maindiv_
);
789 var nullOut
= function(obj
) {
791 if (typeof(obj
[n
]) === 'object') {
797 // These may not all be necessary, but it can't hurt...
798 nullOut(this.layout_
);
799 nullOut(this.plotter_
);
804 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
805 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
806 * or the zoom rectangles) is done on this.canvas_.
807 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
808 * @return {Object} The newly-created canvas
811 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
812 var h
= Dygraph
.createCanvas();
813 h
.style
.position
= "absolute";
814 // TODO(danvk): h should be offset from canvas. canvas needs to include
815 // some extra area to make it easier to zoom in on the far left and far
816 // right. h needs to be precisely the plot area, so that clipping occurs.
817 h
.style
.top
= canvas
.style
.top
;
818 h
.style
.left
= canvas
.style
.left
;
819 h
.width
= this.width_
;
820 h
.height
= this.height_
;
821 h
.style
.width
= this.width_
+ "px"; // for IE
822 h
.style
.height
= this.height_
+ "px"; // for IE
827 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
828 * is used to generate default series colors which are evenly spaced on the
830 * @param { Number } hue Range is 0.0-1.0.
831 * @param { Number } saturation Range is 0.0-1.0.
832 * @param { Number } value Range is 0.0-1.0.
833 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
836 Dygraph
.hsvToRGB
= function (hue
, saturation
, value
) {
840 if (saturation
=== 0) {
845 var i
= Math
.floor(hue
* 6);
846 var f
= (hue
* 6) - i
;
847 var p
= value
* (1 - saturation
);
848 var q
= value
* (1 - (saturation
* f
));
849 var t
= value
* (1 - (saturation
* (1 - f
)));
851 case 1: red
= q
; green
= value
; blue
= p
; break;
852 case 2: red
= p
; green
= value
; blue
= t
; break;
853 case 3: red
= p
; green
= q
; blue
= value
; break;
854 case 4: red
= t
; green
= p
; blue
= value
; break;
855 case 5: red
= value
; green
= p
; blue
= q
; break;
856 case 6: // fall through
857 case 0: red
= value
; green
= t
; blue
= p
; break;
860 red
= Math
.floor(255 * red
+ 0.5);
861 green
= Math
.floor(255 * green
+ 0.5);
862 blue
= Math
.floor(255 * blue
+ 0.5);
863 return 'rgb(' + red
+ ',' + green
+ ',' + blue
+ ')';
868 * Generate a set of distinct colors for the data series. This is done with a
869 * color wheel. Saturation/Value are customizable, and the hue is
870 * equally-spaced around the color wheel. If a custom set of colors is
871 * specified, that is used instead.
874 Dygraph
.prototype.setColors_
= function() {
875 var num
= this.attr_("labels").length
- 1;
877 var colors
= this.attr_('colors');
879 var sat
= this.attr_('colorSaturation') || 1.0;
880 var val
= this.attr_('colorValue') || 0.5;
881 var half
= Math
.ceil(num
/ 2);
882 for (var i
= 1; i
<= num
; i
++) {
883 if (!this.visibility()[i
-1]) continue;
884 // alternate colors for high contrast.
885 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
886 var hue
= (1.0 * idx
/ (1 + num
));
887 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
890 for (var i
= 0; i
< num
; i
++) {
891 if (!this.visibility()[i
]) continue;
892 var colorStr
= colors
[i
% colors
.length
];
893 this.colors_
.push(colorStr
);
897 this.plotter_
.setColors(this.colors_
);
901 * Return the list of colors. This is either the list of colors passed in the
902 * attributes or the autogenerated list of rgb(r,g,b) strings.
903 * @return {Array<string>} The list of colors.
905 Dygraph
.prototype.getColors
= function() {
909 // The following functions are from quirksmode.org with a modification for Safari from
910 // http://blog.firetree.net/2005/07/04/javascript-find-position/
911 // http://www.quirksmode.org/js
/findpos
.html
914 Dygraph
.findPosX
= function(obj
) {
919 curleft
+= obj
.offsetLeft
;
920 if(!obj
.offsetParent
)
922 obj
= obj
.offsetParent
;
931 Dygraph
.findPosY
= function(obj
) {
936 curtop
+= obj
.offsetTop
;
937 if(!obj
.offsetParent
)
939 obj
= obj
.offsetParent
;
948 * Create the div that contains information on the selected point(s)
949 * This goes in the top right of the canvas, unless an external div has already
953 Dygraph
.prototype.createStatusMessage_
= function() {
954 var userLabelsDiv
= this.user_attrs_
["labelsDiv"];
955 if (userLabelsDiv
&& null != userLabelsDiv
956 && (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
)) {
957 this.user_attrs_
["labelsDiv"] = document
.getElementById(userLabelsDiv
);
959 if (!this.attr_("labelsDiv")) {
960 var divWidth
= this.attr_('labelsDivWidth');
962 "position": "absolute",
965 "width": divWidth
+ "px",
967 "left": (this.width_
- divWidth
- 2) + "px",
968 "background": "white",
970 "overflow": "hidden"};
971 Dygraph
.update(messagestyle
, this.attr_('labelsDivStyles'));
972 var div
= document
.createElement("div");
973 for (var name
in messagestyle
) {
974 if (messagestyle
.hasOwnProperty(name
)) {
975 div
.style
[name
] = messagestyle
[name
];
978 this.graphDiv
.appendChild(div
);
979 this.attrs_
.labelsDiv
= div
;
984 * Position the labels div so that:
985 * - its right edge is flush with the right edge of the charting area
986 * - its top edge is flush with the top edge of the charting area
989 Dygraph
.prototype.positionLabelsDiv_
= function() {
990 // Don't touch a user-specified labelsDiv.
991 if (this.user_attrs_
.hasOwnProperty("labelsDiv")) return;
993 var area
= this.plotter_
.area
;
994 var div
= this.attr_("labelsDiv");
995 div
.style
.left
= area
.x
+ area
.w
- this.attr_("labelsDivWidth") - 1 + "px";
996 div
.style
.top
= area
.y
+ "px";
1000 * Create the text box to adjust the averaging period
1003 Dygraph
.prototype.createRollInterface_
= function() {
1004 // Create a roller if one doesn't exist already.
1005 if (!this.roller_
) {
1006 this.roller_
= document
.createElement("input");
1007 this.roller_
.type
= "text";
1008 this.roller_
.style
.display
= "none";
1009 this.graphDiv
.appendChild(this.roller_
);
1012 var display
= this.attr_('showRoller') ? 'block' : 'none';
1014 var area
= this.plotter_
.area
;
1015 var textAttr
= { "position": "absolute",
1017 "top": (area
.y
+ area
.h
- 25) + "px",
1018 "left": (area
.x
+ 1) + "px",
1021 this.roller_
.size
= "2";
1022 this.roller_
.value
= this.rollPeriod_
;
1023 for (var name
in textAttr
) {
1024 if (textAttr
.hasOwnProperty(name
)) {
1025 this.roller_
.style
[name
] = textAttr
[name
];
1030 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1035 * Returns the x-coordinate of the event in a coordinate system where the
1036 * top-left corner of the page (not the window) is (0,0).
1037 * Taken from MochiKit.Signal
1039 Dygraph
.pageX
= function(e
) {
1041 return (!e
.pageX
|| e
.pageX
< 0) ? 0 : e
.pageX
;
1044 var b
= document
.body
;
1046 (de
.scrollLeft
|| b
.scrollLeft
) -
1047 (de
.clientLeft
|| 0);
1053 * Returns the y-coordinate of the event in a coordinate system where the
1054 * top-left corner of the page (not the window) is (0,0).
1055 * Taken from MochiKit.Signal
1057 Dygraph
.pageY
= function(e
) {
1059 return (!e
.pageY
|| e
.pageY
< 0) ? 0 : e
.pageY
;
1062 var b
= document
.body
;
1064 (de
.scrollTop
|| b
.scrollTop
) -
1065 (de
.clientTop
|| 0);
1071 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1072 * canvas (i.e. DOM Coords).
1074 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1075 return Dygraph
.pageX(e
) - context
.px
1080 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1081 * canvas (i.e. DOM Coords).
1083 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1084 return Dygraph
.pageY(e
) - context
.py
1088 * A collection of functions to facilitate build custom interaction models.
1091 Dygraph
.Interaction
= {};
1094 * Called in response to an interaction model operation that
1095 * should start the default panning behavior.
1097 * It's used in the default callback for "mousedown" operations.
1098 * Custom interaction model builders can use it to provide the default
1101 * @param { Event } event the event object which led to the startPan call.
1102 * @param { Dygraph} g The dygraph on which to act.
1103 * @param { Object} context The dragging context object (with
1104 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1106 Dygraph
.Interaction
.startPan
= function(event
, g
, context
) {
1107 context
.isPanning
= true;
1108 var xRange
= g
.xAxisRange();
1109 context
.dateRange
= xRange
[1] - xRange
[0];
1110 context
.initialLeftmostDate
= xRange
[0];
1111 context
.xUnitsPerPixel
= context
.dateRange
/ (g
.plotter_
.area
.w
- 1);
1113 if (g
.attr_("panEdgeFraction")) {
1114 var maxXPixelsToDraw
= g
.width_
* g
.attr_("panEdgeFraction");
1115 var xExtremes
= g
.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes!
1117 var boundedLeftX
= g
.toDomXCoord(xExtremes
[0]) - maxXPixelsToDraw
;
1118 var boundedRightX
= g
.toDomXCoord(xExtremes
[1]) + maxXPixelsToDraw
;
1120 var boundedLeftDate
= g
.toDataXCoord(boundedLeftX
);
1121 var boundedRightDate
= g
.toDataXCoord(boundedRightX
);
1122 context
.boundedDates
= [boundedLeftDate
, boundedRightDate
];
1124 var boundedValues
= [];
1125 var maxYPixelsToDraw
= g
.height_
* g
.attr_("panEdgeFraction");
1127 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
1128 var axis
= g
.axes_
[i
];
1129 var yExtremes
= axis
.extremeRange
;
1131 var boundedTopY
= g
.toDomYCoord(yExtremes
[0], i
) + maxYPixelsToDraw
;
1132 var boundedBottomY
= g
.toDomYCoord(yExtremes
[1], i
) - maxYPixelsToDraw
;
1134 var boundedTopValue
= g
.toDataYCoord(boundedTopY
);
1135 var boundedBottomValue
= g
.toDataYCoord(boundedBottomY
);
1137 boundedValues
[i
] = [boundedTopValue
, boundedBottomValue
];
1139 context
.boundedValues
= boundedValues
;
1142 // Record the range of each y-axis at the start of the drag.
1143 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
1144 context
.is2DPan
= false;
1145 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
1146 var axis
= g
.axes_
[i
];
1147 var yRange
= g
.yAxisRange(i
);
1148 // TODO(konigsberg): These values should be in |context|.
1149 // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
1150 if (axis
.logscale
) {
1151 axis
.initialTopValue
= Dygraph
.log10(yRange
[1]);
1152 axis
.dragValueRange
= Dygraph
.log10(yRange
[1]) - Dygraph
.log10(yRange
[0]);
1154 axis
.initialTopValue
= yRange
[1];
1155 axis
.dragValueRange
= yRange
[1] - yRange
[0];
1157 axis
.unitsPerPixel
= axis
.dragValueRange
/ (g
.plotter_
.area
.h
- 1);
1159 // While calculating axes, set 2dpan.
1160 if (axis
.valueWindow
|| axis
.valueRange
) context
.is2DPan
= true;
1165 * Called in response to an interaction model operation that
1166 * responds to an event that pans the view.
1168 * It's used in the default callback for "mousemove" operations.
1169 * Custom interaction model builders can use it to provide the default
1172 * @param { Event } event the event object which led to the movePan call.
1173 * @param { Dygraph} g The dygraph on which to act.
1174 * @param { Object} context The dragging context object (with
1175 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1177 Dygraph
.Interaction
.movePan
= function(event
, g
, context
) {
1178 context
.dragEndX
= g
.dragGetX_(event
, context
);
1179 context
.dragEndY
= g
.dragGetY_(event
, context
);
1181 var minDate
= context
.initialLeftmostDate
-
1182 (context
.dragEndX
- context
.dragStartX
) * context
.xUnitsPerPixel
;
1183 if (context
.boundedDates
) {
1184 minDate
= Math
.max(minDate
, context
.boundedDates
[0]);
1186 var maxDate
= minDate
+ context
.dateRange
;
1187 if (context
.boundedDates
) {
1188 if (maxDate
> context
.boundedDates
[1]) {
1189 // Adjust minDate, and recompute maxDate.
1190 minDate
= minDate
- (maxDate
- context
.boundedDates
[1]);
1191 maxDate
= minDate
+ context
.dateRange
;
1195 g
.dateWindow_
= [minDate
, maxDate
];
1197 // y-axis scaling is automatic unless this is a full 2D pan.
1198 if (context
.is2DPan
) {
1199 // Adjust each axis appropriately.
1200 for (var i
= 0; i
< g
.axes_
.length
; i
++) {
1201 var axis
= g
.axes_
[i
];
1203 var pixelsDragged
= context
.dragEndY
- context
.dragStartY
;
1204 var unitsDragged
= pixelsDragged
* axis
.unitsPerPixel
;
1206 var boundedValue
= context
.boundedValues
? context
.boundedValues
[i
] : null;
1208 // In log scale, maxValue and minValue are the logs of those values.
1209 var maxValue
= axis
.initialTopValue
+ unitsDragged
;
1211 maxValue
= Math
.min(maxValue
, boundedValue
[1]);
1213 var minValue
= maxValue
- axis
.dragValueRange
;
1215 if (minValue
< boundedValue
[0]) {
1216 // Adjust maxValue, and recompute minValue.
1217 maxValue
= maxValue
- (minValue
- boundedValue
[0]);
1218 minValue
= maxValue
- axis
.dragValueRange
;
1221 if (axis
.logscale
) {
1222 axis
.valueWindow
= [ Math
.pow(Dygraph
.LOG_SCALE
, minValue
),
1223 Math
.pow(Dygraph
.LOG_SCALE
, maxValue
) ];
1225 axis
.valueWindow
= [ minValue
, maxValue
];
1234 * Called in response to an interaction model operation that
1235 * responds to an event that ends panning.
1237 * It's used in the default callback for "mouseup" operations.
1238 * Custom interaction model builders can use it to provide the default
1241 * @param { Event } event the event object which led to the startZoom call.
1242 * @param { Dygraph} g The dygraph on which to act.
1243 * @param { Object} context The dragging context object (with
1244 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1246 Dygraph
.Interaction
.endPan
= function(event
, g
, context
) {
1247 // TODO(konigsberg): Clear the context data from the axis.
1248 // TODO(konigsberg): mouseup should just delete the
1249 // context object, and mousedown should create a new one.
1250 context
.isPanning
= false;
1251 context
.is2DPan
= false;
1252 context
.initialLeftmostDate
= null;
1253 context
.dateRange
= null;
1254 context
.valueRange
= null;
1255 context
.boundedDates
= null;
1256 context
.boundedValues
= null;
1260 * Called in response to an interaction model operation that
1261 * responds to an event that starts zooming.
1263 * It's used in the default callback for "mousedown" operations.
1264 * Custom interaction model builders can use it to provide the default
1267 * @param { Event } event the event object which led to the startZoom call.
1268 * @param { Dygraph} g The dygraph on which to act.
1269 * @param { Object} context The dragging context object (with
1270 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1272 Dygraph
.Interaction
.startZoom
= function(event
, g
, context
) {
1273 context
.isZooming
= true;
1277 * Called in response to an interaction model operation that
1278 * responds to an event that defines zoom boundaries.
1280 * It's used in the default callback for "mousemove" operations.
1281 * Custom interaction model builders can use it to provide the default
1284 * @param { Event } event the event object which led to the moveZoom call.
1285 * @param { Dygraph} g The dygraph on which to act.
1286 * @param { Object} context The dragging context object (with
1287 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1289 Dygraph
.Interaction
.moveZoom
= function(event
, g
, context
) {
1290 context
.dragEndX
= g
.dragGetX_(event
, context
);
1291 context
.dragEndY
= g
.dragGetY_(event
, context
);
1293 var xDelta
= Math
.abs(context
.dragStartX
- context
.dragEndX
);
1294 var yDelta
= Math
.abs(context
.dragStartY
- context
.dragEndY
);
1296 // drag direction threshold for y axis is twice as large as x axis
1297 context
.dragDirection
= (xDelta
< yDelta
/ 2) ? Dygraph
.VERTICAL
: Dygraph
.HORIZONTAL
;
1300 context
.dragDirection
,
1305 context
.prevDragDirection
,
1309 context
.prevEndX
= context
.dragEndX
;
1310 context
.prevEndY
= context
.dragEndY
;
1311 context
.prevDragDirection
= context
.dragDirection
;
1315 * Called in response to an interaction model operation that
1316 * responds to an event that performs a zoom based on previously defined
1319 * It's used in the default callback for "mouseup" operations.
1320 * Custom interaction model builders can use it to provide the default
1323 * @param { Event } event the event object which led to the endZoom call.
1324 * @param { Dygraph} g The dygraph on which to end the zoom.
1325 * @param { Object} context The dragging context object (with
1326 * dragStartX/dragStartY/etc. properties). This function modifies the context.
1328 Dygraph
.Interaction
.endZoom
= function(event
, g
, context
) {
1329 // TODO(konigsberg): Refactor or rename this fn -- it deals with clicks, too.
1330 context
.isZooming
= false;
1331 context
.dragEndX
= g
.dragGetX_(event
, context
);
1332 context
.dragEndY
= g
.dragGetY_(event
, context
);
1333 var regionWidth
= Math
.abs(context
.dragEndX
- context
.dragStartX
);
1334 var regionHeight
= Math
.abs(context
.dragEndY
- context
.dragStartY
);
1336 if (regionWidth
< 2 && regionHeight
< 2 &&
1337 g
.lastx_
!= undefined
&& g
.lastx_
!= -1) {
1338 // TODO(danvk): pass along more info about the points, e.g. 'x'
1339 if (g
.attr_('clickCallback') != null) {
1340 g
.attr_('clickCallback')(event
, g
.lastx_
, g
.selPoints_
);
1342 if (g
.attr_('pointClickCallback')) {
1343 // check if the click was on a particular point.
1344 var closestIdx
= -1;
1345 var closestDistance
= 0;
1346 for (var i
= 0; i
< g
.selPoints_
.length
; i
++) {
1347 var p
= g
.selPoints_
[i
];
1348 var distance
= Math
.pow(p
.canvasx
- context
.dragEndX
, 2) +
1349 Math
.pow(p
.canvasy
- context
.dragEndY
, 2);
1350 if (closestIdx
== -1 || distance
< closestDistance
) {
1351 closestDistance
= distance
;
1356 // Allow any click within two pixels of the dot.
1357 var radius
= g
.attr_('highlightCircleSize') + 2;
1358 if (closestDistance
<= 5 * 5) {
1359 g
.attr_('pointClickCallback')(event
, g
.selPoints_
[closestIdx
]);
1364 if (regionWidth
>= 10 && context
.dragDirection
== Dygraph
.HORIZONTAL
) {
1365 g
.doZoomX_(Math
.min(context
.dragStartX
, context
.dragEndX
),
1366 Math
.max(context
.dragStartX
, context
.dragEndX
));
1367 } else if (regionHeight
>= 10 && context
.dragDirection
== Dygraph
.VERTICAL
) {
1368 g
.doZoomY_(Math
.min(context
.dragStartY
, context
.dragEndY
),
1369 Math
.max(context
.dragStartY
, context
.dragEndY
));
1371 g
.canvas_ctx_
.clearRect(0, 0, g
.canvas_
.width
, g
.canvas_
.height
);
1373 context
.dragStartX
= null;
1374 context
.dragStartY
= null;
1378 * Default interation model for dygraphs. You can refer to specific elements of
1379 * this when constructing your own interaction model, e.g.:
1380 * g.updateOptions( {
1381 * interactionModel: {
1382 * mousedown: Dygraph.defaultInteractionModel.mousedown
1386 Dygraph
.Interaction
.defaultModel
= {
1387 // Track the beginning of drag events
1388 mousedown
: function(event
, g
, context
) {
1389 context
.initializeMouseDown(event
, g
, context
);
1391 if (event
.altKey
|| event
.shiftKey
) {
1392 Dygraph
.startPan(event
, g
, context
);
1394 Dygraph
.startZoom(event
, g
, context
);
1398 // Draw zoom rectangles when the mouse is down and the user moves around
1399 mousemove
: function(event
, g
, context
) {
1400 if (context
.isZooming
) {
1401 Dygraph
.moveZoom(event
, g
, context
);
1402 } else if (context
.isPanning
) {
1403 Dygraph
.movePan(event
, g
, context
);
1407 mouseup
: function(event
, g
, context
) {
1408 if (context
.isZooming
) {
1409 Dygraph
.endZoom(event
, g
, context
);
1410 } else if (context
.isPanning
) {
1411 Dygraph
.endPan(event
, g
, context
);
1415 // Temporarily cancel the dragging event when the mouse leaves the graph
1416 mouseout
: function(event
, g
, context
) {
1417 if (context
.isZooming
) {
1418 context
.dragEndX
= null;
1419 context
.dragEndY
= null;
1423 // Disable zooming out if panning.
1424 dblclick
: function(event
, g
, context
) {
1425 if (event
.altKey
|| event
.shiftKey
) {
1428 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1429 // friendlier to public use.
1434 Dygraph
.DEFAULT_ATTRS
.interactionModel
= Dygraph
.Interaction
.defaultModel
;
1436 // old ways of accessing these methods/properties
1437 Dygraph
.defaultInteractionModel
= Dygraph
.Interaction
.defaultModel
;
1438 Dygraph
.endZoom
= Dygraph
.Interaction
.endZoom
;
1439 Dygraph
.moveZoom
= Dygraph
.Interaction
.moveZoom
;
1440 Dygraph
.startZoom
= Dygraph
.Interaction
.startZoom
;
1441 Dygraph
.endPan
= Dygraph
.Interaction
.endPan
;
1442 Dygraph
.movePan
= Dygraph
.Interaction
.movePan
;
1443 Dygraph
.startPan
= Dygraph
.Interaction
.startPan
;
1446 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1450 Dygraph
.prototype.createDragInterface_
= function() {
1452 // Tracks whether the mouse is down right now
1454 isPanning
: false, // is this drag part of a pan?
1455 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1460 dragDirection
: null,
1463 prevDragDirection
: null,
1465 // The value on the left side of the graph when a pan operation starts.
1466 initialLeftmostDate
: null,
1468 // The number of units each pixel spans. (This won't be valid for log
1470 xUnitsPerPixel
: null,
1472 // TODO(danvk): update this comment
1473 // The range in second/value units that the viewport encompasses during a
1474 // panning operation.
1477 // Utility function to convert page-wide coordinates to canvas coords
1481 // Values for use with panEdgeFraction, which limit how far outside the
1482 // graph's data boundaries it can be panned.
1483 boundedDates
: null, // [minDate, maxDate]
1484 boundedValues
: null, // [[minValue, maxValue] ...]
1486 initializeMouseDown
: function(event
, g
, context
) {
1487 // prevents mouse drags from selecting page text.
1488 if (event
.preventDefault
) {
1489 event
.preventDefault(); // Firefox, Chrome, etc.
1491 event
.returnValue
= false; // IE
1492 event
.cancelBubble
= true;
1495 context
.px
= Dygraph
.findPosX(g
.canvas_
);
1496 context
.py
= Dygraph
.findPosY(g
.canvas_
);
1497 context
.dragStartX
= g
.dragGetX_(event
, context
);
1498 context
.dragStartY
= g
.dragGetY_(event
, context
);
1502 var interactionModel
= this.attr_("interactionModel");
1504 // Self is the graph.
1507 // Function that binds the graph and context to the handler.
1508 var bindHandler
= function(handler
) {
1509 return function(event
) {
1510 handler(event
, self
, context
);
1514 for (var eventName
in interactionModel
) {
1515 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1516 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
1517 bindHandler(interactionModel
[eventName
]));
1520 // If the user releases the mouse button during a drag, but not over the
1521 // canvas, then it doesn't count as a zooming action.
1522 Dygraph
.addEvent(document
, 'mouseup', function(event
) {
1523 if (context
.isZooming
|| context
.isPanning
) {
1524 context
.isZooming
= false;
1525 context
.dragStartX
= null;
1526 context
.dragStartY
= null;
1529 if (context
.isPanning
) {
1530 context
.isPanning
= false;
1531 context
.draggingDate
= null;
1532 context
.dateRange
= null;
1533 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1534 delete self
.axes_
[i
].draggingValue
;
1535 delete self
.axes_
[i
].dragValueRange
;
1543 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1544 * up any previous zoom rectangles that were drawn. This could be optimized to
1545 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1548 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1549 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1550 * @param {Number} startX The X position where the drag started, in canvas
1552 * @param {Number} endX The current X position of the drag, in canvas coords.
1553 * @param {Number} startY The Y position where the drag started, in canvas
1555 * @param {Number} endY The current Y position of the drag, in canvas coords.
1556 * @param {Number} prevDirection the value of direction on the previous call to
1557 * this function. Used to avoid excess redrawing
1558 * @param {Number} prevEndX The value of endX on the previous call to this
1559 * function. Used to avoid excess redrawing
1560 * @param {Number} prevEndY The value of endY on the previous call to this
1561 * function. Used to avoid excess redrawing
1564 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1565 endY
, prevDirection
, prevEndX
,
1567 var ctx
= this.canvas_ctx_
;
1569 // Clean up from the previous rect if necessary
1570 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1571 ctx
.clearRect(Math
.min(startX
, prevEndX
), 0,
1572 Math
.abs(startX
- prevEndX
), this.height_
);
1573 } else if (prevDirection
== Dygraph
.VERTICAL
){
1574 ctx
.clearRect(0, Math
.min(startY
, prevEndY
),
1575 this.width_
, Math
.abs(startY
- prevEndY
));
1578 // Draw a light-grey rectangle to show the new viewing area
1579 if (direction
== Dygraph
.HORIZONTAL
) {
1580 if (endX
&& startX
) {
1581 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1582 ctx
.fillRect(Math
.min(startX
, endX
), 0,
1583 Math
.abs(endX
- startX
), this.height_
);
1586 if (direction
== Dygraph
.VERTICAL
) {
1587 if (endY
&& startY
) {
1588 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1589 ctx
.fillRect(0, Math
.min(startY
, endY
),
1590 this.width_
, Math
.abs(endY
- startY
));
1596 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1597 * the canvas. The exact zoom window may be slightly larger if there are no data
1598 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1599 * which accepts dates that match the raw data. This function redraws the graph.
1601 * @param {Number} lowX The leftmost pixel value that should be visible.
1602 * @param {Number} highX The rightmost pixel value that should be visible.
1605 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1606 // Find the earliest and latest dates contained in this canvasx range.
1607 // Convert the call to date ranges of the raw data.
1608 var minDate
= this.toDataXCoord(lowX
);
1609 var maxDate
= this.toDataXCoord(highX
);
1610 this.doZoomXDates_(minDate
, maxDate
);
1614 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1615 * method with doZoomX which accepts pixel coordinates. This function redraws
1618 * @param {Number} minDate The minimum date that should be visible.
1619 * @param {Number} maxDate The maximum date that should be visible.
1622 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1623 this.dateWindow_
= [minDate
, maxDate
];
1624 this.zoomed_x_
= true;
1626 if (this.attr_("zoomCallback")) {
1627 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1632 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1633 * the canvas. This function redraws the graph.
1635 * @param {Number} lowY The topmost pixel value that should be visible.
1636 * @param {Number} highY The lowest pixel value that should be visible.
1639 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1640 // Find the highest and lowest values in pixel range for each axis.
1641 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1642 // This is because pixels increase as you go down on the screen, whereas data
1643 // coordinates increase as you go up the screen.
1644 var valueRanges
= [];
1645 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1646 var hi
= this.toDataYCoord(lowY
, i
);
1647 var low
= this.toDataYCoord(highY
, i
);
1648 this.axes_
[i
].valueWindow
= [low
, hi
];
1649 valueRanges
.push([low
, hi
]);
1652 this.zoomed_y_
= true;
1654 if (this.attr_("zoomCallback")) {
1655 var xRange
= this.xAxisRange();
1656 var yRange
= this.yAxisRange();
1657 this.attr_("zoomCallback")(xRange
[0], xRange
[1], this.yAxisRanges());
1662 * Reset the zoom to the original view coordinates. This is the same as
1663 * double-clicking on the graph.
1667 Dygraph
.prototype.doUnzoom_
= function() {
1669 if (this.dateWindow_
!= null) {
1671 this.dateWindow_
= null;
1674 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1675 if (this.axes_
[i
].valueWindow
!= null) {
1677 delete this.axes_
[i
].valueWindow
;
1681 // Clear any selection, since it's likely to be drawn in the wrong place.
1682 this.clearSelection();
1685 // Putting the drawing operation before the callback because it resets
1687 this.zoomed_x_
= false;
1688 this.zoomed_y_
= false;
1690 if (this.attr_("zoomCallback")) {
1691 var minDate
= this.rawData_
[0][0];
1692 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1693 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1699 * When the mouse moves in the canvas, display information about a nearby data
1700 * point and draw dots over those points in the data series. This function
1701 * takes care of cleanup of previously-drawn dots.
1702 * @param {Object} event The mousemove event from the browser.
1705 Dygraph
.prototype.mouseMove_
= function(event
) {
1706 // This prevents JS errors when mousing over the canvas before data loads.
1707 var points
= this.layout_
.points
;
1708 if (points
=== undefined
) return;
1710 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1715 // Loop through all the points and find the date nearest to our current
1717 var minDist
= 1e+100;
1719 for (var i
= 0; i
< points
.length
; i
++) {
1720 var point
= points
[i
];
1721 if (point
== null) continue;
1722 var dist
= Math
.abs(point
.canvasx
- canvasx
);
1723 if (dist
> minDist
) continue;
1727 if (idx
>= 0) lastx
= points
[idx
].xval
;
1729 // Extract the points we've selected
1730 this.selPoints_
= [];
1731 var l
= points
.length
;
1732 if (!this.attr_("stackedGraph")) {
1733 for (var i
= 0; i
< l
; i
++) {
1734 if (points
[i
].xval
== lastx
) {
1735 this.selPoints_
.push(points
[i
]);
1739 // Need to 'unstack' points starting from the bottom
1740 var cumulative_sum
= 0;
1741 for (var i
= l
- 1; i
>= 0; i
--) {
1742 if (points
[i
].xval
== lastx
) {
1743 var p
= {}; // Clone the point since we modify it
1744 for (var k
in points
[i
]) {
1745 p
[k
] = points
[i
][k
];
1747 p
.yval
-= cumulative_sum
;
1748 cumulative_sum
+= p
.yval
;
1749 this.selPoints_
.push(p
);
1752 this.selPoints_
.reverse();
1755 if (this.attr_("highlightCallback")) {
1756 var px
= this.lastx_
;
1757 if (px
!== null && lastx
!= px
) {
1758 // only fire if the selected point has changed.
1759 this.attr_("highlightCallback")(event
, lastx
, this.selPoints_
, this.idxToRow_(idx
));
1763 // Save last x position for callbacks.
1764 this.lastx_
= lastx
;
1766 this.updateSelection_();
1770 * Transforms layout_.points index into data row number.
1771 * @param int layout_.points index
1772 * @return int row number, or -1 if none could be found.
1775 Dygraph
.prototype.idxToRow_
= function(idx
) {
1776 if (idx
< 0) return -1;
1778 for (var i
in this.layout_
.datasets
) {
1779 if (idx
< this.layout_
.datasets
[i
].length
) {
1780 return this.boundaryIds_
[0][0]+idx
;
1782 idx
-= this.layout_
.datasets
[i
].length
;
1789 * @param { Number } x The number to consider.
1790 * @return { Boolean } Whether the number is zero or NaN.
1792 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
1793 Dygraph
.isOK
= function(x
) {
1794 return x
&& !isNaN(x
);
1799 * Generates HTML for the legend which is displayed when hovering over the
1800 * chart. If no selected points are specified, a default legend is returned
1801 * (this may just be the empty string).
1802 * @param { Number } [x] The x-value of the selected points.
1803 * @param { [Object] } [sel_points] List of selected points for the given
1804 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1806 Dygraph
.prototype.generateLegendHTML_
= function(x
, sel_points
) {
1807 // If no points are selected, we display a default legend. Traditionally,
1808 // this has been blank. But a better default would be a conventional legend,
1809 // which provides essential information for a non-interactive chart.
1810 if (typeof(x
) === 'undefined') {
1811 if (this.attr_('legend') != 'always') return '';
1813 var sepLines
= this.attr_('labelsSeparateLines');
1814 var labels
= this.attr_('labels');
1816 for (var i
= 1; i
< labels
.length
; i
++) {
1817 if (!this.visibility()[i
- 1]) continue;
1818 var c
= this.plotter_
.colors
[labels
[i
]];
1819 if (html
!= '') html
+= (sepLines
? '<br/>' : ' ');
1820 html
+= "<b><span style='color: " + c
+ ";'>—" + labels
[i
] +
1826 var html
= this.attr_('xValueFormatter')(x
) + ":";
1828 var fmtFunc
= this.attr_('yValueFormatter');
1829 var showZeros
= this.attr_("labelsShowZeroValues");
1830 var sepLines
= this.attr_("labelsSeparateLines");
1831 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1832 var pt
= this.selPoints_
[i
];
1833 if (pt
.yval
== 0 && !showZeros
) continue;
1834 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1835 if (sepLines
) html
+= "<br/>";
1837 var c
= this.plotter_
.colors
[pt
.name
];
1838 var yval
= fmtFunc(pt
.yval
, this);
1839 // TODO(danvk): use a template string here and make it an attribute.
1840 html
+= " <b><span style='color: " + c
+ ";'>"
1841 + pt
.name
+ "</span></b>:"
1849 * Displays information about the selected points in the legend. If there is no
1850 * selection, the legend will be cleared.
1851 * @param { Number } [x] The x-value of the selected points.
1852 * @param { [Object] } [sel_points] List of selected points for the given
1853 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1855 Dygraph
.prototype.setLegendHTML_
= function(x
, sel_points
) {
1856 var html
= this.generateLegendHTML_(x
, sel_points
);
1857 var labelsDiv
= this.attr_("labelsDiv");
1858 if (labelsDiv
!== null) {
1859 labelsDiv
.innerHTML
= html
;
1861 if (typeof(this.shown_legend_error_
) == 'undefined') {
1862 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1863 this.shown_legend_error_
= true;
1869 * Draw dots over the selectied points in the data series. This function
1870 * takes care of cleanup of previously-drawn dots.
1873 Dygraph
.prototype.updateSelection_
= function() {
1874 // Clear the previously drawn vertical, if there is one
1875 var ctx
= this.canvas_ctx_
;
1876 if (this.previousVerticalX_
>= 0) {
1877 // Determine the maximum highlight circle size.
1878 var maxCircleSize
= 0;
1879 var labels
= this.attr_('labels');
1880 for (var i
= 1; i
< labels
.length
; i
++) {
1881 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1882 if (r
> maxCircleSize
) maxCircleSize
= r
;
1884 var px
= this.previousVerticalX_
;
1885 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1886 2 * maxCircleSize
+ 2, this.height_
);
1889 if (this.selPoints_
.length
> 0) {
1890 // Set the status message to indicate the selected point(s)
1891 if (this.attr_('showLabelsOnHighlight')) {
1892 this.setLegendHTML_(this.lastx_
, this.selPoints_
);
1895 // Draw colored circles over the center of each selected point
1896 var canvasx
= this.selPoints_
[0].canvasx
;
1898 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1899 var pt
= this.selPoints_
[i
];
1900 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1902 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1904 ctx
.fillStyle
= this.plotter_
.colors
[pt
.name
];
1905 ctx
.arc(canvasx
, pt
.canvasy
, circleSize
, 0, 2 * Math
.PI
, false);
1910 this.previousVerticalX_
= canvasx
;
1915 * Manually set the selected points and display information about them in the
1916 * legend. The selection can be cleared using clearSelection() and queried
1917 * using getSelection().
1918 * @param { Integer } row number that should be highlighted (i.e. appear with
1919 * hover dots on the chart). Set to false to clear any selection.
1921 Dygraph
.prototype.setSelection
= function(row
) {
1922 // Extract the points we've selected
1923 this.selPoints_
= [];
1926 if (row
!== false) {
1927 row
= row
-this.boundaryIds_
[0][0];
1930 if (row
!== false && row
>= 0) {
1931 for (var i
in this.layout_
.datasets
) {
1932 if (row
< this.layout_
.datasets
[i
].length
) {
1933 var point
= this.layout_
.points
[pos
+row
];
1935 if (this.attr_("stackedGraph")) {
1936 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
1939 this.selPoints_
.push(point
);
1941 pos
+= this.layout_
.datasets
[i
].length
;
1945 if (this.selPoints_
.length
) {
1946 this.lastx_
= this.selPoints_
[0].xval
;
1947 this.updateSelection_();
1949 this.clearSelection();
1955 * The mouse has left the canvas. Clear out whatever artifacts remain
1956 * @param {Object} event the mouseout event from the browser.
1959 Dygraph
.prototype.mouseOut_
= function(event
) {
1960 if (this.attr_("unhighlightCallback")) {
1961 this.attr_("unhighlightCallback")(event
);
1964 if (this.attr_("hideOverlayOnMouseOut")) {
1965 this.clearSelection();
1970 * Clears the current selection (i.e. points that were highlighted by moving
1971 * the mouse over the chart).
1973 Dygraph
.prototype.clearSelection
= function() {
1974 // Get rid of the overlay data
1975 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1976 this.setLegendHTML_();
1977 this.selPoints_
= [];
1982 * Returns the number of the currently selected row. To get data for this row,
1983 * you can use the getValue method.
1984 * @return { Integer } row number, or -1 if nothing is selected
1986 Dygraph
.prototype.getSelection
= function() {
1987 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1991 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
1992 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
1993 return row
+ this.boundaryIds_
[0][0];
2000 * Number formatting function which mimicks the behavior of %g in printf, i.e.
2001 * either exponential or fixed format (without trailing 0s) is used depending on
2002 * the length of the generated string. The advantage of this format is that
2003 * there is a predictable upper bound on the resulting string length,
2004 * significant figures are not dropped, and normal numbers are not displayed in
2005 * exponential notation.
2007 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
2008 * It creates strings which are too long for absolute values between 10^-4 and
2009 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
2012 * @param {Number} x The number to format
2013 * @param {Number} opt_precision The precision to use, default 2.
2014 * @return {String} A string formatted like %g in printf. The max generated
2015 * string length should be precision + 6 (e.g 1.123e+300).
2017 Dygraph
.floatFormat
= function(x
, opt_precision
) {
2018 // Avoid invalid precision values; [1, 21] is the valid range.
2019 var p
= Math
.min(Math
.max(1, opt_precision
|| 2), 21);
2021 // This is deceptively simple. The actual algorithm comes from:
2023 // Max allowed length = p + 4
2024 // where 4 comes from 'e+n' and '.'.
2026 // Length of fixed format = 2 + y + p
2027 // where 2 comes from '0.' and y = # of leading zeroes.
2029 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
2032 // Since the behavior of toPrecision() is identical for larger numbers, we
2033 // don't have to worry about the other bound.
2035 // Finally, the argument for toExponential() is the number of trailing digits,
2036 // so we take off 1 for the value before the '.'.
2037 return (Math
.abs(x
) < 1.0e-3 && x
!= 0.0) ?
2038 x
.toExponential(p
- 1) : x
.toPrecision(p
);
2043 * Return a string version of a number. This respects the digitsAfterDecimal
2044 * and maxNumberWidth options.
2045 * @param {Number} x The number to be formatted
2046 * @param {Dygraph} g The dygraph object
2048 Dygraph
.numberFormatter
= function(x
, g
) {
2049 var sigFigs
= g
.attr_('sigFigs');
2051 if (sigFigs
!== null) {
2052 // User has opted for a fixed number of significant figures.
2053 return Dygraph
.floatFormat(x
, sigFigs
);
2056 var digits
= g
.attr_('digitsAfterDecimal');
2057 var maxNumberWidth
= g
.attr_('maxNumberWidth');
2059 // switch to scientific notation if we underflow or overflow fixed display.
2061 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
2062 Math
.abs(x
) < Math
.pow(10, -digits
))) {
2063 return x
.toExponential(digits
);
2065 return '' + Dygraph
.round_(x
, digits
);
2071 * Converts '9' to '09' (useful for dates)
2073 Dygraph
.zeropad
= function(x
) {
2074 if (x
< 10) return "0" + x
; else return "" + x
;
2078 * Return a string version of the hours, minutes and seconds portion of a date.
2079 * @param {Number} date The JavaScript date (ms since epoch)
2080 * @return {String} A time of the form "HH:MM:SS"
2083 Dygraph
.hmsString_
= function(date
) {
2084 var zeropad
= Dygraph
.zeropad
;
2085 var d
= new Date(date
);
2086 if (d
.getSeconds()) {
2087 return zeropad(d
.getHours()) + ":" +
2088 zeropad(d
.getMinutes()) + ":" +
2089 zeropad(d
.getSeconds());
2091 return zeropad(d
.getHours()) + ":" + zeropad(d
.getMinutes());
2096 * Convert a JS date to a string appropriate to display on an axis that
2097 * is displaying values at the stated granularity.
2098 * @param {Date} date The date to format
2099 * @param {Number} granularity One of the Dygraph granularity constants
2100 * @return {String} The formatted date
2103 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
2104 if (granularity
>= Dygraph
.DECADAL
) {
2105 return date
.strftime('%Y');
2106 } else if (granularity
>= Dygraph
.MONTHLY
) {
2107 return date
.strftime('%b %y');
2109 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
2110 if (frac
== 0 || granularity
>= Dygraph
.DAILY
) {
2111 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
2113 return Dygraph
.hmsString_(date
.getTime());
2119 * Convert a JS date (millis since epoch) to YYYY/MM/DD
2120 * @param {Number} date The JavaScript date (ms since epoch)
2121 * @return {String} A date of the form "YYYY/MM/DD"
2124 Dygraph
.dateString_
= function(date
) {
2125 var zeropad
= Dygraph
.zeropad
;
2126 var d
= new Date(date
);
2129 var year
= "" + d
.getFullYear();
2130 // Get a 0 padded month string
2131 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
2132 // Get a 0 padded day string
2133 var day
= zeropad(d
.getDate());
2136 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
2137 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
2139 return year
+ "/" + month + "/" + day
+ ret
;
2143 * Round a number to the specified number of digits past the decimal point.
2144 * @param {Number} num The number to round
2145 * @param {Number} places The number of decimals to which to round
2146 * @return {Number} The rounded number
2149 Dygraph
.round_
= function(num
, places
) {
2150 var shift
= Math
.pow(10, places
);
2151 return Math
.round(num
* shift
)/shift
;
2155 * Fires when there's data available to be graphed.
2156 * @param {String} data Raw CSV data to be plotted
2159 Dygraph
.prototype.loadedEvent_
= function(data
) {
2160 this.rawData_
= this.parseCSV_(data
);
2164 Dygraph
.prototype.months
= ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
2165 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
2166 Dygraph
.prototype.quarters
= ["Jan", "Apr", "Jul", "Oct"];
2169 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2172 Dygraph
.prototype.addXTicks_
= function() {
2173 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2175 if (this.dateWindow_
) {
2176 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2178 range
= [this.rawData_
[0][0], this.rawData_
[this.rawData_
.length
- 1][0]];
2181 var xTicks
= this.attr_('xTicker')(range
[0], range
[1], this);
2182 this.layout_
.setXTicks(xTicks
);
2185 // Time granularity enumeration
2186 Dygraph
.SECONDLY
= 0;
2187 Dygraph
.TWO_SECONDLY
= 1;
2188 Dygraph
.FIVE_SECONDLY
= 2;
2189 Dygraph
.TEN_SECONDLY
= 3;
2190 Dygraph
.THIRTY_SECONDLY
= 4;
2191 Dygraph
.MINUTELY
= 5;
2192 Dygraph
.TWO_MINUTELY
= 6;
2193 Dygraph
.FIVE_MINUTELY
= 7;
2194 Dygraph
.TEN_MINUTELY
= 8;
2195 Dygraph
.THIRTY_MINUTELY
= 9;
2196 Dygraph
.HOURLY
= 10;
2197 Dygraph
.TWO_HOURLY
= 11;
2198 Dygraph
.SIX_HOURLY
= 12;
2200 Dygraph
.WEEKLY
= 14;
2201 Dygraph
.MONTHLY
= 15;
2202 Dygraph
.QUARTERLY
= 16;
2203 Dygraph
.BIANNUAL
= 17;
2204 Dygraph
.ANNUAL
= 18;
2205 Dygraph
.DECADAL
= 19;
2206 Dygraph
.CENTENNIAL
= 20;
2207 Dygraph
.NUM_GRANULARITIES
= 21;
2209 Dygraph
.SHORT_SPACINGS
= [];
2210 Dygraph
.SHORT_SPACINGS
[Dygraph
.SECONDLY
] = 1000 * 1;
2211 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_SECONDLY
] = 1000 * 2;
2212 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_SECONDLY
] = 1000 * 5;
2213 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_SECONDLY
] = 1000 * 10;
2214 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_SECONDLY
] = 1000 * 30;
2215 Dygraph
.SHORT_SPACINGS
[Dygraph
.MINUTELY
] = 1000 * 60;
2216 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_MINUTELY
] = 1000 * 60 * 2;
2217 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_MINUTELY
] = 1000 * 60 * 5;
2218 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_MINUTELY
] = 1000 * 60 * 10;
2219 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_MINUTELY
] = 1000 * 60 * 30;
2220 Dygraph
.SHORT_SPACINGS
[Dygraph
.HOURLY
] = 1000 * 3600;
2221 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_HOURLY
] = 1000 * 3600 * 2;
2222 Dygraph
.SHORT_SPACINGS
[Dygraph
.SIX_HOURLY
] = 1000 * 3600 * 6;
2223 Dygraph
.SHORT_SPACINGS
[Dygraph
.DAILY
] = 1000 * 86400;
2224 Dygraph
.SHORT_SPACINGS
[Dygraph
.WEEKLY
] = 1000 * 604800;
2228 * If we used this time granularity, how many ticks would there be?
2229 * This is only an approximation, but it's generally good enough.
2231 Dygraph
.prototype.NumXTicks
= function(start_time
, end_time
, granularity
) {
2232 if (granularity
< Dygraph
.MONTHLY
) {
2233 // Generate one tick mark for every fixed interval of time.
2234 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
2235 return Math
.floor(0.5 + 1.0 * (end_time
- start_time
) / spacing
);
2237 var year_mod
= 1; // e.g. to only print one point every 10 years.
2238 var num_months
= 12;
2239 if (granularity
== Dygraph
.QUARTERLY
) num_months
= 3;
2240 if (granularity
== Dygraph
.BIANNUAL
) num_months
= 2;
2241 if (granularity
== Dygraph
.ANNUAL
) num_months
= 1;
2242 if (granularity
== Dygraph
.DECADAL
) { num_months
= 1; year_mod
= 10; }
2243 if (granularity
== Dygraph
.CENTENNIAL
) { num_months
= 1; year_mod
= 100; }
2245 var msInYear
= 365.2524 * 24 * 3600 * 1000;
2246 var num_years
= 1.0 * (end_time
- start_time
) / msInYear
;
2247 return Math
.floor(0.5 + 1.0 * num_years
* num_months
/ year_mod
);
2254 * Construct an x-axis of nicely-formatted times on meaningful boundaries
2255 * (e.g. 'Jan 09' rather than 'Jan 22, 2009').
2257 * Returns an array containing {v: millis, label: label} dictionaries.
2259 Dygraph
.prototype.GetXAxis
= function(start_time
, end_time
, granularity
) {
2260 var formatter
= this.attr_("xAxisLabelFormatter");
2262 if (granularity
< Dygraph
.MONTHLY
) {
2263 // Generate one tick mark for every fixed interval of time.
2264 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
2265 var format
= '%d%b'; // e.g. "1Jan"
2267 // Find a time less than start_time which occurs on a "nice" time boundary
2268 // for this granularity.
2269 var g
= spacing
/ 1000;
2270 var d
= new Date(start_time
);
2271 if (g
<= 60) { // seconds
2272 var x
= d
.getSeconds(); d
.setSeconds(x
- x
% g
);
2276 if (g
<= 60) { // minutes
2277 var x
= d
.getMinutes(); d
.setMinutes(x
- x
% g
);
2282 if (g
<= 24) { // days
2283 var x
= d
.getHours(); d
.setHours(x
- x
% g
);
2288 if (g
== 7) { // one week
2289 d
.setDate(d
.getDate() - d
.getDay());
2294 start_time
= d
.getTime();
2296 for (var t
= start_time
; t
<= end_time
; t
+= spacing
) {
2297 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
2300 // Display a tick mark on the first of a set of months of each year.
2301 // Years get a tick mark iff y % year_mod == 0. This is useful for
2302 // displaying a tick mark once every 10 years, say, on long time scales.
2304 var year_mod
= 1; // e.g. to only print one point every 10 years.
2306 if (granularity
== Dygraph
.MONTHLY
) {
2307 months
= [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
2308 } else if (granularity
== Dygraph
.QUARTERLY
) {
2309 months
= [ 0, 3, 6, 9 ];
2310 } else if (granularity
== Dygraph
.BIANNUAL
) {
2312 } else if (granularity
== Dygraph
.ANNUAL
) {
2314 } else if (granularity
== Dygraph
.DECADAL
) {
2317 } else if (granularity
== Dygraph
.CENTENNIAL
) {
2321 this.warn("Span of dates is too long");
2324 var start_year
= new Date(start_time
).getFullYear();
2325 var end_year
= new Date(end_time
).getFullYear();
2326 var zeropad
= Dygraph
.zeropad
;
2327 for (var i
= start_year
; i
<= end_year
; i
++) {
2328 if (i
% year_mod
!= 0) continue;
2329 for (var j
= 0; j
< months
.length
; j
++) {
2330 var date_str
= i
+ "/" + zeropad(1 + months[j]) + "/01";
2331 var t
= Dygraph
.dateStrToMillis(date_str
);
2332 if (t
< start_time
|| t
> end_time
) continue;
2333 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
2343 * Add ticks to the x-axis based on a date range.
2344 * @param {Number} startDate Start of the date window (millis since epoch)
2345 * @param {Number} endDate End of the date window (millis since epoch)
2346 * @param {Dygraph} self The dygraph object
2347 * @return { [Object] } Array of {label, value} tuples.
2350 Dygraph
.dateTicker
= function(startDate
, endDate
, self
) {
2351 // TODO(danvk): why does this take 'self' as a param?
2353 for (var i
= 0; i
< Dygraph
.NUM_GRANULARITIES
; i
++) {
2354 var num_ticks
= self
.NumXTicks(startDate
, endDate
, i
);
2355 if (self
.width_
/ num_ticks
>= self
.attr_('pixelsPerXLabel')) {
2362 return self
.GetXAxis(startDate
, endDate
, chosen
);
2364 // TODO(danvk): signal error.
2370 * This is a list of human-friendly values at which to show tick marks on a log
2371 * scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
2372 * ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
2373 * NOTE: this assumes that Dygraph.LOG_SCALE = 10.
2375 Dygraph
.PREFERRED_LOG_TICK_VALUES
= function() {
2377 for (var power
= -39; power
<= 39; power
++) {
2378 var range
= Math
.pow(10, power
);
2379 for (var mult
= 1; mult
<= 9; mult
++) {
2380 var val
= range
* mult
;
2389 * Implementation of binary search over an array.
2390 * Currently does not work when val is outside the range of arry's values.
2391 * @param { Integer } val the value to search for
2392 * @param { Integer[] } arry is the value over which to search
2393 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
2394 * If abs < 0, find the highest entry less than val.
2395 * if abs == 0, find the entry that equals val.
2396 * @param { Integer } [low] The first index in arry to consider (optional)
2397 * @param { Integer } [high] The last index in arry to consider (optional)
2399 Dygraph
.binarySearch
= function(val
, arry
, abs
, low
, high
) {
2400 if (low
== null || high
== null) {
2402 high
= arry
.length
- 1;
2410 var validIndex
= function(idx
) {
2411 return idx
>= 0 && idx
< arry
.length
;
2413 var mid
= parseInt((low
+ high
) / 2);
2414 var element
= arry
[mid
];
2415 if (element
== val
) {
2418 if (element
> val
) {
2420 // Accept if element > val, but also if prior element < val.
2422 if (validIndex(idx
) && arry
[idx
] < val
) {
2426 return Dygraph
.binarySearch(val
, arry
, abs
, low
, mid
- 1);
2428 if (element
< val
) {
2430 // Accept if element < val, but also if prior element > val.
2432 if (validIndex(idx
) && arry
[idx
] > val
) {
2436 return Dygraph
.binarySearch(val
, arry
, abs
, mid
+ 1, high
);
2440 // TODO(konigsberg): Update comment.
2442 * Add ticks when the x axis has numbers on it (instead of dates)
2444 * @param {Number} minV minimum value
2445 * @param {Number} maxV maximum value
2447 * @param {function} attribute accessor function.
2448 * @return {[Object]} Array of {label, value} tuples.
2450 Dygraph
.numericTicks
= function(minV
, maxV
, self
, axis_props
, vals
) {
2451 var attr
= function(k
) {
2452 if (axis_props
&& axis_props
.hasOwnProperty(k
)) return axis_props
[k
];
2453 return self
.attr_(k
);
2458 for (var i
= 0; i
< vals
.length
; i
++) {
2459 ticks
.push({v
: vals
[i
]});
2462 if (axis_props
&& attr("logscale")) {
2463 var pixelsPerTick
= attr('pixelsPerYLabel');
2464 // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
2465 var nTicks
= Math
.floor(self
.height_
/ pixelsPerTick
);
2466 var minIdx
= Dygraph
.binarySearch(minV
, Dygraph
.PREFERRED_LOG_TICK_VALUES
, 1);
2467 var maxIdx
= Dygraph
.binarySearch(maxV
, Dygraph
.PREFERRED_LOG_TICK_VALUES
, -1);
2472 maxIdx
= Dygraph
.PREFERRED_LOG_TICK_VALUES
.length
- 1;
2474 // Count the number of tick values would appear, if we can get at least
2475 // nTicks / 4 accept them
.
2476 var lastDisplayed
= null;
2477 if (maxIdx
- minIdx
>= nTicks
/ 4) {
2478 var axisId
= axis_props
.yAxisId
;
2479 for (var idx
= maxIdx
; idx
>= minIdx
; idx
--) {
2480 var tickValue
= Dygraph
.PREFERRED_LOG_TICK_VALUES
[idx
];
2481 var domCoord
= axis_props
.g
.toDomYCoord(tickValue
, axisId
);
2482 var tick
= { v
: tickValue
};
2483 if (lastDisplayed
== null) {
2485 tickValue
: tickValue
,
2489 if (domCoord
- lastDisplayed
.domCoord
>= pixelsPerTick
) {
2491 tickValue
: tickValue
,
2500 // Since we went in backwards order.
2505 // ticks.length won't be 0 if the log scale function finds values to insert.
2506 if (ticks
.length
== 0) {
2508 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
2509 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks
).
2510 // The first spacing greater than pixelsPerYLabel is what we use.
2511 // TODO(danvk): version that works on a log scale.
2512 if (attr("labelsKMG2")) {
2513 var mults
= [1, 2, 4, 8];
2515 var mults
= [1, 2, 5];
2517 var scale
, low_val
, high_val
, nTicks
;
2518 // TODO(danvk): make it possible to set this for x- and y-axes independently.
2519 var pixelsPerTick
= attr('pixelsPerYLabel');
2520 for (var i
= -10; i
< 50; i
++) {
2521 if (attr("labelsKMG2")) {
2522 var base_scale
= Math
.pow(16, i
);
2524 var base_scale
= Math
.pow(10, i
);
2526 for (var j
= 0; j
< mults
.length
; j
++) {
2527 scale
= base_scale
* mults
[j
];
2528 low_val
= Math
.floor(minV
/ scale
) * scale
;
2529 high_val
= Math
.ceil(maxV
/ scale
) * scale
;
2530 nTicks
= Math
.abs(high_val
- low_val
) / scale
;
2531 var spacing
= self
.height_
/ nTicks
;
2532 // wish I could break out of both loops at once...
2533 if (spacing
> pixelsPerTick
) break;
2535 if (spacing
> pixelsPerTick
) break;
2538 // Construct the set of ticks.
2539 // Allow reverse y-axis if it's explicitly requested.
2540 if (low_val
> high_val
) scale
*= -1;
2541 for (var i
= 0; i
< nTicks
; i
++) {
2542 var tickV
= low_val
+ i
* scale
;
2543 ticks
.push( {v
: tickV
} );
2548 // Add formatted labels to the ticks.
2551 if (attr("labelsKMB")) {
2553 k_labels
= [ "K", "M", "B", "T" ];
2555 if (attr("labelsKMG2")) {
2556 if (k
) self
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
2558 k_labels
= [ "k", "M", "G", "T" ];
2560 var formatter
= attr('yAxisLabelFormatter') ?
2561 attr('yAxisLabelFormatter') : attr('yValueFormatter');
2563 // Add labels to the ticks.
2564 for (var i
= 0; i
< ticks
.length
; i
++) {
2565 if (ticks
[i
].label
!== undefined
) continue; // Use current label.
2566 var tickV
= ticks
[i
].v
;
2567 var absTickV
= Math
.abs(tickV
);
2568 var label
= formatter(tickV
, self
);
2569 if (k_labels
.length
> 0) {
2570 // Round up to an appropriate unit.
2572 for (var j
= 3; j
>= 0; j
--, n
/= k
) {
2573 if (absTickV
>= n
) {
2574 label
= Dygraph
.round_(tickV
/ n
, attr('digitsAfterDecimal')) + k_labels
[j
];
2579 ticks
[i
].label
= label
;
2587 * Computes the range of the data series (including confidence intervals).
2588 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2589 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2590 * @return [low, high]
2592 Dygraph
.prototype.extremeValues_
= function(series
) {
2593 var minY
= null, maxY
= null;
2595 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2597 // With custom bars, maxY is the max of the high values.
2598 for (var j
= 0; j
< series
.length
; j
++) {
2599 var y
= series
[j
][1][0];
2601 var low
= y
- series
[j
][1][1];
2602 var high
= y
+ series
[j
][1][2];
2603 if (low
> y
) low
= y
; // this can happen with custom bars,
2604 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2605 if (maxY
== null || high
> maxY
) {
2608 if (minY
== null || low
< minY
) {
2613 for (var j
= 0; j
< series
.length
; j
++) {
2614 var y
= series
[j
][1];
2615 if (y
=== null || isNaN(y
)) continue;
2616 if (maxY
== null || y
> maxY
) {
2619 if (minY
== null || y
< minY
) {
2625 return [minY
, maxY
];
2630 * This function is called once when the chart's data is changed or the options
2631 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2632 * idea is that values derived from the chart's data can be computed here,
2633 * rather than every time the chart is drawn. This includes things like the
2634 * number of axes, rolling averages, etc.
2636 Dygraph
.prototype.predraw_
= function() {
2637 // TODO(danvk): move more computations out of drawGraph_ and into here.
2638 this.computeYAxes_();
2640 // Create a new plotter.
2641 if (this.plotter_
) this.plotter_
.clear();
2642 this.plotter_
= new DygraphCanvasRenderer(this,
2647 // The roller sits in the bottom left corner of the chart. We don't know where
2648 // this will be until the options are available, so it's positioned here.
2649 this.createRollInterface_();
2651 // Same thing applies for the labelsDiv. It's right edge should be flush with
2652 // the right edge of the charting area (which may not be the same as the right
2653 // edge of the div, if we have two y-axes.
2654 this.positionLabelsDiv_();
2656 // If the data or options have changed, then we'd better redraw.
2661 * Update the graph with new data. This method is called when the viewing area
2662 * has changed. If the underlying data or options have changed, predraw_ will
2663 * be called before drawGraph_ is called.
2666 Dygraph
.prototype.drawGraph_
= function() {
2667 var data
= this.rawData_
;
2669 // This is used to set the second parameter to drawCallback, below.
2670 var is_initial_draw
= this.is_initial_draw_
;
2671 this.is_initial_draw_
= false;
2673 var minY
= null, maxY
= null;
2674 this.layout_
.removeAllDatasets();
2676 this.attrs_
['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
2678 // Loop over the fields (series). Go from the last to the first,
2679 // because if they're stacked that's how we accumulate the values.
2681 var cumulative_y
= []; // For stacked series.
2684 var extremes
= {}; // series name -> [low, high]
2686 // Loop over all fields and create datasets
2687 for (var i
= data
[0].length
- 1; i
>= 1; i
--) {
2688 if (!this.visibility()[i
- 1]) continue;
2690 var seriesName
= this.attr_("labels")[i
];
2691 var connectSeparatedPoints
= this.attr_('connectSeparatedPoints', i
);
2692 var logScale
= this.attr_('logscale', i
);
2695 for (var j
= 0; j
< data
.length
; j
++) {
2696 var date
= data
[j
][0];
2697 var point
= data
[j
][i
];
2699 // On the log scale, points less than zero do not exist.
2700 // This will create a gap in the chart. Note that this ignores
2701 // connectSeparatedPoints.
2705 series
.push([date
, point
]);
2707 if (point
!= null || !connectSeparatedPoints
) {
2708 series
.push([date
, point
]);
2713 // TODO(danvk): move this into predraw_. It's insane to do it here.
2714 series
= this.rollingAverage(series
, this.rollPeriod_
);
2716 // Prune down to the desired range, if necessary (for zooming)
2717 // Because there can be lines going to points outside of the visible area,
2718 // we actually prune to visible points, plus one on either side.
2719 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2720 if (this.dateWindow_
) {
2721 var low
= this.dateWindow_
[0];
2722 var high
= this.dateWindow_
[1];
2724 // TODO(danvk): do binary search instead of linear search.
2725 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2726 var firstIdx
= null, lastIdx
= null;
2727 for (var k
= 0; k
< series
.length
; k
++) {
2728 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2731 if (series
[k
][0] <= high
) {
2735 if (firstIdx
=== null) firstIdx
= 0;
2736 if (firstIdx
> 0) firstIdx
--;
2737 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2738 if (lastIdx
< series
.length
- 1) lastIdx
++;
2739 this.boundaryIds_
[i
-1] = [firstIdx
, lastIdx
];
2740 for (var k
= firstIdx
; k
<= lastIdx
; k
++) {
2741 pruned
.push(series
[k
]);
2745 this.boundaryIds_
[i
-1] = [0, series
.length
-1];
2748 var seriesExtremes
= this.extremeValues_(series
);
2751 for (var j
=0; j
<series
.length
; j
++) {
2752 val
= [series
[j
][0], series
[j
][1][0], series
[j
][1][1], series
[j
][1][2]];
2755 } else if (this.attr_("stackedGraph")) {
2756 var l
= series
.length
;
2758 for (var j
= 0; j
< l
; j
++) {
2759 // If one data set has a NaN, let all subsequent stacked
2760 // sets inherit the NaN -- only start at 0 for the first set.
2761 var x
= series
[j
][0];
2762 if (cumulative_y
[x
] === undefined
) {
2763 cumulative_y
[x
] = 0;
2766 actual_y
= series
[j
][1];
2767 cumulative_y
[x
] += actual_y
;
2769 series
[j
] = [x
, cumulative_y
[x
]]
2771 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2772 seriesExtremes
[1] = cumulative_y
[x
];
2774 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2775 seriesExtremes
[0] = cumulative_y
[x
];
2779 extremes
[seriesName
] = seriesExtremes
;
2781 datasets
[i
] = series
;
2784 for (var i
= 1; i
< datasets
.length
; i
++) {
2785 if (!this.visibility()[i
- 1]) continue;
2786 this.layout_
.addDataset(this.attr_("labels")[i
], datasets
[i
]);
2789 this.computeYAxisRanges_(extremes
);
2790 this.layout_
.setYAxes(this.axes_
);
2794 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2795 var tmp_zoomed_x
= this.zoomed_x_
;
2796 // Tell PlotKit to use this new data and render itself
2797 this.layout_
.setDateWindow(this.dateWindow_
);
2798 this.zoomed_x_
= tmp_zoomed_x
;
2799 this.layout_
.evaluateWithError();
2800 this.plotter_
.clear();
2801 this.plotter_
.render();
2802 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2803 this.canvas_
.height
);
2805 if (is_initial_draw
) {
2806 // Generate a static legend before any particular point is selected.
2807 this.setLegendHTML_();
2809 if (typeof(this.selPoints_
) !== 'undefined' && this.selPoints_
.length
) {
2810 // We should select the point nearest the page x/y here
, but it
's easier
2811 // to just clear the selection. This prevents erroneous hover dots from
2813 this.clearSelection();
2815 this.clearSelection();
2819 if (this.attr_("drawCallback") !== null) {
2820 this.attr_("drawCallback")(this, is_initial_draw);
2826 * Determine properties of the y-axes which are independent of the data
2827 * currently being displayed. This includes things like the number of axes and
2828 * the style of the axes. It does not include the range of each axis and its
2830 * This fills in this.axes_ and this.seriesToAxisMap_.
2831 * axes_ = [ { options } ]
2832 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2833 * indices are into the axes_ array.
2835 Dygraph.prototype.computeYAxes_ = function() {
2836 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
2837 this.seriesToAxisMap_ = {};
2839 // Get a list of series names.
2840 var labels = this.attr_("labels");
2842 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
2844 // all options which could be applied per-axis:
2852 'axisLabelFontSize
',
2857 // Copy global axis options over to the first axis.
2858 for (var i = 0; i < axisOptions.length; i++) {
2859 var k = axisOptions[i];
2860 var v = this.attr_(k);
2861 if (v) this.axes_[0][k] = v;
2864 // Go through once and add all the axes.
2865 for (var seriesName in series) {
2866 if (!series.hasOwnProperty(seriesName)) continue;
2867 var axis = this.attr_("axis", seriesName);
2869 this.seriesToAxisMap_[seriesName] = 0;
2872 if (typeof(axis) == 'object
') {
2873 // Add a new axis, making a copy of its per-axis options.
2875 Dygraph.update(opts, this.axes_[0]);
2876 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit
this.
2877 var yAxisId
= this.axes_
.length
;
2878 opts
.yAxisId
= yAxisId
;
2880 Dygraph
.update(opts
, axis
);
2881 this.axes_
.push(opts
);
2882 this.seriesToAxisMap_
[seriesName
] = yAxisId
;
2886 // Go through one more time and assign series to an axis defined by another
2887 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2888 for (var seriesName
in series
) {
2889 if (!series
.hasOwnProperty(seriesName
)) continue;
2890 var axis
= this.attr_("axis", seriesName
);
2891 if (typeof(axis
) == 'string') {
2892 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
2893 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
2894 "series " + axis
+ ", which does not define its own axis.");
2897 var idx
= this.seriesToAxisMap_
[axis
];
2898 this.seriesToAxisMap_
[seriesName
] = idx
;
2902 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2903 // this last so that hiding the first series doesn't destroy the axis
2904 // properties of the primary axis.
2905 var seriesToAxisFiltered
= {};
2906 var vis
= this.visibility();
2907 for (var i
= 1; i
< labels
.length
; i
++) {
2909 if (vis
[i
- 1]) seriesToAxisFiltered
[s
] = this.seriesToAxisMap_
[s
];
2911 this.seriesToAxisMap_
= seriesToAxisFiltered
;
2915 * Returns the number of y-axes on the chart.
2916 * @return {Number} the number of axes.
2918 Dygraph
.prototype.numAxes
= function() {
2920 for (var series
in this.seriesToAxisMap_
) {
2921 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2922 var idx
= this.seriesToAxisMap_
[series
];
2923 if (idx
> last_axis
) last_axis
= idx
;
2925 return 1 + last_axis
;
2930 * Returns axis properties for the given series.
2931 * @param { String } setName The name of the series for which to get axis
2932 * properties, e.g. 'Y1'.
2933 * @return { Object } The axis properties.
2935 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2936 // TODO(danvk): handle errors.
2937 return this.axes_
[this.seriesToAxisMap_
[series
]];
2942 * Determine the value range and tick marks for each axis.
2943 * @param {Object} extremes A mapping from seriesName -> [low, high]
2944 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2946 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2947 // Build a map from axis number -> [list of series names]
2948 var seriesForAxis
= [];
2949 for (var series
in this.seriesToAxisMap_
) {
2950 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2951 var idx
= this.seriesToAxisMap_
[series
];
2952 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2953 seriesForAxis
[idx
].push(series
);
2956 // Compute extreme values, a span and tick marks for each axis.
2957 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2958 var axis
= this.axes_
[i
];
2960 if (!seriesForAxis
[i
]) {
2961 // If no series are defined or visible then use a reasonable default
2962 axis
.extremeRange
= [0, 1];
2964 // Calculate the extremes of extremes.
2965 var series
= seriesForAxis
[i
];
2966 var minY
= Infinity
; // extremes[series[0]][0];
2967 var maxY
= -Infinity
; // extremes[series[0]][1];
2968 var extremeMinY
, extremeMaxY
;
2969 for (var j
= 0; j
< series
.length
; j
++) {
2970 // Only use valid extremes to stop null data series' from corrupting the scale.
2971 extremeMinY
= extremes
[series
[j
]][0];
2972 if (extremeMinY
!= null) {
2973 minY
= Math
.min(extremeMinY
, minY
);
2975 extremeMaxY
= extremes
[series
[j
]][1];
2976 if (extremeMaxY
!= null) {
2977 maxY
= Math
.max(extremeMaxY
, maxY
);
2980 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2982 // Ensure we have a valid scale, otherwise defualt to zero for safety.
2983 if (minY
== Infinity
) minY
= 0;
2984 if (maxY
== -Infinity
) maxY
= 0;
2986 // Add some padding and round up to an integer to be human-friendly.
2987 var span
= maxY
- minY
;
2988 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2989 if (span
== 0) { span
= maxY
; }
2993 if (axis
.logscale
) {
2994 var maxAxisY
= maxY
+ 0.1 * span
;
2995 var minAxisY
= minY
;
2997 var maxAxisY
= maxY
+ 0.1 * span
;
2998 var minAxisY
= minY
- 0.1 * span
;
3000 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
3001 if (!this.attr_("avoidMinZero")) {
3002 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
3003 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
3006 if (this.attr_("includeZero")) {
3007 if (maxY
< 0) maxAxisY
= 0;
3008 if (minY
> 0) minAxisY
= 0;
3011 axis
.extremeRange
= [minAxisY
, maxAxisY
];
3013 if (axis
.valueWindow
) {
3014 // This is only set if the user has zoomed on the y-axis. It is never set
3015 // by a user. It takes precedence over axis.valueRange because, if you set
3016 // valueRange, you'd still expect to be able to pan.
3017 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
3018 } else if (axis
.valueRange
) {
3019 // This is a user-set value range for this axis.
3020 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
3022 axis
.computedValueRange
= axis
.extremeRange
;
3025 // Add ticks. By default, all axes inherit the tick positions of the
3026 // primary axis. However, if an axis is specifically marked as having
3027 // independent ticks, then that is permissible as well.
3028 if (i
== 0 || axis
.independentTicks
) {
3030 Dygraph
.numericTicks(axis
.computedValueRange
[0],
3031 axis
.computedValueRange
[1],
3035 var p_axis
= this.axes_
[0];
3036 var p_ticks
= p_axis
.ticks
;
3037 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
3038 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
3039 var tick_values
= [];
3040 for (var i
= 0; i
< p_ticks
.length
; i
++) {
3041 var y_frac
= (p_ticks
[i
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
3042 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
3043 tick_values
.push(y_val
);
3047 Dygraph
.numericTicks(axis
.computedValueRange
[0],
3048 axis
.computedValueRange
[1],
3049 this, axis
, tick_values
);
3056 * Calculates the rolling average of a data set.
3057 * If originalData is [label, val], rolls the average of those.
3058 * If originalData is [label, [, it's interpreted as [value, stddev]
3059 * and the roll is returned in the same form, with appropriately reduced
3060 * stddev for each value.
3061 * Note that this is where fractional input (i.e. '5/10') is converted into
3063 * @param {Array} originalData The data in the appropriate format (see above)
3064 * @param {Number} rollPeriod The number of points over which to average the
3067 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
3068 if (originalData
.length
< 2)
3069 return originalData
;
3070 var rollPeriod
= Math
.min(rollPeriod
, originalData
.length
- 1);
3071 var rollingData
= [];
3072 var sigma
= this.attr_("sigma");
3074 if (this.fractions_
) {
3076 var den
= 0; // numerator/denominator
3078 for (var i
= 0; i
< originalData
.length
; i
++) {
3079 num
+= originalData
[i
][1][0];
3080 den
+= originalData
[i
][1][1];
3081 if (i
- rollPeriod
>= 0) {
3082 num
-= originalData
[i
- rollPeriod
][1][0];
3083 den
-= originalData
[i
- rollPeriod
][1][1];
3086 var date
= originalData
[i
][0];
3087 var value
= den
? num
/ den
: 0.0;
3088 if (this.attr_("errorBars")) {
3089 if (this.wilsonInterval_
) {
3090 // For more details on this confidence interval, see:
3091 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
3093 var p
= value
< 0 ? 0 : value
, n
= den
;
3094 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
3095 var denom
= 1 + sigma
* sigma
/ den
;
3096 var low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
3097 var high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
3098 rollingData
[i
] = [date
,
3099 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
3101 rollingData
[i
] = [date
, [0, 0, 0]];
3104 var stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
3105 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
3108 rollingData
[i
] = [date
, mult
* value
];
3111 } else if (this.attr_("customBars")) {
3116 for (var i
= 0; i
< originalData
.length
; i
++) {
3117 var data
= originalData
[i
][1];
3119 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
3121 if (y
!= null && !isNaN(y
)) {
3127 if (i
- rollPeriod
>= 0) {
3128 var prev
= originalData
[i
- rollPeriod
];
3129 if (prev
[1][1] != null && !isNaN(prev
[1][1])) {
3136 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
3137 1.0 * (mid
- low
) / count
,
3138 1.0 * (high
- mid
) / count
]];
3141 // Calculate the rolling average for the first rollPeriod - 1 points where
3142 // there is not enough data to roll over the full number of points
3143 var num_init_points
= Math
.min(rollPeriod
- 1, originalData
.length
- 2);
3144 if (!this.attr_("errorBars")){
3145 if (rollPeriod
== 1) {
3146 return originalData
;
3149 for (var i
= 0; i
< originalData
.length
; i
++) {
3152 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
3153 var y
= originalData
[j
][1];
3154 if (y
== null || isNaN(y
)) continue;
3156 sum
+= originalData
[j
][1];
3159 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
3161 rollingData
[i
] = [originalData
[i
][0], null];
3166 for (var i
= 0; i
< originalData
.length
; i
++) {
3170 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
3171 var y
= originalData
[j
][1][0];
3172 if (y
== null || isNaN(y
)) continue;
3174 sum
+= originalData
[j
][1][0];
3175 variance
+= Math
.pow(originalData
[j
][1][1], 2);
3178 var stddev
= Math
.sqrt(variance
) / num_ok
;
3179 rollingData
[i
] = [originalData
[i
][0],
3180 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
3182 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
3193 * Parses a date, returning the number of milliseconds since epoch. This can be
3194 * passed in as an xValueParser in the Dygraph constructor.
3195 * TODO(danvk): enumerate formats that this understands.
3196 * @param {String} A date in YYYYMMDD format.
3197 * @return {Number} Milliseconds since epoch.
3199 Dygraph
.dateParser
= function(dateStr
, self
) {
3202 if (dateStr
.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
3203 dateStrSlashed
= dateStr
.replace("-", "/", "g");
3204 while (dateStrSlashed
.search("-") != -1) {
3205 dateStrSlashed
= dateStrSlashed
.replace("-", "/");
3207 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
3208 } else if (dateStr
.length
== 8) { // e.g. '20090712'
3209 // TODO(danvk): remove support for this format. It's confusing.
3210 dateStrSlashed
= dateStr
.substr(0,4) + "/" + dateStr
.substr(4,2)
3211 + "/" + dateStr
.substr(6,2);
3212 d
= Dygraph
.dateStrToMillis(dateStrSlashed
);
3214 // Any format that Date.parse will accept, e.g. "2009/07/12" or
3215 // "2009/07/12 12:34:56"
3216 d
= Dygraph
.dateStrToMillis(dateStr
);
3219 if (!d
|| isNaN(d
)) {
3220 self
.error("Couldn't parse " + dateStr
+ " as a date");
3226 * Detects the type of the str (date or numeric) and sets the various
3227 * formatting attributes in this.attrs_ based on this type.
3228 * @param {String} str An x value.
3231 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
3233 if (str
.indexOf('-') > 0 ||
3234 str
.indexOf('/') >= 0 ||
3235 isNaN(parseFloat(str
))) {
3237 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
3238 // TODO(danvk): remove support for this format.
3243 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
3244 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3245 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
3246 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3248 // TODO(danvk): use Dygraph.numberFormatter here?
3249 /** @private (shut up, jsdoc!) */
3250 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
3251 /** @private (shut up, jsdoc!) */
3252 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3253 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
3254 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
3259 * Parses the value as a floating point number. This is like the parseFloat()
3260 * built-in, but with a few differences:
3261 * - the empty string is parsed as null, rather than NaN.
3262 * - if the string cannot be parsed at all, an error is logged.
3263 * If the string can't be parsed, this method returns null.
3264 * @param {String} x The string to be parsed
3265 * @param {Number} opt_line_no The line number from which the string comes.
3266 * @param {String} opt_line The text of the line from which the string comes.
3270 // Parse the x as a float or return null if it's not a number.
3271 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
3272 var val
= parseFloat(x
);
3273 if (!isNaN(val
)) return val
;
3275 // Try to figure out what happeend.
3276 // If the value is the empty string, parse it as null.
3277 if (/^ *$/.test(x
)) return null;
3279 // If it was actually "NaN", return it as NaN.
3280 if (/^ *nan *$/i.test(x
)) return NaN
;
3282 // Looks like a parsing error.
3283 var msg
= "Unable to parse '" + x
+ "' as a number";
3284 if (opt_line
!== null && opt_line_no
!== null) {
3285 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
3294 * Parses a string in a special csv format. We expect a csv file where each
3295 * line is a date point, and the first field in each line is the date string.
3296 * We also expect that all remaining fields represent series.
3297 * if the errorBars attribute is set, then interpret the fields as:
3298 * date, series1, stddev1, series2, stddev2, ...
3299 * @param {[Object]} data See above.
3301 * @return [Object] An array with one entry for each row. These entries
3302 * are an array of cells in that row. The first entry is the parsed x-value for
3303 * the row. The second, third, etc. are the y-values. These can take on one of
3304 * three forms, depending on the CSV and constructor parameters:
3306 * 2. [ value, stddev ]
3307 * 3. [ low value, center value, high value ]
3309 Dygraph
.prototype.parseCSV_
= function(data
) {
3311 var lines
= data
.split("\n");
3313 // Use the default delimiter or fall back to a tab if that makes sense.
3314 var delim
= this.attr_('delimiter');
3315 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
3320 if (!('labels' in this.user_attrs_
)) {
3321 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3323 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
3328 var defaultParserSet
= false; // attempt to auto-detect x value type
3329 var expectedCols
= this.attr_("labels").length
;
3330 var outOfOrder
= false;
3331 for (var i
= start
; i
< lines
.length
; i
++) {
3332 var line
= lines
[i
];
3334 if (line
.length
== 0) continue; // skip blank lines
3335 if (line
[0] == '#') continue; // skip comment lines
3336 var inFields
= line
.split(delim
);
3337 if (inFields
.length
< 2) continue;
3340 if (!defaultParserSet
) {
3341 this.detectTypeFromString_(inFields
[0]);
3342 xParser
= this.attr_("xValueParser");
3343 defaultParserSet
= true;
3345 fields
[0] = xParser(inFields
[0], this);
3347 // If fractions are expected, parse the numbers as "A/B
"
3348 if (this.fractions_) {
3349 for (var j = 1; j < inFields.length; j++) {
3350 // TODO(danvk): figure out an appropriate way to flag parse errors.
3351 var vals = inFields[j].split("/");
3352 if (vals.length != 2) {
3353 this.error('Expected fractional "num
/den
" values in CSV data ' +
3354 "but found a value
'" + inFields[j] + "' on line
" +
3355 (1 + i) + " ('" + line + "') which is not of
this form
.");
3358 fields[j] = [this.parseFloat_(vals[0], i, line),
3359 this.parseFloat_(vals[1], i, line)];
3362 } else if (this.attr_("errorBars
")) {
3363 // If there are error bars, values are (value, stddev) pairs
3364 if (inFields.length % 2 != 1) {
3365 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3366 'but line ' + (1 + i) + ' has an odd number of values (' +
3367 (inFields.length - 1) + "): '" + line + "'");
3369 for (var j = 1; j < inFields.length; j += 2) {
3370 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3371 this.parseFloat_(inFields[j + 1], i, line)];
3373 } else if (this.attr_("customBars
")) {
3374 // Bars are a low;center;high tuple
3375 for (var j = 1; j < inFields.length; j++) {
3376 var val = inFields[j];
3377 if (/^ *$/.test(val)) {
3378 fields[j] = [null, null, null];
3380 var vals = val.split(";");
3381 if (vals.length == 3) {
3382 fields[j] = [ this.parseFloat_(vals[0], i, line),
3383 this.parseFloat_(vals[1], i, line),
3384 this.parseFloat_(vals[2], i, line) ];
3386 this.warning('When using customBars, values must be either blank ' +
3387 'or "low
;center
;high
" tuples (got "' + val +
3388 '" on line ' + (1+i));
3393 // Values are just numbers
3394 for (var j = 1; j < inFields.length; j++) {
3395 fields[j] = this.parseFloat_(inFields[j], i, line);
3398 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3402 if (fields.length != expectedCols) {
3403 this.error("Number of columns
in line
" + i + " (" + fields.length +
3404 ") does not agree
with number of
labels (" + expectedCols +
3408 // If the user specified the 'labels' option and none of the cells of the
3409 // first row parsed correctly, then they probably double-specified the
3410 // labels. We go with the values set in the option, discard this row and
3411 // log a warning to the JS console.
3412 if (i == 0 && this.attr_('labels')) {
3413 var all_null = true;
3414 for (var j = 0; all_null && j < fields.length; j++) {
3415 if (fields[j]) all_null = false;
3418 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
3419 "CSV
data ('" + line + "') appears to also contain labels
. " +
3420 "Will drop the CSV labels and
use the option labels
.");
3428 this.warn("CSV is out of order
; order it correctly to speed loading
.");
3429 ret.sort(function(a,b) { return a[0] - b[0] });
3437 * The user has provided their data as a pre-packaged JS array. If the x values
3438 * are numeric, this is the same as dygraphs' internal format. If the x values
3439 * are dates, we need to convert them from Date objects to ms since epoch.
3440 * @param {[Object]} data
3441 * @return {[Object]} data with numeric x values.
3443 Dygraph.prototype.parseArray_ = function(data) {
3444 // Peek at the first x value to see if it's numeric.
3445 if (data.length == 0) {
3446 this.error("Can
't plot empty data set");
3449 if (data[0].length == 0) {
3450 this.error("Data set cannot contain an empty row");
3454 if (this.attr_("labels") == null) {
3455 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3456 "in the options parameter");
3457 this.attrs_.labels = [ "X" ];
3458 for (var i = 1; i < data[0].length; i++) {
3459 this.attrs_.labels.push("Y" + i);
3463 if (Dygraph.isDateLike(data[0][0])) {
3464 // Some intelligent defaults for a date x-axis.
3465 this.attrs_.xValueFormatter = Dygraph.dateString_;
3466 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
3467 this.attrs_.xTicker = Dygraph.dateTicker;
3469 // Assume they're all dates
.
3470 var parsedData
= Dygraph
.clone(data
);
3471 for (var i
= 0; i
< data
.length
; i
++) {
3472 if (parsedData
[i
].length
== 0) {
3473 this.error("Row " + (1 + i
) + " of data is empty");
3476 if (parsedData
[i
][0] == null
3477 || typeof(parsedData
[i
][0].getTime
) != 'function'
3478 || isNaN(parsedData
[i
][0].getTime())) {
3479 this.error("x value in row " + (1 + i
) + " is not a Date");
3482 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3486 // Some intelligent defaults for a numeric x-axis.
3487 /** @private (shut up, jsdoc!) */
3488 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
3489 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
3495 * Parses a DataTable object from gviz.
3496 * The data is expected to have a first column that is either a date or a
3497 * number. All subsequent columns must be numbers. If there is a clear mismatch
3498 * between this.xValueParser_ and the type of the first column, it will be
3499 * fixed. Fills out rawData_.
3500 * @param {[Object]} data See above.
3503 Dygraph
.prototype.parseDataTable_
= function(data
) {
3504 var cols
= data
.getNumberOfColumns();
3505 var rows
= data
.getNumberOfRows();
3507 var indepType
= data
.getColumnType(0);
3508 if (indepType
== 'date' || indepType
== 'datetime') {
3509 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
3510 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3511 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
3512 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3513 } else if (indepType
== 'number') {
3514 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
3515 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3516 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
3517 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
3519 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3520 "column 1 of DataTable input (Got '" + indepType
+ "')");
3524 // Array of the column indices which contain data (and not annotations).
3526 var annotationCols
= {}; // data index -> [annotation cols]
3527 var hasAnnotations
= false;
3528 for (var i
= 1; i
< cols
; i
++) {
3529 var type
= data
.getColumnType(i
);
3530 if (type
== 'number') {
3532 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3533 // This is OK -- it's an annotation column.
3534 var dataIdx
= colIdx
[colIdx
.length
- 1];
3535 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3536 annotationCols
[dataIdx
] = [i
];
3538 annotationCols
[dataIdx
].push(i
);
3540 hasAnnotations
= true;
3542 this.error("Only 'number' is supported as a dependent type with Gviz." +
3543 " 'string' is only supported if displayAnnotations is true");
3547 // Read column labels
3548 // TODO(danvk): add support back for errorBars
3549 var labels
= [data
.getColumnLabel(0)];
3550 for (var i
= 0; i
< colIdx
.length
; i
++) {
3551 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3552 if (this.attr_("errorBars")) i
+= 1;
3554 this.attrs_
.labels
= labels
;
3555 cols
= labels
.length
;
3558 var outOfOrder
= false;
3559 var annotations
= [];
3560 for (var i
= 0; i
< rows
; i
++) {
3562 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3563 data
.getValue(i
, 0) === null) {
3564 this.warn("Ignoring row " + i
+
3565 " of DataTable because of undefined or null first column.");
3569 if (indepType
== 'date' || indepType
== 'datetime') {
3570 row
.push(data
.getValue(i
, 0).getTime());
3572 row
.push(data
.getValue(i
, 0));
3574 if (!this.attr_("errorBars")) {
3575 for (var j
= 0; j
< colIdx
.length
; j
++) {
3576 var col
= colIdx
[j
];
3577 row
.push(data
.getValue(i
, col
));
3578 if (hasAnnotations
&&
3579 annotationCols
.hasOwnProperty(col
) &&
3580 data
.getValue(i
, annotationCols
[col
][0]) != null) {
3582 ann
.series
= data
.getColumnLabel(col
);
3584 ann
.shortText
= String
.fromCharCode(65 /* A */ + annotations
.length
)
3586 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3587 if (k
) ann
.text
+= "\n";
3588 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3590 annotations
.push(ann
);
3594 // Strip out infinities, which give dygraphs problems later on.
3595 for (var j
= 0; j
< row
.length
; j
++) {
3596 if (!isFinite(row
[j
])) row
[j
] = null;
3599 for (var j
= 0; j
< cols
- 1; j
++) {
3600 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3603 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3610 this.warn("DataTable is out of order; order it correctly to speed loading.");
3611 ret
.sort(function(a
,b
) { return a
[0] - b
[0] });
3613 this.rawData_
= ret
;
3615 if (annotations
.length
> 0) {
3616 this.setAnnotations(annotations
, true);
3622 * This is identical to JavaScript's built-in Date.parse() method, except that
3623 * it doesn't get replaced with an incompatible method by aggressive JS
3624 * libraries like MooTools or Joomla.
3625 * @param { String } str The date string, e.g. "2011/05/06"
3626 * @return { Integer } millis since epoch
3628 Dygraph
.dateStrToMillis
= function(str
) {
3629 return new Date(str
).getTime();
3632 // These functions are all based on MochiKit.
3636 Dygraph
.update
= function (self
, o
) {
3637 if (typeof(o
) != 'undefined' && o
!== null) {
3639 if (o
.hasOwnProperty(k
)) {
3650 Dygraph
.isArrayLike
= function (o
) {
3651 var typ
= typeof(o
);
3653 (typ
!= 'object' && !(typ
== 'function' &&
3654 typeof(o
.item
) == 'function')) ||
3656 typeof(o
.length
) != 'number' ||
3667 Dygraph
.isDateLike
= function (o
) {
3668 if (typeof(o
) != "object" || o
=== null ||
3669 typeof(o
.getTime
) != 'function') {
3678 Dygraph
.clone
= function(o
) {
3679 // TODO(danvk): figure out how MochiKit's version works
3681 for (var i
= 0; i
< o
.length
; i
++) {
3682 if (Dygraph
.isArrayLike(o
[i
])) {
3683 r
.push(Dygraph
.clone(o
[i
]));
3693 * Get the CSV data. If it's in a function, call that function. If it's in a
3694 * file, do an XMLHttpRequest to get it.
3697 Dygraph
.prototype.start_
= function() {
3698 if (typeof this.file_
== 'function') {
3699 // CSV string. Pretend we got it via XHR.
3700 this.loadedEvent_(this.file_());
3701 } else if (Dygraph
.isArrayLike(this.file_
)) {
3702 this.rawData_
= this.parseArray_(this.file_
);
3704 } else if (typeof this.file_
== 'object' &&
3705 typeof this.file_
.getColumnRange
== 'function') {
3706 // must be a DataTable from gviz.
3707 this.parseDataTable_(this.file_
);
3709 } else if (typeof this.file_
== 'string') {
3710 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3711 if (this.file_
.indexOf('\n') >= 0) {
3712 this.loadedEvent_(this.file_
);
3714 var req
= new XMLHttpRequest();
3716 req
.onreadystatechange
= function () {
3717 if (req
.readyState
== 4) {
3718 if (req
.status
== 200) {
3719 caller
.loadedEvent_(req
.responseText
);
3724 req
.open("GET", this.file_
, true);
3728 this.error("Unknown data format: " + (typeof this.file_
));
3733 * Changes various properties of the graph. These can include:
3735 * <li>file: changes the source data for the graph</li>
3736 * <li>errorBars: changes whether the data contains stddev</li>
3739 * There's a huge variety of options that can be passed to this method. For a
3740 * full list, see http://dygraphs.com/options.html.
3742 * @param {Object} attrs The new properties and values
3743 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3744 * call to updateOptions(). If you know better, you can pass true to explicitly
3745 * block the redraw. This can be useful for chaining updateOptions() calls,
3746 * avoiding the occasional infinite loop and preventing redraws when it's not
3747 * necessary (e.g. when updating a callback).
3749 Dygraph
.prototype.updateOptions
= function(attrs
, block_redraw
) {
3750 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3752 // TODO(danvk): this is a mess. Move these options into attr_.
3753 if ('rollPeriod' in attrs
) {
3754 this.rollPeriod_
= attrs
.rollPeriod
;
3756 if ('dateWindow' in attrs
) {
3757 this.dateWindow_
= attrs
.dateWindow
;
3758 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3759 this.zoomed_x_
= attrs
.dateWindow
!= null;
3762 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3763 this.zoomed_y_
= attrs
.valueRange
!= null;
3766 // TODO(danvk): validate per-series options.
3771 // highlightCircleSize
3773 Dygraph
.update(this.user_attrs_
, attrs
);
3775 if (attrs
['file']) {
3776 this.file_
= attrs
['file'];
3777 if (!block_redraw
) this.start_();
3779 if (!block_redraw
) this.predraw_();
3784 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3785 * containing div (which has presumably changed size since the dygraph was
3786 * instantiated. If the width/height are specified, the div will be resized.
3788 * This is far more efficient than destroying and re-instantiating a
3789 * Dygraph, since it doesn't have to reparse the underlying data.
3791 * @param {Number} [width] Width (in pixels)
3792 * @param {Number} [height] Height (in pixels)
3794 Dygraph
.prototype.resize
= function(width
, height
) {
3795 if (this.resize_lock
) {
3798 this.resize_lock
= true;
3800 if ((width
=== null) != (height
=== null)) {
3801 this.warn("Dygraph.resize() should be called with zero parameters or " +
3802 "two non-NULL parameters. Pretending it was zero.");
3803 width
= height
= null;
3806 // TODO(danvk): there should be a clear() method.
3807 this.maindiv_
.innerHTML
= "";
3808 this.attrs_
.labelsDiv
= null;
3811 this.maindiv_
.style
.width
= width
+ "px";
3812 this.maindiv_
.style
.height
= height
+ "px";
3813 this.width_
= width
;
3814 this.height_
= height
;
3816 this.width_
= this.maindiv_
.offsetWidth
;
3817 this.height_
= this.maindiv_
.offsetHeight
;
3820 this.createInterface_();
3823 this.resize_lock
= false;
3827 * Adjusts the number of points in the rolling average. Updates the graph to
3828 * reflect the new averaging period.
3829 * @param {Number} length Number of points over which to average the data.
3831 Dygraph
.prototype.adjustRoll
= function(length
) {
3832 this.rollPeriod_
= length
;
3837 * Returns a boolean array of visibility statuses.
3839 Dygraph
.prototype.visibility
= function() {
3840 // Do lazy-initialization, so that this happens after we know the number of
3842 if (!this.attr_("visibility")) {
3843 this.attrs_
["visibility"] = [];
3845 while (this.attr_("visibility").length
< this.rawData_
[0].length
- 1) {
3846 this.attr_("visibility").push(true);
3848 return this.attr_("visibility");
3852 * Changes the visiblity of a series.
3854 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3855 var x
= this.visibility();
3856 if (num
< 0 || num
>= x
.length
) {
3857 this.warn("invalid series number in setVisibility: " + num
);
3865 * Update the list of annotations and redraw the chart.
3867 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3868 // Only add the annotation CSS rule once we know it will be used.
3869 Dygraph
.addAnnotationRule();
3870 this.annotations_
= ann
;
3871 this.layout_
.setAnnotations(this.annotations_
);
3872 if (!suppressDraw
) {
3878 * Return the list of annotations.
3880 Dygraph
.prototype.annotations
= function() {
3881 return this.annotations_
;
3885 * Get the index of a series (column) given its name. The first column is the
3886 * x-axis, so the data series start with index 1.
3888 Dygraph
.prototype.indexFromSetName
= function(name
) {
3889 var labels
= this.attr_("labels");
3890 for (var i
= 0; i
< labels
.length
; i
++) {
3891 if (labels
[i
] == name
) return i
;
3898 * Adds a default style for the annotation CSS classes to the document. This is
3899 * only executed when annotations are actually used. It is designed to only be
3900 * called once -- all calls after the first will return immediately.
3902 Dygraph
.addAnnotationRule
= function() {
3903 if (Dygraph
.addedAnnotationCSS
) return;
3905 var rule
= "border: 1px solid black; " +
3906 "background-color: white; " +
3907 "text-align: center;";
3909 var styleSheetElement
= document
.createElement("style");
3910 styleSheetElement
.type
= "text/css";
3911 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3913 // Find the first style sheet that we can access.
3914 // We may not add a rule to a style sheet from another domain for security
3915 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3916 // adds its own style sheets from google.com.
3917 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3918 if (document
.styleSheets
[i
].disabled
) continue;
3919 var mysheet
= document
.styleSheets
[i
];
3921 if (mysheet
.insertRule
) { // Firefox
3922 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3923 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3924 } else if (mysheet
.addRule
) { // IE
3925 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3927 Dygraph
.addedAnnotationCSS
= true;
3930 // Was likely a security exception.
3934 this.warn("Unable to add default annotation CSS rule; display may be off.");
3939 * Create a new canvas element. This is more complex than a simple
3940 * document.createElement("canvas") because of IE and excanvas.
3942 Dygraph
.createCanvas
= function() {
3943 var canvas
= document
.createElement("canvas");
3945 isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
3946 if (isIE
&& (typeof(G_vmlCanvasManager
) != 'undefined')) {
3947 canvas
= G_vmlCanvasManager
.initElement(canvas
);
3953 // Older pages may still use this name.
3954 DateGraph
= Dygraph
;