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 // Default attribute values.
90 Dygraph
.DEFAULT_ATTRS
= {
91 highlightCircleSize
: 3,
97 // TODO(danvk): move defaults from createStatusMessage_ here.
99 labelsSeparateLines
: false,
100 labelsShowZeroValues
: true,
103 showLabelsOnHighlight
: true,
105 yValueFormatter
: function(a
,b
) { return Dygraph
.numberFormatter(a
,b
); },
106 digitsAfterDecimal
: 2,
113 axisLabelFontSize
: 14,
116 xAxisLabelFormatter
: Dygraph
.dateAxisFormatter
,
120 xValueFormatter
: Dygraph
.dateString_
,
121 xValueParser
: Dygraph
.dateParser
,
122 xTicker
: Dygraph
.dateTicker
,
129 wilsonInterval
: true, // only relevant if fractions is true
133 connectSeparatedPoints
: false,
136 hideOverlayOnMouseOut
: true,
138 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
139 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
144 // Sizes of the various chart labels.
151 axisLineColor
: "black",
154 axisLabelColor
: "black",
155 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
159 gridLineColor
: "rgb(128,128,128)",
161 interactionModel
: null // will be set to Dygraph.Interaction.defaultModel
164 // Directions for panning and zooming. Use bit operations when combined
165 // values are possible.
166 Dygraph
.HORIZONTAL
= 1;
167 Dygraph
.VERTICAL
= 2;
169 // Used for initializing annotation CSS rules only once.
170 Dygraph
.addedAnnotationCSS
= false;
172 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
173 // Labels is no longer a constructor parameter, since it's typically set
174 // directly from the data source. It also conains a name for the x-axis,
175 // which the previous constructor form did not.
176 if (labels
!= null) {
177 var new_labels
= ["Date"];
178 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
179 Dygraph
.update(attrs
, { 'labels': new_labels
});
181 this.__init__(div
, file
, attrs
);
185 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
186 * and context <canvas> inside of it. See the constructor for details.
188 * @param {Element} div the Element to render the graph into.
189 * @param {String | Function} file Source data
190 * @param {Object} attrs Miscellaneous other options
193 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
194 // Hack for IE: if we're using excanvas and the document hasn't finished
195 // loading yet (and hence may not have initialized whatever it needs to
196 // initialize), then keep calling this routine periodically until it has.
197 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
198 typeof(G_vmlCanvasManager
) != 'undefined' &&
199 document
.readyState
!= 'complete') {
201 setTimeout(function() { self
.__init__(div
, file
, attrs
) }, 100);
204 // Support two-argument constructor
205 if (attrs
== null) { attrs
= {}; }
207 // Copy the important bits into the object
208 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
211 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
212 this.previousVerticalX_
= -1;
213 this.fractions_
= attrs
.fractions
|| false;
214 this.dateWindow_
= attrs
.dateWindow
|| null;
216 this.wilsonInterval_
= attrs
.wilsonInterval
|| true;
217 this.is_initial_draw_
= true;
218 this.annotations_
= [];
220 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
221 this.zoomed_x_
= false;
222 this.zoomed_y_
= false;
224 // Clear the div. This ensure that, if multiple dygraphs are passed the same
225 // div, then only one will be drawn.
228 // For historical reasons, the 'width' and 'height' options trump all CSS
229 // rules _except_ for an explicit 'width' or 'height' on the div.
230 // As an added convenience, if the div has zero height (like <div></div> does
231 // without any styles), then we use a default height/width
.
232 if (div
.style
.width
== '' && attrs
.width
) {
233 div
.style
.width
= attrs
.width
+ "px";
235 if (div
.style
.height
== '' && attrs
.height
) {
236 div
.style
.height
= attrs
.height
+ "px";
238 if (div
.offsetHeight
== 0) {
239 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
240 if (div
.style
.width
== '') {
241 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
244 this.width_
= div
.offsetWidth
;
245 this.height_
= div
.offsetHeight
;
247 if (this.width_
== 0) {
248 this.error("dygraph has zero width. Please specify a width in pixels.");
250 if (this.height_
== 0) {
251 this.error("dygraph has zero height. Please specify a height in pixels.");
254 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
255 if (attrs
['stackedGraph']) {
256 attrs
['fillGraph'] = true;
257 // TODO(nikhilk): Add any other stackedGraph checks here.
260 // Dygraphs has many options, some of which interact with one another.
261 // To keep track of everything, we maintain two sets of options:
263 // this.user_attrs_ only options explicitly set by the user.
264 // this.attrs_ defaults, options derived from user_attrs_, data.
266 // Options are then accessed this.attr_('attr'), which first looks at
267 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
268 // defaults without overriding behavior that the user specifically asks for.
269 this.user_attrs_
= {};
270 Dygraph
.update(this.user_attrs_
, attrs
);
273 Dygraph
.update(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
275 this.boundaryIds_
= [];
277 // Create the containing DIV and other interactive elements
278 this.createInterface_();
284 * Returns the zoomed status of the chart for one or both axes.
286 * Axis is an optional parameter. Can be set to 'x' or 'y'.
288 * The zoomed status for an axis is set whenever a user zooms using the mouse
289 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
290 * option is also specified).
292 Dygraph
.prototype.isZoomed
= function(axis
) {
293 if (axis
== null) return this.zoomed_x_
|| this.zoomed_y_
;
294 if (axis
== 'x') return this.zoomed_x_
;
295 if (axis
== 'y') return this.zoomed_y_
;
296 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
300 * Returns information about the Dygraph object, including its containing ID.
302 Dygraph
.prototype.toString
= function() {
303 var maindiv
= this.maindiv_
;
304 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
305 return "[Dygraph " + id
+ "]";
310 * Returns the value of an option. This may be set by the user (either in the
311 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
313 * @param { String } name The name of the option, e.g. 'rollPeriod'.
314 * @param { String } [seriesName] The name of the series to which the option
315 * will be applied. If no per-series value of this option is available, then
316 * the global value is returned. This is optional.
317 * @return { ... } The value of the option.
319 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
320 // <REMOVE_FOR_COMBINED>
321 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
322 this.error('Must include options reference JS for testing');
323 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
324 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
325 'in the Dygraphs.OPTIONS_REFERENCE listing.');
326 // Only log this error once.
327 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
329 // </REMOVE_FOR_COMBINED
>
331 typeof(this.user_attrs_
[seriesName
]) != 'undefined' &&
332 this.user_attrs_
[seriesName
] != null &&
333 typeof(this.user_attrs_
[seriesName
][name
]) != 'undefined') {
334 return this.user_attrs_
[seriesName
][name
];
335 } else if (typeof(this.user_attrs_
[name
]) != 'undefined') {
336 return this.user_attrs_
[name
];
337 } else if (typeof(this.attrs_
[name
]) != 'undefined') {
338 return this.attrs_
[name
];
345 * Returns the current rolling period, as set by the user or an option.
346 * @return {Number} The number of points in the rolling window
348 Dygraph
.prototype.rollPeriod
= function() {
349 return this.rollPeriod_
;
353 * Returns the currently-visible x-range. This can be affected by zooming,
354 * panning or a call to updateOptions.
355 * Returns a two-element array: [left, right].
356 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
358 Dygraph
.prototype.xAxisRange
= function() {
359 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
363 * Returns the lower- and upper-bound x-axis values of the
366 Dygraph
.prototype.xAxisExtremes
= function() {
367 var left
= this.rawData_
[0][0];
368 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
369 return [left
, right
];
373 * Returns the currently-visible y-range for an axis. This can be affected by
374 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
375 * called with no arguments, returns the range of the first axis.
376 * Returns a two-element array: [bottom, top].
378 Dygraph
.prototype.yAxisRange
= function(idx
) {
379 if (typeof(idx
) == "undefined") idx
= 0;
380 if (idx
< 0 || idx
>= this.axes_
.length
) {
383 var axis
= this.axes_
[idx
];
384 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
388 * Returns the currently-visible y-ranges for each axis. This can be affected by
389 * zooming, panning, calls to updateOptions, etc.
390 * Returns an array of [bottom, top] pairs, one for each y-axis.
392 Dygraph
.prototype.yAxisRanges
= function() {
394 for (var i
= 0; i
< this.axes_
.length
; i
++) {
395 ret
.push(this.yAxisRange(i
));
400 // TODO(danvk): use these functions throughout dygraphs.
402 * Convert from data coordinates to canvas/div X/Y coordinates.
403 * If specified, do this conversion for the coordinate system of a particular
404 * axis. Uses the first axis by default.
405 * Returns a two-element array: [X, Y]
407 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
408 * instead of toDomCoords(null, y, axis).
410 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
411 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
415 * Convert from data x coordinates to canvas/div X coordinate.
416 * If specified, do this conversion for the coordinate system of a particular
418 * Returns a single value or null if x is null.
420 Dygraph
.prototype.toDomXCoord
= function(x
) {
425 var area
= this.plotter_
.area
;
426 var xRange
= this.xAxisRange();
427 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
431 * Convert from data x coordinates to canvas/div Y coordinate and optional
432 * axis. Uses the first axis by default.
434 * returns a single value or null if y is null.
436 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
437 var pct
= this.toPercentYCoord(y
, axis
);
442 var area
= this.plotter_
.area
;
443 return area
.y
+ pct
* area
.h
;
447 * Convert from canvas/div coords to data coordinates.
448 * If specified, do this conversion for the coordinate system of a particular
449 * axis. Uses the first axis by default.
450 * Returns a two-element array: [X, Y].
452 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
453 * instead of toDataCoords(null, y, axis).
455 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
456 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
460 * Convert from canvas/div x coordinate to data coordinate.
462 * If x is null, this returns null.
464 Dygraph
.prototype.toDataXCoord
= function(x
) {
469 var area
= this.plotter_
.area
;
470 var xRange
= this.xAxisRange();
471 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
475 * Convert from canvas/div y coord to value.
477 * If y is null, this returns null.
478 * if axis is null, this uses the first axis.
480 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
485 var area
= this.plotter_
.area
;
486 var yRange
= this.yAxisRange(axis
);
488 if (typeof(axis
) == "undefined") axis
= 0;
489 if (!this.axes_
[axis
].logscale
) {
490 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
492 // Computing the inverse of toDomCoord.
493 var pct
= (y
- area
.y
) / area
.h
495 // Computing the inverse of toPercentYCoord. The function was arrived at with
496 // the following steps:
498 // Original calcuation:
499 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
501 // Move denominator to both sides:
502 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
504 // subtract logr1, and take the negative value.
505 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
507 // Swap both sides of the equation, and we can compute the log of the
508 // return value. Which means we just need to use that as the exponent in
510 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
512 var logr1
= Dygraph
.log10(yRange
[1]);
513 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
514 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
520 * Converts a y for an axis to a percentage from the top to the
521 * bottom of the drawing area.
523 * If the coordinate represents a value visible on the canvas, then
524 * the value will be between 0 and 1, where 0 is the top of the canvas.
525 * However, this method will return values outside the range, as
526 * values can fall outside the canvas.
528 * If y is null, this returns null.
529 * if axis is null, this uses the first axis.
531 * @param { Number } y The data y-coordinate.
532 * @param { Number } [axis] The axis number on which the data coordinate lives.
533 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
535 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
539 if (typeof(axis
) == "undefined") axis
= 0;
541 var area
= this.plotter_
.area
;
542 var yRange
= this.yAxisRange(axis
);
545 if (!this.axes_
[axis
].logscale
) {
546 // yRange[1] - y is unit distance from the bottom.
547 // yRange[1] - yRange[0] is the scale of the range.
548 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
549 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
551 var logr1
= Dygraph
.log10(yRange
[1]);
552 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
558 * Converts an x value to a percentage from the left to the right of
561 * If the coordinate represents a value visible on the canvas, then
562 * the value will be between 0 and 1, where 0 is the left of the canvas.
563 * However, this method will return values outside the range, as
564 * values can fall outside the canvas.
566 * If x is null, this returns null.
567 * @param { Number } x The data x-coordinate.
568 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
570 Dygraph
.prototype.toPercentXCoord
= function(x
) {
575 var xRange
= this.xAxisRange();
576 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
580 * Returns the number of columns (including the independent variable).
581 * @return { Integer } The number of columns.
583 Dygraph
.prototype.numColumns
= function() {
584 return this.rawData_
[0].length
;
588 * Returns the number of rows (excluding any header/label row).
589 * @return { Integer } The number of rows, less any header.
591 Dygraph
.prototype.numRows
= function() {
592 return this.rawData_
.length
;
596 * Returns the value in the given row and column. If the row and column exceed
597 * the bounds on the data, returns null. Also returns null if the value is
599 * @param { Number} row The row number of the data (0-based). Row 0 is the
600 * first row of data, not a header row.
601 * @param { Number} col The column number of the data (0-based)
602 * @return { Number } The value in the specified cell or null if the row/col
605 Dygraph
.prototype.getValue
= function(row
, col
) {
606 if (row
< 0 || row
> this.rawData_
.length
) return null;
607 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
609 return this.rawData_
[row
][col
];
613 * Generates interface elements for the Dygraph: a containing div, a div to
614 * display the current point, and a textbox to adjust the rolling average
615 * period. Also creates the Renderer/Layout elements.
618 Dygraph
.prototype.createInterface_
= function() {
619 // Create the all-enclosing graph div
620 var enclosing
= this.maindiv_
;
622 this.graphDiv
= document
.createElement("div");
623 this.graphDiv
.style
.width
= this.width_
+ "px";
624 this.graphDiv
.style
.height
= this.height_
+ "px";
625 enclosing
.appendChild(this.graphDiv
);
627 // Create the canvas for interactive parts of the chart.
628 this.canvas_
= Dygraph
.createCanvas();
629 this.canvas_
.style
.position
= "absolute";
630 this.canvas_
.width
= this.width_
;
631 this.canvas_
.height
= this.height_
;
632 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
633 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
635 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
637 // ... and for static parts of the chart.
638 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
639 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
641 // The interactive parts of the graph are drawn on top of the chart.
642 this.graphDiv
.appendChild(this.hidden_
);
643 this.graphDiv
.appendChild(this.canvas_
);
644 this.mouseEventElement_
= this.canvas_
;
647 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', function(e
) {
648 dygraph
.mouseMove_(e
);
650 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', function(e
) {
651 dygraph
.mouseOut_(e
);
654 // Create the grapher
655 this.layout_
= new DygraphLayout(this);
657 this.createStatusMessage_();
658 this.createDragInterface_();
662 * Detach DOM elements in the dygraph and null out all data references.
663 * Calling this when you're done with a dygraph can dramatically reduce memory
664 * usage. See, e.g., the tests/perf.html example.
666 Dygraph
.prototype.destroy
= function() {
667 var removeRecursive
= function(node
) {
668 while (node
.hasChildNodes()) {
669 removeRecursive(node
.firstChild
);
670 node
.removeChild(node
.firstChild
);
673 removeRecursive(this.maindiv_
);
675 var nullOut
= function(obj
) {
677 if (typeof(obj
[n
]) === 'object') {
683 // These may not all be necessary, but it can't hurt...
684 nullOut(this.layout_
);
685 nullOut(this.plotter_
);
690 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
691 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
692 * or the zoom rectangles) is done on this.canvas_.
693 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
694 * @return {Object} The newly-created canvas
697 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
698 var h
= Dygraph
.createCanvas();
699 h
.style
.position
= "absolute";
700 // TODO(danvk): h should be offset from canvas. canvas needs to include
701 // some extra area to make it easier to zoom in on the far left and far
702 // right. h needs to be precisely the plot area, so that clipping occurs.
703 h
.style
.top
= canvas
.style
.top
;
704 h
.style
.left
= canvas
.style
.left
;
705 h
.width
= this.width_
;
706 h
.height
= this.height_
;
707 h
.style
.width
= this.width_
+ "px"; // for IE
708 h
.style
.height
= this.height_
+ "px"; // for IE
713 * Generate a set of distinct colors for the data series. This is done with a
714 * color wheel. Saturation/Value are customizable, and the hue is
715 * equally-spaced around the color wheel. If a custom set of colors is
716 * specified, that is used instead.
719 Dygraph
.prototype.setColors_
= function() {
720 var num
= this.attr_("labels").length
- 1;
722 var colors
= this.attr_('colors');
724 var sat
= this.attr_('colorSaturation') || 1.0;
725 var val
= this.attr_('colorValue') || 0.5;
726 var half
= Math
.ceil(num
/ 2);
727 for (var i
= 1; i
<= num
; i
++) {
728 if (!this.visibility()[i
-1]) continue;
729 // alternate colors for high contrast.
730 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
731 var hue
= (1.0 * idx
/ (1 + num
));
732 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
735 for (var i
= 0; i
< num
; i
++) {
736 if (!this.visibility()[i
]) continue;
737 var colorStr
= colors
[i
% colors
.length
];
738 this.colors_
.push(colorStr
);
742 this.plotter_
.setColors(this.colors_
);
746 * Return the list of colors. This is either the list of colors passed in the
747 * attributes or the autogenerated list of rgb(r,g,b) strings.
748 * @return {Array<string>} The list of colors.
750 Dygraph
.prototype.getColors
= function() {
755 * Create the div that contains information on the selected point(s)
756 * This goes in the top right of the canvas, unless an external div has already
760 Dygraph
.prototype.createStatusMessage_
= function() {
761 var userLabelsDiv
= this.user_attrs_
["labelsDiv"];
762 if (userLabelsDiv
&& null != userLabelsDiv
763 && (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
)) {
764 this.user_attrs_
["labelsDiv"] = document
.getElementById(userLabelsDiv
);
766 if (!this.attr_("labelsDiv")) {
767 var divWidth
= this.attr_('labelsDivWidth');
769 "position": "absolute",
772 "width": divWidth
+ "px",
774 "left": (this.width_
- divWidth
- 2) + "px",
775 "background": "white",
777 "overflow": "hidden"};
778 Dygraph
.update(messagestyle
, this.attr_('labelsDivStyles'));
779 var div
= document
.createElement("div");
780 for (var name
in messagestyle
) {
781 if (messagestyle
.hasOwnProperty(name
)) {
782 div
.style
[name
] = messagestyle
[name
];
785 this.graphDiv
.appendChild(div
);
786 this.attrs_
.labelsDiv
= div
;
791 * Position the labels div so that:
792 * - its right edge is flush with the right edge of the charting area
793 * - its top edge is flush with the top edge of the charting area
796 Dygraph
.prototype.positionLabelsDiv_
= function() {
797 // Don't touch a user-specified labelsDiv.
798 if (this.user_attrs_
.hasOwnProperty("labelsDiv")) return;
800 var area
= this.plotter_
.area
;
801 var div
= this.attr_("labelsDiv");
802 div
.style
.left
= area
.x
+ area
.w
- this.attr_("labelsDivWidth") - 1 + "px";
803 div
.style
.top
= area
.y
+ "px";
807 * Create the text box to adjust the averaging period
810 Dygraph
.prototype.createRollInterface_
= function() {
811 // Create a roller if one doesn't exist already.
813 this.roller_
= document
.createElement("input");
814 this.roller_
.type
= "text";
815 this.roller_
.style
.display
= "none";
816 this.graphDiv
.appendChild(this.roller_
);
819 var display
= this.attr_('showRoller') ? 'block' : 'none';
821 var area
= this.plotter_
.area
;
822 var textAttr
= { "position": "absolute",
824 "top": (area
.y
+ area
.h
- 25) + "px",
825 "left": (area
.x
+ 1) + "px",
828 this.roller_
.size
= "2";
829 this.roller_
.value
= this.rollPeriod_
;
830 for (var name
in textAttr
) {
831 if (textAttr
.hasOwnProperty(name
)) {
832 this.roller_
.style
[name
] = textAttr
[name
];
837 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
842 * Converts page the x-coordinate of the event to pixel x-coordinates on the
843 * canvas (i.e. DOM Coords).
845 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
846 return Dygraph
.pageX(e
) - context
.px
851 * Converts page the y-coordinate of the event to pixel y-coordinates on the
852 * canvas (i.e. DOM Coords).
854 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
855 return Dygraph
.pageY(e
) - context
.py
859 * Set up all the mouse handlers needed to capture dragging behavior for zoom
863 Dygraph
.prototype.createDragInterface_
= function() {
865 // Tracks whether the mouse is down right now
867 isPanning
: false, // is this drag part of a pan?
868 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
869 dragStartX
: null, // pixel coordinates
870 dragStartY
: null, // pixel coordinates
871 dragEndX
: null, // pixel coordinates
872 dragEndY
: null, // pixel coordinates
874 prevEndX
: null, // pixel coordinates
875 prevEndY
: null, // pixel coordinates
876 prevDragDirection
: null,
878 // The value on the left side of the graph when a pan operation starts.
879 initialLeftmostDate
: null,
881 // The number of units each pixel spans. (This won't be valid for log
883 xUnitsPerPixel
: null,
885 // TODO(danvk): update this comment
886 // The range in second/value units that the viewport encompasses during a
887 // panning operation.
890 // Top-left corner of the canvas, in DOM coords
891 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
895 // Values for use with panEdgeFraction, which limit how far outside the
896 // graph's data boundaries it can be panned.
897 boundedDates
: null, // [minDate, maxDate]
898 boundedValues
: null, // [[minValue, maxValue] ...]
900 initializeMouseDown
: function(event
, g
, context
) {
901 // prevents mouse drags from selecting page text.
902 if (event
.preventDefault
) {
903 event
.preventDefault(); // Firefox, Chrome, etc.
905 event
.returnValue
= false; // IE
906 event
.cancelBubble
= true;
909 context
.px
= Dygraph
.findPosX(g
.canvas_
);
910 context
.py
= Dygraph
.findPosY(g
.canvas_
);
911 context
.dragStartX
= g
.dragGetX_(event
, context
);
912 context
.dragStartY
= g
.dragGetY_(event
, context
);
916 var interactionModel
= this.attr_("interactionModel");
918 // Self is the graph.
921 // Function that binds the graph and context to the handler.
922 var bindHandler
= function(handler
) {
923 return function(event
) {
924 handler(event
, self
, context
);
928 for (var eventName
in interactionModel
) {
929 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
930 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
931 bindHandler(interactionModel
[eventName
]));
934 // If the user releases the mouse button during a drag, but not over the
935 // canvas, then it doesn't count as a zooming action.
936 Dygraph
.addEvent(document
, 'mouseup', function(event
) {
937 if (context
.isZooming
|| context
.isPanning
) {
938 context
.isZooming
= false;
939 context
.dragStartX
= null;
940 context
.dragStartY
= null;
943 if (context
.isPanning
) {
944 context
.isPanning
= false;
945 context
.draggingDate
= null;
946 context
.dateRange
= null;
947 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
948 delete self
.axes_
[i
].draggingValue
;
949 delete self
.axes_
[i
].dragValueRange
;
957 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
958 * up any previous zoom rectangles that were drawn. This could be optimized to
959 * avoid extra redrawing, but it's tricky to avoid interactions with the status
962 * @param {Number} direction the direction of the zoom rectangle. Acceptable
963 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
964 * @param {Number} startX The X position where the drag started, in canvas
966 * @param {Number} endX The current X position of the drag, in canvas coords.
967 * @param {Number} startY The Y position where the drag started, in canvas
969 * @param {Number} endY The current Y position of the drag, in canvas coords.
970 * @param {Number} prevDirection the value of direction on the previous call to
971 * this function. Used to avoid excess redrawing
972 * @param {Number} prevEndX The value of endX on the previous call to this
973 * function. Used to avoid excess redrawing
974 * @param {Number} prevEndY The value of endY on the previous call to this
975 * function. Used to avoid excess redrawing
978 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
979 endY
, prevDirection
, prevEndX
,
981 var ctx
= this.canvas_ctx_
;
983 // Clean up from the previous rect if necessary
984 if (prevDirection
== Dygraph
.HORIZONTAL
) {
985 ctx
.clearRect(Math
.min(startX
, prevEndX
), 0,
986 Math
.abs(startX
- prevEndX
), this.height_
);
987 } else if (prevDirection
== Dygraph
.VERTICAL
){
988 ctx
.clearRect(0, Math
.min(startY
, prevEndY
),
989 this.width_
, Math
.abs(startY
- prevEndY
));
992 // Draw a light-grey rectangle to show the new viewing area
993 if (direction
== Dygraph
.HORIZONTAL
) {
994 if (endX
&& startX
) {
995 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
996 ctx
.fillRect(Math
.min(startX
, endX
), 0,
997 Math
.abs(endX
- startX
), this.height_
);
1000 if (direction
== Dygraph
.VERTICAL
) {
1001 if (endY
&& startY
) {
1002 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1003 ctx
.fillRect(0, Math
.min(startY
, endY
),
1004 this.width_
, Math
.abs(endY
- startY
));
1010 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1011 * the canvas. The exact zoom window may be slightly larger if there are no data
1012 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1013 * which accepts dates that match the raw data. This function redraws the graph.
1015 * @param {Number} lowX The leftmost pixel value that should be visible.
1016 * @param {Number} highX The rightmost pixel value that should be visible.
1019 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1020 // Find the earliest and latest dates contained in this canvasx range.
1021 // Convert the call to date ranges of the raw data.
1022 var minDate
= this.toDataXCoord(lowX
);
1023 var maxDate
= this.toDataXCoord(highX
);
1024 this.doZoomXDates_(minDate
, maxDate
);
1028 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1029 * method with doZoomX which accepts pixel coordinates. This function redraws
1032 * @param {Number} minDate The minimum date that should be visible.
1033 * @param {Number} maxDate The maximum date that should be visible.
1036 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1037 this.dateWindow_
= [minDate
, maxDate
];
1038 this.zoomed_x_
= true;
1040 if (this.attr_("zoomCallback")) {
1041 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1046 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1047 * the canvas. This function redraws the graph.
1049 * @param {Number} lowY The topmost pixel value that should be visible.
1050 * @param {Number} highY The lowest pixel value that should be visible.
1053 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1054 // Find the highest and lowest values in pixel range for each axis.
1055 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1056 // This is because pixels increase as you go down on the screen, whereas data
1057 // coordinates increase as you go up the screen.
1058 var valueRanges
= [];
1059 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1060 var hi
= this.toDataYCoord(lowY
, i
);
1061 var low
= this.toDataYCoord(highY
, i
);
1062 this.axes_
[i
].valueWindow
= [low
, hi
];
1063 valueRanges
.push([low
, hi
]);
1066 this.zoomed_y_
= true;
1068 if (this.attr_("zoomCallback")) {
1069 var xRange
= this.xAxisRange();
1070 var yRange
= this.yAxisRange();
1071 this.attr_("zoomCallback")(xRange
[0], xRange
[1], this.yAxisRanges());
1076 * Reset the zoom to the original view coordinates. This is the same as
1077 * double-clicking on the graph.
1081 Dygraph
.prototype.doUnzoom_
= function() {
1083 if (this.dateWindow_
!= null) {
1085 this.dateWindow_
= null;
1088 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1089 if (this.axes_
[i
].valueWindow
!= null) {
1091 delete this.axes_
[i
].valueWindow
;
1095 // Clear any selection, since it's likely to be drawn in the wrong place.
1096 this.clearSelection();
1099 // Putting the drawing operation before the callback because it resets
1101 this.zoomed_x_
= false;
1102 this.zoomed_y_
= false;
1104 if (this.attr_("zoomCallback")) {
1105 var minDate
= this.rawData_
[0][0];
1106 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1107 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1113 * When the mouse moves in the canvas, display information about a nearby data
1114 * point and draw dots over those points in the data series. This function
1115 * takes care of cleanup of previously-drawn dots.
1116 * @param {Object} event The mousemove event from the browser.
1119 Dygraph
.prototype.mouseMove_
= function(event
) {
1120 // This prevents JS errors when mousing over the canvas before data loads.
1121 var points
= this.layout_
.points
;
1122 if (points
=== undefined
) return;
1124 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1129 // Loop through all the points and find the date nearest to our current
1131 var minDist
= 1e+100;
1133 for (var i
= 0; i
< points
.length
; i
++) {
1134 var point
= points
[i
];
1135 if (point
== null) continue;
1136 var dist
= Math
.abs(point
.canvasx
- canvasx
);
1137 if (dist
> minDist
) continue;
1141 if (idx
>= 0) lastx
= points
[idx
].xval
;
1143 // Extract the points we've selected
1144 this.selPoints_
= [];
1145 var l
= points
.length
;
1146 if (!this.attr_("stackedGraph")) {
1147 for (var i
= 0; i
< l
; i
++) {
1148 if (points
[i
].xval
== lastx
) {
1149 this.selPoints_
.push(points
[i
]);
1153 // Need to 'unstack' points starting from the bottom
1154 var cumulative_sum
= 0;
1155 for (var i
= l
- 1; i
>= 0; i
--) {
1156 if (points
[i
].xval
== lastx
) {
1157 var p
= {}; // Clone the point since we modify it
1158 for (var k
in points
[i
]) {
1159 p
[k
] = points
[i
][k
];
1161 p
.yval
-= cumulative_sum
;
1162 cumulative_sum
+= p
.yval
;
1163 this.selPoints_
.push(p
);
1166 this.selPoints_
.reverse();
1169 if (this.attr_("highlightCallback")) {
1170 var px
= this.lastx_
;
1171 if (px
!== null && lastx
!= px
) {
1172 // only fire if the selected point has changed.
1173 this.attr_("highlightCallback")(event
, lastx
, this.selPoints_
, this.idxToRow_(idx
));
1177 // Save last x position for callbacks.
1178 this.lastx_
= lastx
;
1180 this.updateSelection_();
1184 * Transforms layout_.points index into data row number.
1185 * @param int layout_.points index
1186 * @return int row number, or -1 if none could be found.
1189 Dygraph
.prototype.idxToRow_
= function(idx
) {
1190 if (idx
< 0) return -1;
1192 for (var i
in this.layout_
.datasets
) {
1193 if (idx
< this.layout_
.datasets
[i
].length
) {
1194 return this.boundaryIds_
[0][0]+idx
;
1196 idx
-= this.layout_
.datasets
[i
].length
;
1203 * Generates HTML for the legend which is displayed when hovering over the
1204 * chart. If no selected points are specified, a default legend is returned
1205 * (this may just be the empty string).
1206 * @param { Number } [x] The x-value of the selected points.
1207 * @param { [Object] } [sel_points] List of selected points for the given
1208 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1210 Dygraph
.prototype.generateLegendHTML_
= function(x
, sel_points
) {
1211 // If no points are selected, we display a default legend. Traditionally,
1212 // this has been blank. But a better default would be a conventional legend,
1213 // which provides essential information for a non-interactive chart.
1214 if (typeof(x
) === 'undefined') {
1215 if (this.attr_('legend') != 'always') return '';
1217 var sepLines
= this.attr_('labelsSeparateLines');
1218 var labels
= this.attr_('labels');
1220 for (var i
= 1; i
< labels
.length
; i
++) {
1221 if (!this.visibility()[i
- 1]) continue;
1222 var c
= this.plotter_
.colors
[labels
[i
]];
1223 if (html
!= '') html
+= (sepLines
? '<br/>' : ' ');
1224 html
+= "<b><span style='color: " + c
+ ";'>—" + labels
[i
] +
1230 var html
= this.attr_('xValueFormatter')(x
) + ":";
1232 var fmtFunc
= this.attr_('yValueFormatter');
1233 var showZeros
= this.attr_("labelsShowZeroValues");
1234 var sepLines
= this.attr_("labelsSeparateLines");
1235 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1236 var pt
= this.selPoints_
[i
];
1237 if (pt
.yval
== 0 && !showZeros
) continue;
1238 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1239 if (sepLines
) html
+= "<br/>";
1241 var c
= this.plotter_
.colors
[pt
.name
];
1242 var yval
= fmtFunc(pt
.yval
, this);
1243 // TODO(danvk): use a template string here and make it an attribute.
1244 html
+= " <b><span style='color: " + c
+ ";'>"
1245 + pt
.name
+ "</span></b>:"
1253 * Displays information about the selected points in the legend. If there is no
1254 * selection, the legend will be cleared.
1255 * @param { Number } [x] The x-value of the selected points.
1256 * @param { [Object] } [sel_points] List of selected points for the given
1257 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1259 Dygraph
.prototype.setLegendHTML_
= function(x
, sel_points
) {
1260 var html
= this.generateLegendHTML_(x
, sel_points
);
1261 var labelsDiv
= this.attr_("labelsDiv");
1262 if (labelsDiv
!== null) {
1263 labelsDiv
.innerHTML
= html
;
1265 if (typeof(this.shown_legend_error_
) == 'undefined') {
1266 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1267 this.shown_legend_error_
= true;
1273 * Draw dots over the selectied points in the data series. This function
1274 * takes care of cleanup of previously-drawn dots.
1277 Dygraph
.prototype.updateSelection_
= function() {
1278 // Clear the previously drawn vertical, if there is one
1279 var ctx
= this.canvas_ctx_
;
1280 if (this.previousVerticalX_
>= 0) {
1281 // Determine the maximum highlight circle size.
1282 var maxCircleSize
= 0;
1283 var labels
= this.attr_('labels');
1284 for (var i
= 1; i
< labels
.length
; i
++) {
1285 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1286 if (r
> maxCircleSize
) maxCircleSize
= r
;
1288 var px
= this.previousVerticalX_
;
1289 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1290 2 * maxCircleSize
+ 2, this.height_
);
1293 if (this.selPoints_
.length
> 0) {
1294 // Set the status message to indicate the selected point(s)
1295 if (this.attr_('showLabelsOnHighlight')) {
1296 this.setLegendHTML_(this.lastx_
, this.selPoints_
);
1299 // Draw colored circles over the center of each selected point
1300 var canvasx
= this.selPoints_
[0].canvasx
;
1302 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1303 var pt
= this.selPoints_
[i
];
1304 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1306 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1308 ctx
.fillStyle
= this.plotter_
.colors
[pt
.name
];
1309 ctx
.arc(canvasx
, pt
.canvasy
, circleSize
, 0, 2 * Math
.PI
, false);
1314 this.previousVerticalX_
= canvasx
;
1319 * Manually set the selected points and display information about them in the
1320 * legend. The selection can be cleared using clearSelection() and queried
1321 * using getSelection().
1322 * @param { Integer } row number that should be highlighted (i.e. appear with
1323 * hover dots on the chart). Set to false to clear any selection.
1325 Dygraph
.prototype.setSelection
= function(row
) {
1326 // Extract the points we've selected
1327 this.selPoints_
= [];
1330 if (row
!== false) {
1331 row
= row
-this.boundaryIds_
[0][0];
1334 if (row
!== false && row
>= 0) {
1335 for (var i
in this.layout_
.datasets
) {
1336 if (row
< this.layout_
.datasets
[i
].length
) {
1337 var point
= this.layout_
.points
[pos
+row
];
1339 if (this.attr_("stackedGraph")) {
1340 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
1343 this.selPoints_
.push(point
);
1345 pos
+= this.layout_
.datasets
[i
].length
;
1349 if (this.selPoints_
.length
) {
1350 this.lastx_
= this.selPoints_
[0].xval
;
1351 this.updateSelection_();
1353 this.clearSelection();
1359 * The mouse has left the canvas. Clear out whatever artifacts remain
1360 * @param {Object} event the mouseout event from the browser.
1363 Dygraph
.prototype.mouseOut_
= function(event
) {
1364 if (this.attr_("unhighlightCallback")) {
1365 this.attr_("unhighlightCallback")(event
);
1368 if (this.attr_("hideOverlayOnMouseOut")) {
1369 this.clearSelection();
1374 * Clears the current selection (i.e. points that were highlighted by moving
1375 * the mouse over the chart).
1377 Dygraph
.prototype.clearSelection
= function() {
1378 // Get rid of the overlay data
1379 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1380 this.setLegendHTML_();
1381 this.selPoints_
= [];
1386 * Returns the number of the currently selected row. To get data for this row,
1387 * you can use the getValue method.
1388 * @return { Integer } row number, or -1 if nothing is selected
1390 Dygraph
.prototype.getSelection
= function() {
1391 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1395 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
1396 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
1397 return row
+ this.boundaryIds_
[0][0];
1405 * Return a string version of a number. This respects the digitsAfterDecimal
1406 * and maxNumberWidth options.
1407 * @param {Number} x The number to be formatted
1408 * @param {Dygraph} g The dygraph object
1410 Dygraph
.numberFormatter
= function(x
, g
) {
1411 var sigFigs
= g
.attr_('sigFigs');
1413 if (sigFigs
!== null) {
1414 // User has opted for a fixed number of significant figures.
1415 return Dygraph
.floatFormat(x
, sigFigs
);
1418 var digits
= g
.attr_('digitsAfterDecimal');
1419 var maxNumberWidth
= g
.attr_('maxNumberWidth');
1421 // switch to scientific notation if we underflow or overflow fixed display.
1423 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
1424 Math
.abs(x
) < Math
.pow(10, -digits
))) {
1425 return x
.toExponential(digits
);
1427 return '' + Dygraph
.round_(x
, digits
);
1432 * Convert a JS date to a string appropriate to display on an axis that
1433 * is displaying values at the stated granularity.
1434 * @param {Date} date The date to format
1435 * @param {Number} granularity One of the Dygraph granularity constants
1436 * @return {String} The formatted date
1439 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
1440 if (granularity
>= Dygraph
.DECADAL
) {
1441 return date
.strftime('%Y');
1442 } else if (granularity
>= Dygraph
.MONTHLY
) {
1443 return date
.strftime('%b %y');
1445 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
1446 if (frac
== 0 || granularity
>= Dygraph
.DAILY
) {
1447 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
1449 return Dygraph
.hmsString_(date
.getTime());
1455 * Fires when there's data available to be graphed.
1456 * @param {String} data Raw CSV data to be plotted
1459 Dygraph
.prototype.loadedEvent_
= function(data
) {
1460 this.rawData_
= this.parseCSV_(data
);
1464 Dygraph
.prototype.months
= ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
1465 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
1466 Dygraph
.prototype.quarters
= ["Jan", "Apr", "Jul", "Oct"];
1469 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1472 Dygraph
.prototype.addXTicks_
= function() {
1473 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1475 if (this.dateWindow_
) {
1476 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
1478 range
= [this.rawData_
[0][0], this.rawData_
[this.rawData_
.length
- 1][0]];
1481 var xTicks
= this.attr_('xTicker')(range
[0], range
[1], this);
1482 this.layout_
.setXTicks(xTicks
);
1485 // Time granularity enumeration
1486 Dygraph
.SECONDLY
= 0;
1487 Dygraph
.TWO_SECONDLY
= 1;
1488 Dygraph
.FIVE_SECONDLY
= 2;
1489 Dygraph
.TEN_SECONDLY
= 3;
1490 Dygraph
.THIRTY_SECONDLY
= 4;
1491 Dygraph
.MINUTELY
= 5;
1492 Dygraph
.TWO_MINUTELY
= 6;
1493 Dygraph
.FIVE_MINUTELY
= 7;
1494 Dygraph
.TEN_MINUTELY
= 8;
1495 Dygraph
.THIRTY_MINUTELY
= 9;
1496 Dygraph
.HOURLY
= 10;
1497 Dygraph
.TWO_HOURLY
= 11;
1498 Dygraph
.SIX_HOURLY
= 12;
1500 Dygraph
.WEEKLY
= 14;
1501 Dygraph
.MONTHLY
= 15;
1502 Dygraph
.QUARTERLY
= 16;
1503 Dygraph
.BIANNUAL
= 17;
1504 Dygraph
.ANNUAL
= 18;
1505 Dygraph
.DECADAL
= 19;
1506 Dygraph
.CENTENNIAL
= 20;
1507 Dygraph
.NUM_GRANULARITIES
= 21;
1509 Dygraph
.SHORT_SPACINGS
= [];
1510 Dygraph
.SHORT_SPACINGS
[Dygraph
.SECONDLY
] = 1000 * 1;
1511 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_SECONDLY
] = 1000 * 2;
1512 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_SECONDLY
] = 1000 * 5;
1513 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_SECONDLY
] = 1000 * 10;
1514 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_SECONDLY
] = 1000 * 30;
1515 Dygraph
.SHORT_SPACINGS
[Dygraph
.MINUTELY
] = 1000 * 60;
1516 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_MINUTELY
] = 1000 * 60 * 2;
1517 Dygraph
.SHORT_SPACINGS
[Dygraph
.FIVE_MINUTELY
] = 1000 * 60 * 5;
1518 Dygraph
.SHORT_SPACINGS
[Dygraph
.TEN_MINUTELY
] = 1000 * 60 * 10;
1519 Dygraph
.SHORT_SPACINGS
[Dygraph
.THIRTY_MINUTELY
] = 1000 * 60 * 30;
1520 Dygraph
.SHORT_SPACINGS
[Dygraph
.HOURLY
] = 1000 * 3600;
1521 Dygraph
.SHORT_SPACINGS
[Dygraph
.TWO_HOURLY
] = 1000 * 3600 * 2;
1522 Dygraph
.SHORT_SPACINGS
[Dygraph
.SIX_HOURLY
] = 1000 * 3600 * 6;
1523 Dygraph
.SHORT_SPACINGS
[Dygraph
.DAILY
] = 1000 * 86400;
1524 Dygraph
.SHORT_SPACINGS
[Dygraph
.WEEKLY
] = 1000 * 604800;
1528 * If we used this time granularity, how many ticks would there be?
1529 * This is only an approximation, but it's generally good enough.
1531 Dygraph
.prototype.NumXTicks
= function(start_time
, end_time
, granularity
) {
1532 if (granularity
< Dygraph
.MONTHLY
) {
1533 // Generate one tick mark for every fixed interval of time.
1534 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
1535 return Math
.floor(0.5 + 1.0 * (end_time
- start_time
) / spacing
);
1537 var year_mod
= 1; // e.g. to only print one point every 10 years.
1538 var num_months
= 12;
1539 if (granularity
== Dygraph
.QUARTERLY
) num_months
= 3;
1540 if (granularity
== Dygraph
.BIANNUAL
) num_months
= 2;
1541 if (granularity
== Dygraph
.ANNUAL
) num_months
= 1;
1542 if (granularity
== Dygraph
.DECADAL
) { num_months
= 1; year_mod
= 10; }
1543 if (granularity
== Dygraph
.CENTENNIAL
) { num_months
= 1; year_mod
= 100; }
1545 var msInYear
= 365.2524 * 24 * 3600 * 1000;
1546 var num_years
= 1.0 * (end_time
- start_time
) / msInYear
;
1547 return Math
.floor(0.5 + 1.0 * num_years
* num_months
/ year_mod
);
1554 * Construct an x-axis of nicely-formatted times on meaningful boundaries
1555 * (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1557 * Returns an array containing {v: millis, label: label} dictionaries.
1559 Dygraph
.prototype.GetXAxis
= function(start_time
, end_time
, granularity
) {
1560 var formatter
= this.attr_("xAxisLabelFormatter");
1562 if (granularity
< Dygraph
.MONTHLY
) {
1563 // Generate one tick mark for every fixed interval of time.
1564 var spacing
= Dygraph
.SHORT_SPACINGS
[granularity
];
1565 var format
= '%d%b'; // e.g. "1Jan"
1567 // Find a time less than start_time which occurs on a "nice" time boundary
1568 // for this granularity.
1569 var g
= spacing
/ 1000;
1570 var d
= new Date(start_time
);
1571 if (g
<= 60) { // seconds
1572 var x
= d
.getSeconds(); d
.setSeconds(x
- x
% g
);
1576 if (g
<= 60) { // minutes
1577 var x
= d
.getMinutes(); d
.setMinutes(x
- x
% g
);
1582 if (g
<= 24) { // days
1583 var x
= d
.getHours(); d
.setHours(x
- x
% g
);
1588 if (g
== 7) { // one week
1589 d
.setDate(d
.getDate() - d
.getDay());
1594 start_time
= d
.getTime();
1596 for (var t
= start_time
; t
<= end_time
; t
+= spacing
) {
1597 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
1600 // Display a tick mark on the first of a set of months of each year.
1601 // Years get a tick mark iff y % year_mod == 0. This is useful for
1602 // displaying a tick mark once every 10 years, say, on long time scales.
1604 var year_mod
= 1; // e.g. to only print one point every 10 years.
1606 if (granularity
== Dygraph
.MONTHLY
) {
1607 months
= [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
1608 } else if (granularity
== Dygraph
.QUARTERLY
) {
1609 months
= [ 0, 3, 6, 9 ];
1610 } else if (granularity
== Dygraph
.BIANNUAL
) {
1612 } else if (granularity
== Dygraph
.ANNUAL
) {
1614 } else if (granularity
== Dygraph
.DECADAL
) {
1617 } else if (granularity
== Dygraph
.CENTENNIAL
) {
1621 this.warn("Span of dates is too long");
1624 var start_year
= new Date(start_time
).getFullYear();
1625 var end_year
= new Date(end_time
).getFullYear();
1626 var zeropad
= Dygraph
.zeropad
;
1627 for (var i
= start_year
; i
<= end_year
; i
++) {
1628 if (i
% year_mod
!= 0) continue;
1629 for (var j
= 0; j
< months
.length
; j
++) {
1630 var date_str
= i
+ "/" + zeropad(1 + months[j]) + "/01";
1631 var t
= Dygraph
.dateStrToMillis(date_str
);
1632 if (t
< start_time
|| t
> end_time
) continue;
1633 ticks
.push({ v
:t
, label
: formatter(new Date(t
), granularity
) });
1643 * Add ticks to the x-axis based on a date range.
1644 * @param {Number} startDate Start of the date window (millis since epoch)
1645 * @param {Number} endDate End of the date window (millis since epoch)
1646 * @param {Dygraph} self The dygraph object
1647 * @return { [Object] } Array of {label, value} tuples.
1650 Dygraph
.dateTicker
= function(startDate
, endDate
, self
) {
1651 // TODO(danvk): why does this take 'self' as a param?
1653 for (var i
= 0; i
< Dygraph
.NUM_GRANULARITIES
; i
++) {
1654 var num_ticks
= self
.NumXTicks(startDate
, endDate
, i
);
1655 if (self
.width_
/ num_ticks
>= self
.attr_('pixelsPerXLabel')) {
1662 return self
.GetXAxis(startDate
, endDate
, chosen
);
1664 // TODO(danvk): signal error.
1670 * This is a list of human-friendly values at which to show tick marks on a log
1671 * scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
1672 * ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
1673 * NOTE: this assumes that Dygraph.LOG_SCALE = 10.
1675 Dygraph
.PREFERRED_LOG_TICK_VALUES
= function() {
1677 for (var power
= -39; power
<= 39; power
++) {
1678 var range
= Math
.pow(10, power
);
1679 for (var mult
= 1; mult
<= 9; mult
++) {
1680 var val
= range
* mult
;
1687 // TODO(konigsberg): Update comment.
1689 * Add ticks when the x axis has numbers on it (instead of dates)
1691 * @param {Number} minV minimum value
1692 * @param {Number} maxV maximum value
1694 * @param {function} attribute accessor function.
1695 * @return {[Object]} Array of {label, value} tuples.
1697 Dygraph
.numericTicks
= function(minV
, maxV
, self
, axis_props
, vals
) {
1698 var attr
= function(k
) {
1699 if (axis_props
&& axis_props
.hasOwnProperty(k
)) return axis_props
[k
];
1700 return self
.attr_(k
);
1705 for (var i
= 0; i
< vals
.length
; i
++) {
1706 ticks
.push({v
: vals
[i
]});
1709 if (axis_props
&& attr("logscale")) {
1710 var pixelsPerTick
= attr('pixelsPerYLabel');
1711 // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
1712 var nTicks
= Math
.floor(self
.height_
/ pixelsPerTick
);
1713 var minIdx
= Dygraph
.binarySearch(minV
, Dygraph
.PREFERRED_LOG_TICK_VALUES
, 1);
1714 var maxIdx
= Dygraph
.binarySearch(maxV
, Dygraph
.PREFERRED_LOG_TICK_VALUES
, -1);
1719 maxIdx
= Dygraph
.PREFERRED_LOG_TICK_VALUES
.length
- 1;
1721 // Count the number of tick values would appear, if we can get at least
1722 // nTicks / 4 accept them
.
1723 var lastDisplayed
= null;
1724 if (maxIdx
- minIdx
>= nTicks
/ 4) {
1725 var axisId
= axis_props
.yAxisId
;
1726 for (var idx
= maxIdx
; idx
>= minIdx
; idx
--) {
1727 var tickValue
= Dygraph
.PREFERRED_LOG_TICK_VALUES
[idx
];
1728 var domCoord
= axis_props
.g
.toDomYCoord(tickValue
, axisId
);
1729 var tick
= { v
: tickValue
};
1730 if (lastDisplayed
== null) {
1732 tickValue
: tickValue
,
1736 if (domCoord
- lastDisplayed
.domCoord
>= pixelsPerTick
) {
1738 tickValue
: tickValue
,
1747 // Since we went in backwards order.
1752 // ticks.length won't be 0 if the log scale function finds values to insert.
1753 if (ticks
.length
== 0) {
1755 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
1756 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks
).
1757 // The first spacing greater than pixelsPerYLabel is what we use.
1758 // TODO(danvk): version that works on a log scale.
1759 if (attr("labelsKMG2")) {
1760 var mults
= [1, 2, 4, 8];
1762 var mults
= [1, 2, 5];
1764 var scale
, low_val
, high_val
, nTicks
;
1765 // TODO(danvk): make it possible to set this for x- and y-axes independently.
1766 var pixelsPerTick
= attr('pixelsPerYLabel');
1767 for (var i
= -10; i
< 50; i
++) {
1768 if (attr("labelsKMG2")) {
1769 var base_scale
= Math
.pow(16, i
);
1771 var base_scale
= Math
.pow(10, i
);
1773 for (var j
= 0; j
< mults
.length
; j
++) {
1774 scale
= base_scale
* mults
[j
];
1775 low_val
= Math
.floor(minV
/ scale
) * scale
;
1776 high_val
= Math
.ceil(maxV
/ scale
) * scale
;
1777 nTicks
= Math
.abs(high_val
- low_val
) / scale
;
1778 var spacing
= self
.height_
/ nTicks
;
1779 // wish I could break out of both loops at once...
1780 if (spacing
> pixelsPerTick
) break;
1782 if (spacing
> pixelsPerTick
) break;
1785 // Construct the set of ticks.
1786 // Allow reverse y-axis if it's explicitly requested.
1787 if (low_val
> high_val
) scale
*= -1;
1788 for (var i
= 0; i
< nTicks
; i
++) {
1789 var tickV
= low_val
+ i
* scale
;
1790 ticks
.push( {v
: tickV
} );
1795 // Add formatted labels to the ticks.
1798 if (attr("labelsKMB")) {
1800 k_labels
= [ "K", "M", "B", "T" ];
1802 if (attr("labelsKMG2")) {
1803 if (k
) self
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1805 k_labels
= [ "k", "M", "G", "T" ];
1807 var formatter
= attr('yAxisLabelFormatter') ?
1808 attr('yAxisLabelFormatter') : attr('yValueFormatter');
1810 // Add labels to the ticks.
1811 for (var i
= 0; i
< ticks
.length
; i
++) {
1812 if (ticks
[i
].label
!== undefined
) continue; // Use current label.
1813 var tickV
= ticks
[i
].v
;
1814 var absTickV
= Math
.abs(tickV
);
1815 var label
= formatter(tickV
, self
);
1816 if (k_labels
.length
> 0) {
1817 // Round up to an appropriate unit.
1819 for (var j
= 3; j
>= 0; j
--, n
/= k
) {
1820 if (absTickV
>= n
) {
1821 label
= Dygraph
.round_(tickV
/ n
, attr('digitsAfterDecimal')) + k_labels
[j
];
1826 ticks
[i
].label
= label
;
1834 * Computes the range of the data series (including confidence intervals).
1835 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
1836 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
1837 * @return [low, high]
1839 Dygraph
.prototype.extremeValues_
= function(series
) {
1840 var minY
= null, maxY
= null;
1842 var bars
= this.attr_("errorBars") || this.attr_("customBars");
1844 // With custom bars, maxY is the max of the high values.
1845 for (var j
= 0; j
< series
.length
; j
++) {
1846 var y
= series
[j
][1][0];
1848 var low
= y
- series
[j
][1][1];
1849 var high
= y
+ series
[j
][1][2];
1850 if (low
> y
) low
= y
; // this can happen with custom bars,
1851 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
1852 if (maxY
== null || high
> maxY
) {
1855 if (minY
== null || low
< minY
) {
1860 for (var j
= 0; j
< series
.length
; j
++) {
1861 var y
= series
[j
][1];
1862 if (y
=== null || isNaN(y
)) continue;
1863 if (maxY
== null || y
> maxY
) {
1866 if (minY
== null || y
< minY
) {
1872 return [minY
, maxY
];
1877 * This function is called once when the chart's data is changed or the options
1878 * dictionary is updated. It is _not_ called when the user pans or zooms. The
1879 * idea is that values derived from the chart's data can be computed here,
1880 * rather than every time the chart is drawn. This includes things like the
1881 * number of axes, rolling averages, etc.
1883 Dygraph
.prototype.predraw_
= function() {
1884 var start
= new Date();
1886 // TODO(danvk): move more computations out of drawGraph_ and into here.
1887 this.computeYAxes_();
1889 // Create a new plotter.
1890 if (this.plotter_
) this.plotter_
.clear();
1891 this.plotter_
= new DygraphCanvasRenderer(this,
1896 // The roller sits in the bottom left corner of the chart. We don't know where
1897 // this will be until the options are available, so it's positioned here.
1898 this.createRollInterface_();
1900 // Same thing applies for the labelsDiv. It's right edge should be flush with
1901 // the right edge of the charting area (which may not be the same as the right
1902 // edge of the div, if we have two y-axes.
1903 this.positionLabelsDiv_();
1905 // If the data or options have changed, then we'd better redraw.
1910 * Update the graph with new data. This method is called when the viewing area
1911 * has changed. If the underlying data or options have changed, predraw_ will
1912 * be called before drawGraph_ is called.
1914 * clearSelection, when undefined or true, causes this.clearSelection to be
1915 * called at the end of the draw operation. This should rarely be defined,
1916 * and never true (that is it should be undefined most of the time, and
1921 Dygraph
.prototype.drawGraph_
= function(clearSelection
) {
1922 var start
= new Date();
1924 if (typeof(clearSelection
) === 'undefined') {
1925 clearSelection
= true;
1928 var data
= this.rawData_
;
1930 // This is used to set the second parameter to drawCallback, below.
1931 var is_initial_draw
= this.is_initial_draw_
;
1932 this.is_initial_draw_
= false;
1934 var minY
= null, maxY
= null;
1935 this.layout_
.removeAllDatasets();
1937 this.attrs_
['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
1939 // Loop over the fields (series). Go from the last to the first,
1940 // because if they're stacked that's how we accumulate the values.
1942 var cumulative_y
= []; // For stacked series.
1945 var extremes
= {}; // series name -> [low, high]
1947 // Loop over all fields and create datasets
1948 for (var i
= data
[0].length
- 1; i
>= 1; i
--) {
1949 if (!this.visibility()[i
- 1]) continue;
1951 var seriesName
= this.attr_("labels")[i
];
1952 var connectSeparatedPoints
= this.attr_('connectSeparatedPoints', i
);
1953 var logScale
= this.attr_('logscale', i
);
1956 for (var j
= 0; j
< data
.length
; j
++) {
1957 var date
= data
[j
][0];
1958 var point
= data
[j
][i
];
1960 // On the log scale, points less than zero do not exist.
1961 // This will create a gap in the chart. Note that this ignores
1962 // connectSeparatedPoints.
1966 series
.push([date
, point
]);
1968 if (point
!= null || !connectSeparatedPoints
) {
1969 series
.push([date
, point
]);
1974 // TODO(danvk): move this into predraw_. It's insane to do it here.
1975 series
= this.rollingAverage(series
, this.rollPeriod_
);
1977 // Prune down to the desired range, if necessary (for zooming)
1978 // Because there can be lines going to points outside of the visible area,
1979 // we actually prune to visible points, plus one on either side.
1980 var bars
= this.attr_("errorBars") || this.attr_("customBars");
1981 if (this.dateWindow_
) {
1982 var low
= this.dateWindow_
[0];
1983 var high
= this.dateWindow_
[1];
1985 // TODO(danvk): do binary search instead of linear search.
1986 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
1987 var firstIdx
= null, lastIdx
= null;
1988 for (var k
= 0; k
< series
.length
; k
++) {
1989 if (series
[k
][0] >= low
&& firstIdx
=== null) {
1992 if (series
[k
][0] <= high
) {
1996 if (firstIdx
=== null) firstIdx
= 0;
1997 if (firstIdx
> 0) firstIdx
--;
1998 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
1999 if (lastIdx
< series
.length
- 1) lastIdx
++;
2000 this.boundaryIds_
[i
-1] = [firstIdx
, lastIdx
];
2001 for (var k
= firstIdx
; k
<= lastIdx
; k
++) {
2002 pruned
.push(series
[k
]);
2006 this.boundaryIds_
[i
-1] = [0, series
.length
-1];
2009 var seriesExtremes
= this.extremeValues_(series
);
2012 for (var j
=0; j
<series
.length
; j
++) {
2013 val
= [series
[j
][0], series
[j
][1][0], series
[j
][1][1], series
[j
][1][2]];
2016 } else if (this.attr_("stackedGraph")) {
2017 var l
= series
.length
;
2019 for (var j
= 0; j
< l
; j
++) {
2020 // If one data set has a NaN, let all subsequent stacked
2021 // sets inherit the NaN -- only start at 0 for the first set.
2022 var x
= series
[j
][0];
2023 if (cumulative_y
[x
] === undefined
) {
2024 cumulative_y
[x
] = 0;
2027 actual_y
= series
[j
][1];
2028 cumulative_y
[x
] += actual_y
;
2030 series
[j
] = [x
, cumulative_y
[x
]]
2032 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2033 seriesExtremes
[1] = cumulative_y
[x
];
2035 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2036 seriesExtremes
[0] = cumulative_y
[x
];
2040 extremes
[seriesName
] = seriesExtremes
;
2042 datasets
[i
] = series
;
2045 for (var i
= 1; i
< datasets
.length
; i
++) {
2046 if (!this.visibility()[i
- 1]) continue;
2047 this.layout_
.addDataset(this.attr_("labels")[i
], datasets
[i
]);
2050 this.computeYAxisRanges_(extremes
);
2051 this.layout_
.setYAxes(this.axes_
);
2055 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2056 var tmp_zoomed_x
= this.zoomed_x_
;
2057 // Tell PlotKit to use this new data and render itself
2058 this.layout_
.setDateWindow(this.dateWindow_
);
2059 this.zoomed_x_
= tmp_zoomed_x
;
2060 this.layout_
.evaluateWithError();
2061 this.plotter_
.clear();
2062 this.plotter_
.render();
2063 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2064 this.canvas_
.height
);
2066 if (is_initial_draw
) {
2067 // Generate a static legend before any particular point is selected.
2068 this.setLegendHTML_();
2070 if (clearSelection
) {
2071 if (typeof(this.selPoints_
) !== 'undefined' && this.selPoints_
.length
) {
2072 // We should select the point nearest the page x/y here
, but it
's easier
2073 // to just clear the selection. This prevents erroneous hover dots from
2075 this.clearSelection();
2077 this.clearSelection();
2082 if (this.attr_("drawCallback") !== null) {
2083 this.attr_("drawCallback")(this, is_initial_draw);
2086 if (this.attr_("timingName")) {
2087 var end = new Date();
2089 console.log(this.attr_("timingName") + " - drawGraph: " + (end - start) + "ms")
2096 * Determine properties of the y-axes which are independent of the data
2097 * currently being displayed. This includes things like the number of axes and
2098 * the style of the axes. It does not include the range of each axis and its
2100 * This fills in this.axes_ and this.seriesToAxisMap_.
2101 * axes_ = [ { options } ]
2102 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2103 * indices are into the axes_ array.
2105 Dygraph.prototype.computeYAxes_ = function() {
2106 // Preserve valueWindow settings if they exist, and if the user hasn't
2107 // specified a new valueRange.
2109 if (this.axes_
!= undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") == false) {
2111 for (var index
= 0; index
< this.axes_
.length
; index
++) {
2112 valueWindows
.push(this.axes_
[index
].valueWindow
);
2117 this.axes_
= [{ yAxisId
: 0, g
: this }]; // always have at least one y-axis.
2118 this.seriesToAxisMap_
= {};
2120 // Get a list of series names.
2121 var labels
= this.attr_("labels");
2123 for (var i
= 1; i
< labels
.length
; i
++) series
[labels
[i
]] = (i
- 1);
2125 // all options which could be applied per-axis:
2133 'axisLabelFontSize',
2138 // Copy global axis options over to the first axis.
2139 for (var i
= 0; i
< axisOptions
.length
; i
++) {
2140 var k
= axisOptions
[i
];
2141 var v
= this.attr_(k
);
2142 if (v
) this.axes_
[0][k
] = v
;
2145 // Go through once and add all the axes.
2146 for (var seriesName
in series
) {
2147 if (!series
.hasOwnProperty(seriesName
)) continue;
2148 var axis
= this.attr_("axis", seriesName
);
2150 this.seriesToAxisMap_
[seriesName
] = 0;
2153 if (typeof(axis
) == 'object') {
2154 // Add a new axis, making a copy of its per-axis options.
2156 Dygraph
.update(opts
, this.axes_
[0]);
2157 Dygraph
.update(opts
, { valueRange
: null }); // shouldn't inherit this.
2158 var yAxisId
= this.axes_
.length
;
2159 opts
.yAxisId
= yAxisId
;
2161 Dygraph
.update(opts
, axis
);
2162 this.axes_
.push(opts
);
2163 this.seriesToAxisMap_
[seriesName
] = yAxisId
;
2167 // Go through one more time and assign series to an axis defined by another
2168 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2169 for (var seriesName
in series
) {
2170 if (!series
.hasOwnProperty(seriesName
)) continue;
2171 var axis
= this.attr_("axis", seriesName
);
2172 if (typeof(axis
) == 'string') {
2173 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
2174 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
2175 "series " + axis
+ ", which does not define its own axis.");
2178 var idx
= this.seriesToAxisMap_
[axis
];
2179 this.seriesToAxisMap_
[seriesName
] = idx
;
2183 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2184 // this last so that hiding the first series doesn't destroy the axis
2185 // properties of the primary axis.
2186 var seriesToAxisFiltered
= {};
2187 var vis
= this.visibility();
2188 for (var i
= 1; i
< labels
.length
; i
++) {
2190 if (vis
[i
- 1]) seriesToAxisFiltered
[s
] = this.seriesToAxisMap_
[s
];
2192 this.seriesToAxisMap_
= seriesToAxisFiltered
;
2194 if (valueWindows
!= undefined
) {
2195 // Restore valueWindow settings.
2196 for (var index
= 0; index
< valueWindows
.length
; index
++) {
2197 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2203 * Returns the number of y-axes on the chart.
2204 * @return {Number} the number of axes.
2206 Dygraph
.prototype.numAxes
= function() {
2208 for (var series
in this.seriesToAxisMap_
) {
2209 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2210 var idx
= this.seriesToAxisMap_
[series
];
2211 if (idx
> last_axis
) last_axis
= idx
;
2213 return 1 + last_axis
;
2218 * Returns axis properties for the given series.
2219 * @param { String } setName The name of the series for which to get axis
2220 * properties, e.g. 'Y1'.
2221 * @return { Object } The axis properties.
2223 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2224 // TODO(danvk): handle errors.
2225 return this.axes_
[this.seriesToAxisMap_
[series
]];
2230 * Determine the value range and tick marks for each axis.
2231 * @param {Object} extremes A mapping from seriesName -> [low, high]
2232 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2234 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2235 // Build a map from axis number -> [list of series names]
2236 var seriesForAxis
= [];
2237 for (var series
in this.seriesToAxisMap_
) {
2238 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2239 var idx
= this.seriesToAxisMap_
[series
];
2240 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2241 seriesForAxis
[idx
].push(series
);
2244 // Compute extreme values, a span and tick marks for each axis.
2245 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2246 var axis
= this.axes_
[i
];
2248 if (!seriesForAxis
[i
]) {
2249 // If no series are defined or visible then use a reasonable default
2250 axis
.extremeRange
= [0, 1];
2252 // Calculate the extremes of extremes.
2253 var series
= seriesForAxis
[i
];
2254 var minY
= Infinity
; // extremes[series[0]][0];
2255 var maxY
= -Infinity
; // extremes[series[0]][1];
2256 var extremeMinY
, extremeMaxY
;
2257 for (var j
= 0; j
< series
.length
; j
++) {
2258 // Only use valid extremes to stop null data series' from corrupting the scale.
2259 extremeMinY
= extremes
[series
[j
]][0];
2260 if (extremeMinY
!= null) {
2261 minY
= Math
.min(extremeMinY
, minY
);
2263 extremeMaxY
= extremes
[series
[j
]][1];
2264 if (extremeMaxY
!= null) {
2265 maxY
= Math
.max(extremeMaxY
, maxY
);
2268 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2270 // Ensure we have a valid scale, otherwise defualt to zero for safety.
2271 if (minY
== Infinity
) minY
= 0;
2272 if (maxY
== -Infinity
) maxY
= 0;
2274 // Add some padding and round up to an integer to be human-friendly.
2275 var span
= maxY
- minY
;
2276 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2277 if (span
== 0) { span
= maxY
; }
2281 if (axis
.logscale
) {
2282 var maxAxisY
= maxY
+ 0.1 * span
;
2283 var minAxisY
= minY
;
2285 var maxAxisY
= maxY
+ 0.1 * span
;
2286 var minAxisY
= minY
- 0.1 * span
;
2288 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2289 if (!this.attr_("avoidMinZero")) {
2290 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2291 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2294 if (this.attr_("includeZero")) {
2295 if (maxY
< 0) maxAxisY
= 0;
2296 if (minY
> 0) minAxisY
= 0;
2299 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2301 if (axis
.valueWindow
) {
2302 // This is only set if the user has zoomed on the y-axis. It is never set
2303 // by a user. It takes precedence over axis.valueRange because, if you set
2304 // valueRange, you'd still expect to be able to pan.
2305 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2306 } else if (axis
.valueRange
) {
2307 // This is a user-set value range for this axis.
2308 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
2310 axis
.computedValueRange
= axis
.extremeRange
;
2313 // Add ticks. By default, all axes inherit the tick positions of the
2314 // primary axis. However, if an axis is specifically marked as having
2315 // independent ticks, then that is permissible as well.
2316 if (i
== 0 || axis
.independentTicks
) {
2318 Dygraph
.numericTicks(axis
.computedValueRange
[0],
2319 axis
.computedValueRange
[1],
2323 var p_axis
= this.axes_
[0];
2324 var p_ticks
= p_axis
.ticks
;
2325 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2326 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2327 var tick_values
= [];
2328 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2329 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2330 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2331 tick_values
.push(y_val
);
2335 Dygraph
.numericTicks(axis
.computedValueRange
[0],
2336 axis
.computedValueRange
[1],
2337 this, axis
, tick_values
);
2344 * Calculates the rolling average of a data set.
2345 * If originalData is [label, val], rolls the average of those.
2346 * If originalData is [label, [, it's interpreted as [value, stddev]
2347 * and the roll is returned in the same form, with appropriately reduced
2348 * stddev for each value.
2349 * Note that this is where fractional input (i.e. '5/10') is converted into
2351 * @param {Array} originalData The data in the appropriate format (see above)
2352 * @param {Number} rollPeriod The number of points over which to average the
2355 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2356 if (originalData
.length
< 2)
2357 return originalData
;
2358 var rollPeriod
= Math
.min(rollPeriod
, originalData
.length
- 1);
2359 var rollingData
= [];
2360 var sigma
= this.attr_("sigma");
2362 if (this.fractions_
) {
2364 var den
= 0; // numerator/denominator
2366 for (var i
= 0; i
< originalData
.length
; i
++) {
2367 num
+= originalData
[i
][1][0];
2368 den
+= originalData
[i
][1][1];
2369 if (i
- rollPeriod
>= 0) {
2370 num
-= originalData
[i
- rollPeriod
][1][0];
2371 den
-= originalData
[i
- rollPeriod
][1][1];
2374 var date
= originalData
[i
][0];
2375 var value
= den
? num
/ den
: 0.0;
2376 if (this.attr_("errorBars")) {
2377 if (this.wilsonInterval_
) {
2378 // For more details on this confidence interval, see:
2379 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2381 var p
= value
< 0 ? 0 : value
, n
= den
;
2382 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2383 var denom
= 1 + sigma
* sigma
/ den
;
2384 var low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2385 var high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2386 rollingData
[i
] = [date
,
2387 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2389 rollingData
[i
] = [date
, [0, 0, 0]];
2392 var stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2393 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2396 rollingData
[i
] = [date
, mult
* value
];
2399 } else if (this.attr_("customBars")) {
2404 for (var i
= 0; i
< originalData
.length
; i
++) {
2405 var data
= originalData
[i
][1];
2407 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2409 if (y
!= null && !isNaN(y
)) {
2415 if (i
- rollPeriod
>= 0) {
2416 var prev
= originalData
[i
- rollPeriod
];
2417 if (prev
[1][1] != null && !isNaN(prev
[1][1])) {
2425 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2426 1.0 * (mid
- low
) / count
,
2427 1.0 * (high
- mid
) / count
]];
2429 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2433 // Calculate the rolling average for the first rollPeriod - 1 points where
2434 // there is not enough data to roll over the full number of points
2435 var num_init_points
= Math
.min(rollPeriod
- 1, originalData
.length
- 2);
2436 if (!this.attr_("errorBars")){
2437 if (rollPeriod
== 1) {
2438 return originalData
;
2441 for (var i
= 0; i
< originalData
.length
; i
++) {
2444 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2445 var y
= originalData
[j
][1];
2446 if (y
== null || isNaN(y
)) continue;
2448 sum
+= originalData
[j
][1];
2451 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2453 rollingData
[i
] = [originalData
[i
][0], null];
2458 for (var i
= 0; i
< originalData
.length
; i
++) {
2462 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2463 var y
= originalData
[j
][1][0];
2464 if (y
== null || isNaN(y
)) continue;
2466 sum
+= originalData
[j
][1][0];
2467 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2470 var stddev
= Math
.sqrt(variance
) / num_ok
;
2471 rollingData
[i
] = [originalData
[i
][0],
2472 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2474 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2484 * Detects the type of the str (date or numeric) and sets the various
2485 * formatting attributes in this.attrs_ based on this type.
2486 * @param {String} str An x value.
2489 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2491 if (str
.indexOf('-') > 0 ||
2492 str
.indexOf('/') >= 0 ||
2493 isNaN(parseFloat(str
))) {
2495 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2496 // TODO(danvk): remove support for this format.
2501 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
2502 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2503 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
2504 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2506 // TODO(danvk): use Dygraph.numberFormatter here?
2507 /** @private (shut up, jsdoc!) */
2508 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
2509 /** @private (shut up, jsdoc!) */
2510 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2511 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2512 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
2517 * Parses the value as a floating point number. This is like the parseFloat()
2518 * built-in, but with a few differences:
2519 * - the empty string is parsed as null, rather than NaN.
2520 * - if the string cannot be parsed at all, an error is logged.
2521 * If the string can't be parsed, this method returns null.
2522 * @param {String} x The string to be parsed
2523 * @param {Number} opt_line_no The line number from which the string comes.
2524 * @param {String} opt_line The text of the line from which the string comes.
2528 // Parse the x as a float or return null if it's not a number.
2529 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
2530 var val
= parseFloat(x
);
2531 if (!isNaN(val
)) return val
;
2533 // Try to figure out what happeend.
2534 // If the value is the empty string, parse it as null.
2535 if (/^ *$/.test(x
)) return null;
2537 // If it was actually "NaN", return it as NaN.
2538 if (/^ *nan *$/i.test(x
)) return NaN
;
2540 // Looks like a parsing error.
2541 var msg
= "Unable to parse '" + x
+ "' as a number";
2542 if (opt_line
!== null && opt_line_no
!== null) {
2543 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
2552 * Parses a string in a special csv format. We expect a csv file where each
2553 * line is a date point, and the first field in each line is the date string.
2554 * We also expect that all remaining fields represent series.
2555 * if the errorBars attribute is set, then interpret the fields as:
2556 * date, series1, stddev1, series2, stddev2, ...
2557 * @param {[Object]} data See above.
2559 * @return [Object] An array with one entry for each row. These entries
2560 * are an array of cells in that row. The first entry is the parsed x-value for
2561 * the row. The second, third, etc. are the y-values. These can take on one of
2562 * three forms, depending on the CSV and constructor parameters:
2564 * 2. [ value, stddev ]
2565 * 3. [ low value, center value, high value ]
2567 Dygraph
.prototype.parseCSV_
= function(data
) {
2569 var lines
= data
.split("\n");
2571 // Use the default delimiter or fall back to a tab if that makes sense.
2572 var delim
= this.attr_('delimiter');
2573 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2578 if (!('labels' in this.user_attrs_
)) {
2579 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
2581 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
2586 var defaultParserSet
= false; // attempt to auto-detect x value type
2587 var expectedCols
= this.attr_("labels").length
;
2588 var outOfOrder
= false;
2589 for (var i
= start
; i
< lines
.length
; i
++) {
2590 var line
= lines
[i
];
2592 if (line
.length
== 0) continue; // skip blank lines
2593 if (line
[0] == '#') continue; // skip comment lines
2594 var inFields
= line
.split(delim
);
2595 if (inFields
.length
< 2) continue;
2598 if (!defaultParserSet
) {
2599 this.detectTypeFromString_(inFields
[0]);
2600 xParser
= this.attr_("xValueParser");
2601 defaultParserSet
= true;
2603 fields
[0] = xParser(inFields
[0], this);
2605 // If fractions are expected, parse the numbers as "A/B
"
2606 if (this.fractions_) {
2607 for (var j = 1; j < inFields.length; j++) {
2608 // TODO(danvk): figure out an appropriate way to flag parse errors.
2609 var vals = inFields[j].split("/");
2610 if (vals.length != 2) {
2611 this.error('Expected fractional "num
/den
" values in CSV data ' +
2612 "but found a value
'" + inFields[j] + "' on line
" +
2613 (1 + i) + " ('" + line + "') which is not of
this form
.");
2616 fields[j] = [this.parseFloat_(vals[0], i, line),
2617 this.parseFloat_(vals[1], i, line)];
2620 } else if (this.attr_("errorBars
")) {
2621 // If there are error bars, values are (value, stddev) pairs
2622 if (inFields.length % 2 != 1) {
2623 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2624 'but line ' + (1 + i) + ' has an odd number of values (' +
2625 (inFields.length - 1) + "): '" + line + "'");
2627 for (var j = 1; j < inFields.length; j += 2) {
2628 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2629 this.parseFloat_(inFields[j + 1], i, line)];
2631 } else if (this.attr_("customBars
")) {
2632 // Bars are a low;center;high tuple
2633 for (var j = 1; j < inFields.length; j++) {
2634 var val = inFields[j];
2635 if (/^ *$/.test(val)) {
2636 fields[j] = [null, null, null];
2638 var vals = val.split(";");
2639 if (vals.length == 3) {
2640 fields[j] = [ this.parseFloat_(vals[0], i, line),
2641 this.parseFloat_(vals[1], i, line),
2642 this.parseFloat_(vals[2], i, line) ];
2644 this.warning('When using customBars, values must be either blank ' +
2645 'or "low
;center
;high
" tuples (got "' + val +
2646 '" on line ' + (1+i));
2651 // Values are just numbers
2652 for (var j = 1; j < inFields.length; j++) {
2653 fields[j] = this.parseFloat_(inFields[j], i, line);
2656 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2660 if (fields.length != expectedCols) {
2661 this.error("Number of columns
in line
" + i + " (" + fields.length +
2662 ") does not agree
with number of
labels (" + expectedCols +
2666 // If the user specified the 'labels' option and none of the cells of the
2667 // first row parsed correctly, then they probably double-specified the
2668 // labels. We go with the values set in the option, discard this row and
2669 // log a warning to the JS console.
2670 if (i == 0 && this.attr_('labels')) {
2671 var all_null = true;
2672 for (var j = 0; all_null && j < fields.length; j++) {
2673 if (fields[j]) all_null = false;
2676 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
2677 "CSV
data ('" + line + "') appears to also contain labels
. " +
2678 "Will drop the CSV labels and
use the option labels
.");
2686 this.warn("CSV is out of order
; order it correctly to speed loading
.");
2687 ret.sort(function(a,b) { return a[0] - b[0] });
2695 * The user has provided their data as a pre-packaged JS array. If the x values
2696 * are numeric, this is the same as dygraphs' internal format. If the x values
2697 * are dates, we need to convert them from Date objects to ms since epoch.
2698 * @param {[Object]} data
2699 * @return {[Object]} data with numeric x values.
2701 Dygraph.prototype.parseArray_ = function(data) {
2702 // Peek at the first x value to see if it's numeric.
2703 if (data.length == 0) {
2704 this.error("Can
't plot empty data set");
2707 if (data[0].length == 0) {
2708 this.error("Data set cannot contain an empty row");
2712 if (this.attr_("labels") == null) {
2713 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
2714 "in the options parameter");
2715 this.attrs_.labels = [ "X" ];
2716 for (var i = 1; i < data[0].length; i++) {
2717 this.attrs_.labels.push("Y" + i);
2721 if (Dygraph.isDateLike(data[0][0])) {
2722 // Some intelligent defaults for a date x-axis.
2723 this.attrs_.xValueFormatter = Dygraph.dateString_;
2724 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
2725 this.attrs_.xTicker = Dygraph.dateTicker;
2727 // Assume they're all dates
.
2728 var parsedData
= Dygraph
.clone(data
);
2729 for (var i
= 0; i
< data
.length
; i
++) {
2730 if (parsedData
[i
].length
== 0) {
2731 this.error("Row " + (1 + i
) + " of data is empty");
2734 if (parsedData
[i
][0] == null
2735 || typeof(parsedData
[i
][0].getTime
) != 'function'
2736 || isNaN(parsedData
[i
][0].getTime())) {
2737 this.error("x value in row " + (1 + i
) + " is not a Date");
2740 parsedData
[i
][0] = parsedData
[i
][0].getTime();
2744 // Some intelligent defaults for a numeric x-axis.
2745 /** @private (shut up, jsdoc!) */
2746 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
2747 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2753 * Parses a DataTable object from gviz.
2754 * The data is expected to have a first column that is either a date or a
2755 * number. All subsequent columns must be numbers. If there is a clear mismatch
2756 * between this.xValueParser_ and the type of the first column, it will be
2757 * fixed. Fills out rawData_.
2758 * @param {[Object]} data See above.
2761 Dygraph
.prototype.parseDataTable_
= function(data
) {
2762 var cols
= data
.getNumberOfColumns();
2763 var rows
= data
.getNumberOfRows();
2765 var indepType
= data
.getColumnType(0);
2766 if (indepType
== 'date' || indepType
== 'datetime') {
2767 this.attrs_
.xValueFormatter
= Dygraph
.dateString_
;
2768 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2769 this.attrs_
.xTicker
= Dygraph
.dateTicker
;
2770 this.attrs_
.xAxisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2771 } else if (indepType
== 'number') {
2772 this.attrs_
.xValueFormatter
= function(x
) { return x
; };
2773 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2774 this.attrs_
.xTicker
= Dygraph
.numericTicks
;
2775 this.attrs_
.xAxisLabelFormatter
= this.attrs_
.xValueFormatter
;
2777 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2778 "column 1 of DataTable input (Got '" + indepType
+ "')");
2782 // Array of the column indices which contain data (and not annotations).
2784 var annotationCols
= {}; // data index -> [annotation cols]
2785 var hasAnnotations
= false;
2786 for (var i
= 1; i
< cols
; i
++) {
2787 var type
= data
.getColumnType(i
);
2788 if (type
== 'number') {
2790 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
2791 // This is OK -- it's an annotation column.
2792 var dataIdx
= colIdx
[colIdx
.length
- 1];
2793 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
2794 annotationCols
[dataIdx
] = [i
];
2796 annotationCols
[dataIdx
].push(i
);
2798 hasAnnotations
= true;
2800 this.error("Only 'number' is supported as a dependent type with Gviz." +
2801 " 'string' is only supported if displayAnnotations is true");
2805 // Read column labels
2806 // TODO(danvk): add support back for errorBars
2807 var labels
= [data
.getColumnLabel(0)];
2808 for (var i
= 0; i
< colIdx
.length
; i
++) {
2809 labels
.push(data
.getColumnLabel(colIdx
[i
]));
2810 if (this.attr_("errorBars")) i
+= 1;
2812 this.attrs_
.labels
= labels
;
2813 cols
= labels
.length
;
2816 var outOfOrder
= false;
2817 var annotations
= [];
2818 for (var i
= 0; i
< rows
; i
++) {
2820 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
2821 data
.getValue(i
, 0) === null) {
2822 this.warn("Ignoring row " + i
+
2823 " of DataTable because of undefined or null first column.");
2827 if (indepType
== 'date' || indepType
== 'datetime') {
2828 row
.push(data
.getValue(i
, 0).getTime());
2830 row
.push(data
.getValue(i
, 0));
2832 if (!this.attr_("errorBars")) {
2833 for (var j
= 0; j
< colIdx
.length
; j
++) {
2834 var col
= colIdx
[j
];
2835 row
.push(data
.getValue(i
, col
));
2836 if (hasAnnotations
&&
2837 annotationCols
.hasOwnProperty(col
) &&
2838 data
.getValue(i
, annotationCols
[col
][0]) != null) {
2840 ann
.series
= data
.getColumnLabel(col
);
2842 ann
.shortText
= String
.fromCharCode(65 /* A */ + annotations
.length
)
2844 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
2845 if (k
) ann
.text
+= "\n";
2846 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
2848 annotations
.push(ann
);
2852 // Strip out infinities, which give dygraphs problems later on.
2853 for (var j
= 0; j
< row
.length
; j
++) {
2854 if (!isFinite(row
[j
])) row
[j
] = null;
2857 for (var j
= 0; j
< cols
- 1; j
++) {
2858 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
2861 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
2868 this.warn("DataTable is out of order; order it correctly to speed loading.");
2869 ret
.sort(function(a
,b
) { return a
[0] - b
[0] });
2871 this.rawData_
= ret
;
2873 if (annotations
.length
> 0) {
2874 this.setAnnotations(annotations
, true);
2879 * Get the CSV data. If it's in a function, call that function. If it's in a
2880 * file, do an XMLHttpRequest to get it.
2883 Dygraph
.prototype.start_
= function() {
2884 if (typeof this.file_
== 'function') {
2885 // CSV string. Pretend we got it via XHR.
2886 this.loadedEvent_(this.file_());
2887 } else if (Dygraph
.isArrayLike(this.file_
)) {
2888 this.rawData_
= this.parseArray_(this.file_
);
2890 } else if (typeof this.file_
== 'object' &&
2891 typeof this.file_
.getColumnRange
== 'function') {
2892 // must be a DataTable from gviz.
2893 this.parseDataTable_(this.file_
);
2895 } else if (typeof this.file_
== 'string') {
2896 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2897 if (this.file_
.indexOf('\n') >= 0) {
2898 this.loadedEvent_(this.file_
);
2900 var req
= new XMLHttpRequest();
2902 req
.onreadystatechange
= function () {
2903 if (req
.readyState
== 4) {
2904 if (req
.status
== 200 || // Normal http
2905 req
.status
== 0) { // Chrome w/ --allow
-file
-access
-from
-files
2906 caller
.loadedEvent_(req
.responseText
);
2911 req
.open("GET", this.file_
, true);
2915 this.error("Unknown data format: " + (typeof this.file_
));
2920 * Changes various properties of the graph. These can include:
2922 * <li>file: changes the source data for the graph</li>
2923 * <li>errorBars: changes whether the data contains stddev</li>
2926 * There's a huge variety of options that can be passed to this method. For a
2927 * full list, see http://dygraphs.com/options.html.
2929 * @param {Object} attrs The new properties and values
2930 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
2931 * call to updateOptions(). If you know better, you can pass true to explicitly
2932 * block the redraw. This can be useful for chaining updateOptions() calls,
2933 * avoiding the occasional infinite loop and preventing redraws when it's not
2934 * necessary (e.g. when updating a callback).
2936 Dygraph
.prototype.updateOptions
= function(attrs
, block_redraw
) {
2937 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
2939 // TODO(danvk): this is a mess. Move these options into attr_.
2940 if ('rollPeriod' in attrs
) {
2941 this.rollPeriod_
= attrs
.rollPeriod
;
2943 if ('dateWindow' in attrs
) {
2944 this.dateWindow_
= attrs
.dateWindow
;
2945 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
2946 this.zoomed_x_
= attrs
.dateWindow
!= null;
2949 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
2950 this.zoomed_y_
= attrs
.valueRange
!= null;
2953 // TODO(danvk): validate per-series options.
2958 // highlightCircleSize
2960 Dygraph
.update(this.user_attrs_
, attrs
);
2962 if (attrs
['file']) {
2963 this.file_
= attrs
['file'];
2964 if (!block_redraw
) this.start_();
2966 if (!block_redraw
) this.predraw_();
2971 * Resizes the dygraph. If no parameters are specified, resizes to fill the
2972 * containing div (which has presumably changed size since the dygraph was
2973 * instantiated. If the width/height are specified, the div will be resized.
2975 * This is far more efficient than destroying and re-instantiating a
2976 * Dygraph, since it doesn't have to reparse the underlying data.
2978 * @param {Number} [width] Width (in pixels)
2979 * @param {Number} [height] Height (in pixels)
2981 Dygraph
.prototype.resize
= function(width
, height
) {
2982 if (this.resize_lock
) {
2985 this.resize_lock
= true;
2987 if ((width
=== null) != (height
=== null)) {
2988 this.warn("Dygraph.resize() should be called with zero parameters or " +
2989 "two non-NULL parameters. Pretending it was zero.");
2990 width
= height
= null;
2993 // TODO(danvk): there should be a clear() method.
2994 this.maindiv_
.innerHTML
= "";
2995 this.attrs_
.labelsDiv
= null;
2998 this.maindiv_
.style
.width
= width
+ "px";
2999 this.maindiv_
.style
.height
= height
+ "px";
3000 this.width_
= width
;
3001 this.height_
= height
;
3003 this.width_
= this.maindiv_
.offsetWidth
;
3004 this.height_
= this.maindiv_
.offsetHeight
;
3007 this.createInterface_();
3010 this.resize_lock
= false;
3014 * Adjusts the number of points in the rolling average. Updates the graph to
3015 * reflect the new averaging period.
3016 * @param {Number} length Number of points over which to average the data.
3018 Dygraph
.prototype.adjustRoll
= function(length
) {
3019 this.rollPeriod_
= length
;
3024 * Returns a boolean array of visibility statuses.
3026 Dygraph
.prototype.visibility
= function() {
3027 // Do lazy-initialization, so that this happens after we know the number of
3029 if (!this.attr_("visibility")) {
3030 this.attrs_
["visibility"] = [];
3032 while (this.attr_("visibility").length
< this.rawData_
[0].length
- 1) {
3033 this.attr_("visibility").push(true);
3035 return this.attr_("visibility");
3039 * Changes the visiblity of a series.
3041 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3042 var x
= this.visibility();
3043 if (num
< 0 || num
>= x
.length
) {
3044 this.warn("invalid series number in setVisibility: " + num
);
3052 * How large of an area will the dygraph render itself in?
3053 * This is used for testing.
3054 * @return A {width: w, height: h} object.
3057 Dygraph
.prototype.size
= function() {
3058 return { width
: this.width_
, height
: this.height_
};
3062 * Update the list of annotations and redraw the chart.
3064 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3065 // Only add the annotation CSS rule once we know it will be used.
3066 Dygraph
.addAnnotationRule();
3067 this.annotations_
= ann
;
3068 this.layout_
.setAnnotations(this.annotations_
);
3069 if (!suppressDraw
) {
3075 * Return the list of annotations.
3077 Dygraph
.prototype.annotations
= function() {
3078 return this.annotations_
;
3082 * Get the index of a series (column) given its name. The first column is the
3083 * x-axis, so the data series start with index 1.
3085 Dygraph
.prototype.indexFromSetName
= function(name
) {
3086 var labels
= this.attr_("labels");
3087 for (var i
= 0; i
< labels
.length
; i
++) {
3088 if (labels
[i
] == name
) return i
;
3095 * Adds a default style for the annotation CSS classes to the document. This is
3096 * only executed when annotations are actually used. It is designed to only be
3097 * called once -- all calls after the first will return immediately.
3099 Dygraph
.addAnnotationRule
= function() {
3100 if (Dygraph
.addedAnnotationCSS
) return;
3102 var rule
= "border: 1px solid black; " +
3103 "background-color: white; " +
3104 "text-align: center;";
3106 var styleSheetElement
= document
.createElement("style");
3107 styleSheetElement
.type
= "text/css";
3108 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3110 // Find the first style sheet that we can access.
3111 // We may not add a rule to a style sheet from another domain for security
3112 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3113 // adds its own style sheets from google.com.
3114 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3115 if (document
.styleSheets
[i
].disabled
) continue;
3116 var mysheet
= document
.styleSheets
[i
];
3118 if (mysheet
.insertRule
) { // Firefox
3119 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3120 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3121 } else if (mysheet
.addRule
) { // IE
3122 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3124 Dygraph
.addedAnnotationCSS
= true;
3127 // Was likely a security exception.
3131 this.warn("Unable to add default annotation CSS rule; display may be off.");
3134 // Older pages may still use this name.
3135 DateGraph
= Dygraph
;