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 // These are defined before DEFAULT_ATTRS so that it can refer to them.
92 * Return a string version of a number. This respects the digitsAfterDecimal
93 * and maxNumberWidth options.
94 * @param {Number} x The number to be formatted
95 * @param {Dygraph} opts An options view
96 * @param {String} name The name of the point's data series
97 * @param {Dygraph} g The dygraph object
99 Dygraph
.numberValueFormatter
= function(x
, opts
, pt
, g
) {
100 var sigFigs
= opts('sigFigs');
102 if (sigFigs
!== null) {
103 // User has opted for a fixed number of significant figures.
104 return Dygraph
.floatFormat(x
, sigFigs
);
107 var digits
= opts('digitsAfterDecimal');
108 var maxNumberWidth
= opts('maxNumberWidth');
110 // switch to scientific notation if we underflow or overflow fixed display.
112 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
113 Math
.abs(x
) < Math
.pow(10, -digits
))) {
114 return x
.toExponential(digits
);
116 return '' + Dygraph
.round_(x
, digits
);
121 * variant for use as an axisLabelFormatter.
124 Dygraph
.numberAxisLabelFormatter
= function(x
, granularity
, opts
, g
) {
125 return Dygraph
.numberValueFormatter(x
, opts
, g
);
129 * Convert a JS date (millis since epoch) to YYYY/MM/DD
130 * @param {Number} date The JavaScript date (ms since epoch)
131 * @return {String} A date of the form "YYYY/MM/DD"
134 Dygraph
.dateString_
= function(date
) {
135 var zeropad
= Dygraph
.zeropad
;
136 var d
= new Date(date
);
139 var year
= "" + d
.getFullYear();
140 // Get a 0 padded month string
141 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
142 // Get a 0 padded day string
143 var day
= zeropad(d
.getDate());
146 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
147 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
149 return year
+ "/" + month + "/" + day
+ ret
;
153 * Convert a JS date to a string appropriate to display on an axis that
154 * is displaying values at the stated granularity.
155 * @param {Date} date The date to format
156 * @param {Number} granularity One of the Dygraph granularity constants
157 * @return {String} The formatted date
160 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
161 if (granularity
>= Dygraph
.DECADAL
) {
162 return date
.strftime('%Y');
163 } else if (granularity
>= Dygraph
.MONTHLY
) {
164 return date
.strftime('%b %y');
166 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
167 if (frac
== 0 || granularity
>= Dygraph
.DAILY
) {
168 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
170 return Dygraph
.hmsString_(date
.getTime());
176 // Default attribute values.
177 Dygraph
.DEFAULT_ATTRS
= {
178 highlightCircleSize
: 3,
182 // TODO(danvk): move defaults from createStatusMessage_ here.
184 labelsSeparateLines
: false,
185 labelsShowZeroValues
: true,
188 showLabelsOnHighlight
: true,
190 digitsAfterDecimal
: 2,
197 axisLabelFontSize
: 14,
203 xValueParser
: Dygraph
.dateParser
,
210 wilsonInterval
: true, // only relevant if fractions is true
214 connectSeparatedPoints
: false,
217 hideOverlayOnMouseOut
: true,
219 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
220 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
225 // Sizes of the various chart labels.
232 axisLineColor
: "black",
235 axisLabelColor
: "black",
236 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
240 gridLineColor
: "rgb(128,128,128)",
242 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
248 axisLabelFormatter
: Dygraph
.dateAxisFormatter
,
249 valueFormatter
: Dygraph
.dateString_
,
250 ticker
: null // will be set in dygraph-tickers.js
254 valueFormatter
: Dygraph
.numberValueFormatter
,
255 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
256 ticker
: null // will be set in dygraph-tickers.js
260 valueFormatter
: Dygraph
.numberValueFormatter
,
261 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
262 ticker
: null // will be set in dygraph-tickers.js
267 // Directions for panning and zooming. Use bit operations when combined
268 // values are possible.
269 Dygraph
.HORIZONTAL
= 1;
270 Dygraph
.VERTICAL
= 2;
272 // Used for initializing annotation CSS rules only once.
273 Dygraph
.addedAnnotationCSS
= false;
275 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
276 // Labels is no longer a constructor parameter, since it's typically set
277 // directly from the data source. It also conains a name for the x-axis,
278 // which the previous constructor form did not.
279 if (labels
!= null) {
280 var new_labels
= ["Date"];
281 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
282 Dygraph
.update(attrs
, { 'labels': new_labels
});
284 this.__init__(div
, file
, attrs
);
288 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
289 * and context <canvas> inside of it. See the constructor for details.
291 * @param {Element} div the Element to render the graph into.
292 * @param {String | Function} file Source data
293 * @param {Object} attrs Miscellaneous other options
296 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
297 // Hack for IE: if we're using excanvas and the document hasn't finished
298 // loading yet (and hence may not have initialized whatever it needs to
299 // initialize), then keep calling this routine periodically until it has.
300 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
301 typeof(G_vmlCanvasManager
) != 'undefined' &&
302 document
.readyState
!= 'complete') {
304 setTimeout(function() { self
.__init__(div
, file
, attrs
) }, 100);
307 // Support two-argument constructor
308 if (attrs
== null) { attrs
= {}; }
310 attrs
= Dygraph
.mapLegacyOptions_(attrs
);
313 Dygraph
.error("Constructing dygraph with a non-existent div!");
317 // Copy the important bits into the object
318 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
321 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
322 this.previousVerticalX_
= -1;
323 this.fractions_
= attrs
.fractions
|| false;
324 this.dateWindow_
= attrs
.dateWindow
|| null;
326 this.wilsonInterval_
= attrs
.wilsonInterval
|| true;
327 this.is_initial_draw_
= true;
328 this.annotations_
= [];
330 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
331 this.zoomed_x_
= false;
332 this.zoomed_y_
= false;
334 // Clear the div. This ensure that, if multiple dygraphs are passed the same
335 // div, then only one will be drawn.
338 // For historical reasons, the 'width' and 'height' options trump all CSS
339 // rules _except_ for an explicit 'width' or 'height' on the div.
340 // As an added convenience, if the div has zero height (like <div></div> does
341 // without any styles), then we use a default height/width
.
342 if (div
.style
.width
== '' && attrs
.width
) {
343 div
.style
.width
= attrs
.width
+ "px";
345 if (div
.style
.height
== '' && attrs
.height
) {
346 div
.style
.height
= attrs
.height
+ "px";
348 if (div
.style
.height
== '' && div
.offsetHeight
== 0) {
349 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
350 if (div
.style
.width
== '') {
351 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
354 // these will be zero if the dygraph's div is hidden.
355 this.width_
= div
.offsetWidth
;
356 this.height_
= div
.offsetHeight
;
358 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
359 if (attrs
['stackedGraph']) {
360 attrs
['fillGraph'] = true;
361 // TODO(nikhilk): Add any other stackedGraph checks here.
364 // Dygraphs has many options, some of which interact with one another.
365 // To keep track of everything, we maintain two sets of options:
367 // this.user_attrs_ only options explicitly set by the user.
368 // this.attrs_ defaults, options derived from user_attrs_, data.
370 // Options are then accessed this.attr_('attr'), which first looks at
371 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
372 // defaults without overriding behavior that the user specifically asks for.
373 this.user_attrs_
= {};
374 Dygraph
.update(this.user_attrs_
, attrs
);
376 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
378 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
380 this.boundaryIds_
= [];
382 // Create the containing DIV and other interactive elements
383 this.createInterface_();
389 * Returns the zoomed status of the chart for one or both axes.
391 * Axis is an optional parameter. Can be set to 'x' or 'y'.
393 * The zoomed status for an axis is set whenever a user zooms using the mouse
394 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
395 * option is also specified).
397 Dygraph
.prototype.isZoomed
= function(axis
) {
398 if (axis
== null) return this.zoomed_x_
|| this.zoomed_y_
;
399 if (axis
== 'x') return this.zoomed_x_
;
400 if (axis
== 'y') return this.zoomed_y_
;
401 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
405 * Returns information about the Dygraph object, including its containing ID.
407 Dygraph
.prototype.toString
= function() {
408 var maindiv
= this.maindiv_
;
409 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
410 return "[Dygraph " + id
+ "]";
415 * Returns the value of an option. This may be set by the user (either in the
416 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
418 * @param { String } name The name of the option, e.g. 'rollPeriod'.
419 * @param { String } [seriesName] The name of the series to which the option
420 * will be applied. If no per-series value of this option is available, then
421 * the global value is returned. This is optional.
422 * @return { ... } The value of the option.
424 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
425 // <REMOVE_FOR_COMBINED>
426 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
427 this.error('Must include options reference JS for testing');
428 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
429 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
430 'in the Dygraphs.OPTIONS_REFERENCE listing.');
431 // Only log this error once.
432 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
434 // </REMOVE_FOR_COMBINED
>
436 typeof(this.user_attrs_
[seriesName
]) != 'undefined' &&
437 this.user_attrs_
[seriesName
] != null &&
438 typeof(this.user_attrs_
[seriesName
][name
]) != 'undefined') {
439 return this.user_attrs_
[seriesName
][name
];
440 } else if (typeof(this.user_attrs_
[name
]) != 'undefined') {
441 return this.user_attrs_
[name
];
442 } else if (typeof(this.attrs_
[name
]) != 'undefined') {
443 return this.attrs_
[name
];
451 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
452 * @return { ... } A function mapping string -> option value
454 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
456 return function(opt
) {
457 var axis_opts
= self
.user_attrs_
['axes'];
458 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
459 return axis_opts
[axis
][opt
];
461 // user-specified attributes always trump defaults, even if they're less
463 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
464 return self
.user_attrs_
[opt
];
467 axis_opts
= self
.attrs_
['axes'];
468 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
469 return axis_opts
[axis
][opt
];
471 // check old-style axis options
472 // TODO(danvk): add a deprecation warning if either of these match.
473 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
474 return self
.axes_
[0][opt
];
475 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
476 return self
.axes_
[1][opt
];
478 return self
.attr_(opt
);
483 * Returns the current rolling period, as set by the user or an option.
484 * @return {Number} The number of points in the rolling window
486 Dygraph
.prototype.rollPeriod
= function() {
487 return this.rollPeriod_
;
491 * Returns the currently-visible x-range. This can be affected by zooming,
492 * panning or a call to updateOptions.
493 * Returns a two-element array: [left, right].
494 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
496 Dygraph
.prototype.xAxisRange
= function() {
497 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
501 * Returns the lower- and upper-bound x-axis values of the
504 Dygraph
.prototype.xAxisExtremes
= function() {
505 var left
= this.rawData_
[0][0];
506 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
507 return [left
, right
];
511 * Returns the currently-visible y-range for an axis. This can be affected by
512 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
513 * called with no arguments, returns the range of the first axis.
514 * Returns a two-element array: [bottom, top].
516 Dygraph
.prototype.yAxisRange
= function(idx
) {
517 if (typeof(idx
) == "undefined") idx
= 0;
518 if (idx
< 0 || idx
>= this.axes_
.length
) {
521 var axis
= this.axes_
[idx
];
522 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
526 * Returns the currently-visible y-ranges for each axis. This can be affected by
527 * zooming, panning, calls to updateOptions, etc.
528 * Returns an array of [bottom, top] pairs, one for each y-axis.
530 Dygraph
.prototype.yAxisRanges
= function() {
532 for (var i
= 0; i
< this.axes_
.length
; i
++) {
533 ret
.push(this.yAxisRange(i
));
538 // TODO(danvk): use these functions throughout dygraphs.
540 * Convert from data coordinates to canvas/div X/Y coordinates.
541 * If specified, do this conversion for the coordinate system of a particular
542 * axis. Uses the first axis by default.
543 * Returns a two-element array: [X, Y]
545 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
546 * instead of toDomCoords(null, y, axis).
548 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
549 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
553 * Convert from data x coordinates to canvas/div X coordinate.
554 * If specified, do this conversion for the coordinate system of a particular
556 * Returns a single value or null if x is null.
558 Dygraph
.prototype.toDomXCoord
= function(x
) {
563 var area
= this.plotter_
.area
;
564 var xRange
= this.xAxisRange();
565 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
569 * Convert from data x coordinates to canvas/div Y coordinate and optional
570 * axis. Uses the first axis by default.
572 * returns a single value or null if y is null.
574 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
575 var pct
= this.toPercentYCoord(y
, axis
);
580 var area
= this.plotter_
.area
;
581 return area
.y
+ pct
* area
.h
;
585 * Convert from canvas/div coords to data coordinates.
586 * If specified, do this conversion for the coordinate system of a particular
587 * axis. Uses the first axis by default.
588 * Returns a two-element array: [X, Y].
590 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
591 * instead of toDataCoords(null, y, axis).
593 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
594 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
598 * Convert from canvas/div x coordinate to data coordinate.
600 * If x is null, this returns null.
602 Dygraph
.prototype.toDataXCoord
= function(x
) {
607 var area
= this.plotter_
.area
;
608 var xRange
= this.xAxisRange();
609 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
613 * Convert from canvas/div y coord to value.
615 * If y is null, this returns null.
616 * if axis is null, this uses the first axis.
618 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
623 var area
= this.plotter_
.area
;
624 var yRange
= this.yAxisRange(axis
);
626 if (typeof(axis
) == "undefined") axis
= 0;
627 if (!this.axes_
[axis
].logscale
) {
628 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
630 // Computing the inverse of toDomCoord.
631 var pct
= (y
- area
.y
) / area
.h
633 // Computing the inverse of toPercentYCoord. The function was arrived at with
634 // the following steps:
636 // Original calcuation:
637 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
639 // Move denominator to both sides:
640 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
642 // subtract logr1, and take the negative value.
643 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
645 // Swap both sides of the equation, and we can compute the log of the
646 // return value. Which means we just need to use that as the exponent in
648 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
650 var logr1
= Dygraph
.log10(yRange
[1]);
651 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
652 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
658 * Converts a y for an axis to a percentage from the top to the
659 * bottom of the drawing area.
661 * If the coordinate represents a value visible on the canvas, then
662 * the value will be between 0 and 1, where 0 is the top of the canvas.
663 * However, this method will return values outside the range, as
664 * values can fall outside the canvas.
666 * If y is null, this returns null.
667 * if axis is null, this uses the first axis.
669 * @param { Number } y The data y-coordinate.
670 * @param { Number } [axis] The axis number on which the data coordinate lives.
671 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
673 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
677 if (typeof(axis
) == "undefined") axis
= 0;
679 var area
= this.plotter_
.area
;
680 var yRange
= this.yAxisRange(axis
);
683 if (!this.axes_
[axis
].logscale
) {
684 // yRange[1] - y is unit distance from the bottom.
685 // yRange[1] - yRange[0] is the scale of the range.
686 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
687 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
689 var logr1
= Dygraph
.log10(yRange
[1]);
690 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
696 * Converts an x value to a percentage from the left to the right of
699 * If the coordinate represents a value visible on the canvas, then
700 * the value will be between 0 and 1, where 0 is the left of the canvas.
701 * However, this method will return values outside the range, as
702 * values can fall outside the canvas.
704 * If x is null, this returns null.
705 * @param { Number } x The data x-coordinate.
706 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
708 Dygraph
.prototype.toPercentXCoord
= function(x
) {
713 var xRange
= this.xAxisRange();
714 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
718 * Returns the number of columns (including the independent variable).
719 * @return { Integer } The number of columns.
721 Dygraph
.prototype.numColumns
= function() {
722 return this.rawData_
[0].length
;
726 * Returns the number of rows (excluding any header/label row).
727 * @return { Integer } The number of rows, less any header.
729 Dygraph
.prototype.numRows
= function() {
730 return this.rawData_
.length
;
734 * Returns the value in the given row and column. If the row and column exceed
735 * the bounds on the data, returns null. Also returns null if the value is
737 * @param { Number} row The row number of the data (0-based). Row 0 is the
738 * first row of data, not a header row.
739 * @param { Number} col The column number of the data (0-based)
740 * @return { Number } The value in the specified cell or null if the row/col
743 Dygraph
.prototype.getValue
= function(row
, col
) {
744 if (row
< 0 || row
> this.rawData_
.length
) return null;
745 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
747 return this.rawData_
[row
][col
];
751 * Generates interface elements for the Dygraph: a containing div, a div to
752 * display the current point, and a textbox to adjust the rolling average
753 * period. Also creates the Renderer/Layout elements.
756 Dygraph
.prototype.createInterface_
= function() {
757 // Create the all-enclosing graph div
758 var enclosing
= this.maindiv_
;
760 this.graphDiv
= document
.createElement("div");
761 this.graphDiv
.style
.width
= this.width_
+ "px";
762 this.graphDiv
.style
.height
= this.height_
+ "px";
763 enclosing
.appendChild(this.graphDiv
);
765 // Create the canvas for interactive parts of the chart.
766 this.canvas_
= Dygraph
.createCanvas();
767 this.canvas_
.style
.position
= "absolute";
768 this.canvas_
.width
= this.width_
;
769 this.canvas_
.height
= this.height_
;
770 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
771 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
773 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
775 // ... and for static parts of the chart.
776 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
777 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
779 // The interactive parts of the graph are drawn on top of the chart.
780 this.graphDiv
.appendChild(this.hidden_
);
781 this.graphDiv
.appendChild(this.canvas_
);
782 this.mouseEventElement_
= this.canvas_
;
785 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', function(e
) {
786 dygraph
.mouseMove_(e
);
788 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', function(e
) {
789 dygraph
.mouseOut_(e
);
792 // Create the grapher
793 this.layout_
= new DygraphLayout(this);
795 this.createStatusMessage_();
796 this.createDragInterface_();
798 // Update when the window is resized.
799 // TODO(danvk): drop frames depending on complexity of the chart.
800 Dygraph
.addEvent(window
, 'resize', function(e
) {
806 * Detach DOM elements in the dygraph and null out all data references.
807 * Calling this when you're done with a dygraph can dramatically reduce memory
808 * usage. See, e.g., the tests/perf.html example.
810 Dygraph
.prototype.destroy
= function() {
811 var removeRecursive
= function(node
) {
812 while (node
.hasChildNodes()) {
813 removeRecursive(node
.firstChild
);
814 node
.removeChild(node
.firstChild
);
817 removeRecursive(this.maindiv_
);
819 var nullOut
= function(obj
) {
821 if (typeof(obj
[n
]) === 'object') {
827 // These may not all be necessary, but it can't hurt...
828 nullOut(this.layout_
);
829 nullOut(this.plotter_
);
834 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
835 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
836 * or the zoom rectangles) is done on this.canvas_.
837 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
838 * @return {Object} The newly-created canvas
841 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
842 var h
= Dygraph
.createCanvas();
843 h
.style
.position
= "absolute";
844 // TODO(danvk): h should be offset from canvas. canvas needs to include
845 // some extra area to make it easier to zoom in on the far left and far
846 // right. h needs to be precisely the plot area, so that clipping occurs.
847 h
.style
.top
= canvas
.style
.top
;
848 h
.style
.left
= canvas
.style
.left
;
849 h
.width
= this.width_
;
850 h
.height
= this.height_
;
851 h
.style
.width
= this.width_
+ "px"; // for IE
852 h
.style
.height
= this.height_
+ "px"; // for IE
857 * Generate a set of distinct colors for the data series. This is done with a
858 * color wheel. Saturation/Value are customizable, and the hue is
859 * equally-spaced around the color wheel. If a custom set of colors is
860 * specified, that is used instead.
863 Dygraph
.prototype.setColors_
= function() {
864 var num
= this.attr_("labels").length
- 1;
866 var colors
= this.attr_('colors');
868 var sat
= this.attr_('colorSaturation') || 1.0;
869 var val
= this.attr_('colorValue') || 0.5;
870 var half
= Math
.ceil(num
/ 2);
871 for (var i
= 1; i
<= num
; i
++) {
872 if (!this.visibility()[i
-1]) continue;
873 // alternate colors for high contrast.
874 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
875 var hue
= (1.0 * idx
/ (1 + num
));
876 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
879 for (var i
= 0; i
< num
; i
++) {
880 if (!this.visibility()[i
]) continue;
881 var colorStr
= colors
[i
% colors
.length
];
882 this.colors_
.push(colorStr
);
886 this.plotter_
.setColors(this.colors_
);
890 * Return the list of colors. This is either the list of colors passed in the
891 * attributes or the autogenerated list of rgb(r,g,b) strings.
892 * @return {Array<string>} The list of colors.
894 Dygraph
.prototype.getColors
= function() {
899 * Create the div that contains information on the selected point(s)
900 * This goes in the top right of the canvas, unless an external div has already
904 Dygraph
.prototype.createStatusMessage_
= function() {
905 var userLabelsDiv
= this.user_attrs_
["labelsDiv"];
906 if (userLabelsDiv
&& null != userLabelsDiv
907 && (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
)) {
908 this.user_attrs_
["labelsDiv"] = document
.getElementById(userLabelsDiv
);
910 if (!this.attr_("labelsDiv")) {
911 var divWidth
= this.attr_('labelsDivWidth');
913 "position": "absolute",
916 "width": divWidth
+ "px",
918 "left": (this.width_
- divWidth
- 2) + "px",
919 "background": "white",
921 "overflow": "hidden"};
922 Dygraph
.update(messagestyle
, this.attr_('labelsDivStyles'));
923 var div
= document
.createElement("div");
924 div
.className
= "dygraph-legend";
925 for (var name
in messagestyle
) {
926 if (messagestyle
.hasOwnProperty(name
)) {
927 div
.style
[name
] = messagestyle
[name
];
930 this.graphDiv
.appendChild(div
);
931 this.attrs_
.labelsDiv
= div
;
936 * Position the labels div so that:
937 * - its right edge is flush with the right edge of the charting area
938 * - its top edge is flush with the top edge of the charting area
941 Dygraph
.prototype.positionLabelsDiv_
= function() {
942 // Don't touch a user-specified labelsDiv.
943 if (this.user_attrs_
.hasOwnProperty("labelsDiv")) return;
945 var area
= this.plotter_
.area
;
946 var div
= this.attr_("labelsDiv");
947 div
.style
.left
= area
.x
+ area
.w
- this.attr_("labelsDivWidth") - 1 + "px";
948 div
.style
.top
= area
.y
+ "px";
952 * Create the text box to adjust the averaging period
955 Dygraph
.prototype.createRollInterface_
= function() {
956 // Create a roller if one doesn't exist already.
958 this.roller_
= document
.createElement("input");
959 this.roller_
.type
= "text";
960 this.roller_
.style
.display
= "none";
961 this.graphDiv
.appendChild(this.roller_
);
964 var display
= this.attr_('showRoller') ? 'block' : 'none';
966 var area
= this.plotter_
.area
;
967 var textAttr
= { "position": "absolute",
969 "top": (area
.y
+ area
.h
- 25) + "px",
970 "left": (area
.x
+ 1) + "px",
973 this.roller_
.size
= "2";
974 this.roller_
.value
= this.rollPeriod_
;
975 for (var name
in textAttr
) {
976 if (textAttr
.hasOwnProperty(name
)) {
977 this.roller_
.style
[name
] = textAttr
[name
];
982 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
987 * Converts page the x-coordinate of the event to pixel x-coordinates on the
988 * canvas (i.e. DOM Coords).
990 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
991 return Dygraph
.pageX(e
) - context
.px
996 * Converts page the y-coordinate of the event to pixel y-coordinates on the
997 * canvas (i.e. DOM Coords).
999 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1000 return Dygraph
.pageY(e
) - context
.py
1004 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1008 Dygraph
.prototype.createDragInterface_
= function() {
1010 // Tracks whether the mouse is down right now
1012 isPanning
: false, // is this drag part of a pan?
1013 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1014 dragStartX
: null, // pixel coordinates
1015 dragStartY
: null, // pixel coordinates
1016 dragEndX
: null, // pixel coordinates
1017 dragEndY
: null, // pixel coordinates
1018 dragDirection
: null,
1019 prevEndX
: null, // pixel coordinates
1020 prevEndY
: null, // pixel coordinates
1021 prevDragDirection
: null,
1023 // The value on the left side of the graph when a pan operation starts.
1024 initialLeftmostDate
: null,
1026 // The number of units each pixel spans. (This won't be valid for log
1028 xUnitsPerPixel
: null,
1030 // TODO(danvk): update this comment
1031 // The range in second/value units that the viewport encompasses during a
1032 // panning operation.
1035 // Top-left corner of the canvas, in DOM coords
1036 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1040 // Values for use with panEdgeFraction, which limit how far outside the
1041 // graph's data boundaries it can be panned.
1042 boundedDates
: null, // [minDate, maxDate]
1043 boundedValues
: null, // [[minValue, maxValue] ...]
1045 initializeMouseDown
: function(event
, g
, context
) {
1046 // prevents mouse drags from selecting page text.
1047 if (event
.preventDefault
) {
1048 event
.preventDefault(); // Firefox, Chrome, etc.
1050 event
.returnValue
= false; // IE
1051 event
.cancelBubble
= true;
1054 context
.px
= Dygraph
.findPosX(g
.canvas_
);
1055 context
.py
= Dygraph
.findPosY(g
.canvas_
);
1056 context
.dragStartX
= g
.dragGetX_(event
, context
);
1057 context
.dragStartY
= g
.dragGetY_(event
, context
);
1061 var interactionModel
= this.attr_("interactionModel");
1063 // Self is the graph.
1066 // Function that binds the graph and context to the handler.
1067 var bindHandler
= function(handler
) {
1068 return function(event
) {
1069 handler(event
, self
, context
);
1073 for (var eventName
in interactionModel
) {
1074 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1075 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
1076 bindHandler(interactionModel
[eventName
]));
1079 // If the user releases the mouse button during a drag, but not over the
1080 // canvas, then it doesn't count as a zooming action.
1081 Dygraph
.addEvent(document
, 'mouseup', function(event
) {
1082 if (context
.isZooming
|| context
.isPanning
) {
1083 context
.isZooming
= false;
1084 context
.dragStartX
= null;
1085 context
.dragStartY
= null;
1088 if (context
.isPanning
) {
1089 context
.isPanning
= false;
1090 context
.draggingDate
= null;
1091 context
.dateRange
= null;
1092 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1093 delete self
.axes_
[i
].draggingValue
;
1094 delete self
.axes_
[i
].dragValueRange
;
1102 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1103 * up any previous zoom rectangles that were drawn. This could be optimized to
1104 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1107 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1108 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1109 * @param {Number} startX The X position where the drag started, in canvas
1111 * @param {Number} endX The current X position of the drag, in canvas coords.
1112 * @param {Number} startY The Y position where the drag started, in canvas
1114 * @param {Number} endY The current Y position of the drag, in canvas coords.
1115 * @param {Number} prevDirection the value of direction on the previous call to
1116 * this function. Used to avoid excess redrawing
1117 * @param {Number} prevEndX The value of endX on the previous call to this
1118 * function. Used to avoid excess redrawing
1119 * @param {Number} prevEndY The value of endY on the previous call to this
1120 * function. Used to avoid excess redrawing
1123 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1124 endY
, prevDirection
, prevEndX
,
1126 var ctx
= this.canvas_ctx_
;
1128 // Clean up from the previous rect if necessary
1129 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1130 ctx
.clearRect(Math
.min(startX
, prevEndX
), 0,
1131 Math
.abs(startX
- prevEndX
), this.height_
);
1132 } else if (prevDirection
== Dygraph
.VERTICAL
){
1133 ctx
.clearRect(0, Math
.min(startY
, prevEndY
),
1134 this.width_
, Math
.abs(startY
- prevEndY
));
1137 // Draw a light-grey rectangle to show the new viewing area
1138 if (direction
== Dygraph
.HORIZONTAL
) {
1139 if (endX
&& startX
) {
1140 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1141 ctx
.fillRect(Math
.min(startX
, endX
), 0,
1142 Math
.abs(endX
- startX
), this.height_
);
1145 if (direction
== Dygraph
.VERTICAL
) {
1146 if (endY
&& startY
) {
1147 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1148 ctx
.fillRect(0, Math
.min(startY
, endY
),
1149 this.width_
, Math
.abs(endY
- startY
));
1155 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1156 * the canvas. The exact zoom window may be slightly larger if there are no data
1157 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1158 * which accepts dates that match the raw data. This function redraws the graph.
1160 * @param {Number} lowX The leftmost pixel value that should be visible.
1161 * @param {Number} highX The rightmost pixel value that should be visible.
1164 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1165 // Find the earliest and latest dates contained in this canvasx range.
1166 // Convert the call to date ranges of the raw data.
1167 var minDate
= this.toDataXCoord(lowX
);
1168 var maxDate
= this.toDataXCoord(highX
);
1169 this.doZoomXDates_(minDate
, maxDate
);
1173 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1174 * method with doZoomX which accepts pixel coordinates. This function redraws
1177 * @param {Number} minDate The minimum date that should be visible.
1178 * @param {Number} maxDate The maximum date that should be visible.
1181 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1182 this.dateWindow_
= [minDate
, maxDate
];
1183 this.zoomed_x_
= true;
1185 if (this.attr_("zoomCallback")) {
1186 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1191 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1192 * the canvas. This function redraws the graph.
1194 * @param {Number} lowY The topmost pixel value that should be visible.
1195 * @param {Number} highY The lowest pixel value that should be visible.
1198 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1199 // Find the highest and lowest values in pixel range for each axis.
1200 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1201 // This is because pixels increase as you go down on the screen, whereas data
1202 // coordinates increase as you go up the screen.
1203 var valueRanges
= [];
1204 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1205 var hi
= this.toDataYCoord(lowY
, i
);
1206 var low
= this.toDataYCoord(highY
, i
);
1207 this.axes_
[i
].valueWindow
= [low
, hi
];
1208 valueRanges
.push([low
, hi
]);
1211 this.zoomed_y_
= true;
1213 if (this.attr_("zoomCallback")) {
1214 var xRange
= this.xAxisRange();
1215 var yRange
= this.yAxisRange();
1216 this.attr_("zoomCallback")(xRange
[0], xRange
[1], this.yAxisRanges());
1221 * Reset the zoom to the original view coordinates. This is the same as
1222 * double-clicking on the graph.
1226 Dygraph
.prototype.doUnzoom_
= function() {
1228 if (this.dateWindow_
!= null) {
1230 this.dateWindow_
= null;
1233 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1234 if (this.axes_
[i
].valueWindow
!= null) {
1236 delete this.axes_
[i
].valueWindow
;
1240 // Clear any selection, since it's likely to be drawn in the wrong place.
1241 this.clearSelection();
1244 // Putting the drawing operation before the callback because it resets
1246 this.zoomed_x_
= false;
1247 this.zoomed_y_
= false;
1249 if (this.attr_("zoomCallback")) {
1250 var minDate
= this.rawData_
[0][0];
1251 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1252 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1258 * When the mouse moves in the canvas, display information about a nearby data
1259 * point and draw dots over those points in the data series. This function
1260 * takes care of cleanup of previously-drawn dots.
1261 * @param {Object} event The mousemove event from the browser.
1264 Dygraph
.prototype.mouseMove_
= function(event
) {
1265 // This prevents JS errors when mousing over the canvas before data loads.
1266 var points
= this.layout_
.points
;
1267 if (points
=== undefined
) return;
1269 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1274 // Loop through all the points and find the date nearest to our current
1276 var minDist
= 1e+100;
1278 for (var i
= 0; i
< points
.length
; i
++) {
1279 var point
= points
[i
];
1280 if (point
== null) continue;
1281 var dist
= Math
.abs(point
.canvasx
- canvasx
);
1282 if (dist
> minDist
) continue;
1286 if (idx
>= 0) lastx
= points
[idx
].xval
;
1288 // Extract the points we've selected
1289 this.selPoints_
= [];
1290 var l
= points
.length
;
1291 if (!this.attr_("stackedGraph")) {
1292 for (var i
= 0; i
< l
; i
++) {
1293 if (points
[i
].xval
== lastx
) {
1294 this.selPoints_
.push(points
[i
]);
1298 // Need to 'unstack' points starting from the bottom
1299 var cumulative_sum
= 0;
1300 for (var i
= l
- 1; i
>= 0; i
--) {
1301 if (points
[i
].xval
== lastx
) {
1302 var p
= {}; // Clone the point since we modify it
1303 for (var k
in points
[i
]) {
1304 p
[k
] = points
[i
][k
];
1306 p
.yval
-= cumulative_sum
;
1307 cumulative_sum
+= p
.yval
;
1308 this.selPoints_
.push(p
);
1311 this.selPoints_
.reverse();
1314 if (this.attr_("highlightCallback")) {
1315 var px
= this.lastx_
;
1316 if (px
!== null && lastx
!= px
) {
1317 // only fire if the selected point has changed.
1318 this.attr_("highlightCallback")(event
, lastx
, this.selPoints_
, this.idxToRow_(idx
));
1322 // Save last x position for callbacks.
1323 this.lastx_
= lastx
;
1325 this.updateSelection_();
1329 * Transforms layout_.points index into data row number.
1330 * @param int layout_.points index
1331 * @return int row number, or -1 if none could be found.
1334 Dygraph
.prototype.idxToRow_
= function(idx
) {
1335 if (idx
< 0) return -1;
1337 for (var i
in this.layout_
.datasets
) {
1338 if (idx
< this.layout_
.datasets
[i
].length
) {
1339 return this.boundaryIds_
[0][0]+idx
;
1341 idx
-= this.layout_
.datasets
[i
].length
;
1348 * Generates HTML for the legend which is displayed when hovering over the
1349 * chart. If no selected points are specified, a default legend is returned
1350 * (this may just be the empty string).
1351 * @param { Number } [x] The x-value of the selected points.
1352 * @param { [Object] } [sel_points] List of selected points for the given
1353 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1355 Dygraph
.prototype.generateLegendHTML_
= function(x
, sel_points
) {
1356 // If no points are selected, we display a default legend. Traditionally,
1357 // this has been blank. But a better default would be a conventional legend,
1358 // which provides essential information for a non-interactive chart.
1359 if (typeof(x
) === 'undefined') {
1360 if (this.attr_('legend') != 'always') return '';
1362 var sepLines
= this.attr_('labelsSeparateLines');
1363 var labels
= this.attr_('labels');
1365 for (var i
= 1; i
< labels
.length
; i
++) {
1366 if (!this.visibility()[i
- 1]) continue;
1367 var c
= this.plotter_
.colors
[labels
[i
]];
1368 if (html
!= '') html
+= (sepLines
? '<br/>' : ' ');
1369 html
+= "<b><span style='color: " + c
+ ";'>—" + labels
[i
] +
1375 var xOptView
= this.optionsViewForAxis_('x');
1376 var xvf
= xOptView('valueFormatter');
1377 var html
= xvf(x
, xOptView
, this.attr_('labels')[0], this) + ":";
1380 var num_axes
= this.numAxes();
1381 for (var i
= 0; i
< num_axes
; i
++) {
1382 yOptViews
[i
] = this.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
1384 var showZeros
= this.attr_("labelsShowZeroValues");
1385 var sepLines
= this.attr_("labelsSeparateLines");
1386 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1387 var pt
= this.selPoints_
[i
];
1388 if (pt
.yval
== 0 && !showZeros
) continue;
1389 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1390 if (sepLines
) html
+= "<br/>";
1392 var yOptView
= yOptViews
[this.seriesToAxisMap_
[pt
.name
]];
1393 var fmtFunc
= yOptView('valueFormatter');
1394 var c
= this.plotter_
.colors
[pt
.name
];
1395 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, this);
1397 // TODO(danvk): use a template string here and make it an attribute.
1398 html
+= " <b><span style='color: " + c
+ ";'>"
1399 + pt
.name
+ "</span></b>:"
1407 * Displays information about the selected points in the legend. If there is no
1408 * selection, the legend will be cleared.
1409 * @param { Number } [x] The x-value of the selected points.
1410 * @param { [Object] } [sel_points] List of selected points for the given
1411 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1413 Dygraph
.prototype.setLegendHTML_
= function(x
, sel_points
) {
1414 var html
= this.generateLegendHTML_(x
, sel_points
);
1415 var labelsDiv
= this.attr_("labelsDiv");
1416 if (labelsDiv
!== null) {
1417 labelsDiv
.innerHTML
= html
;
1419 if (typeof(this.shown_legend_error_
) == 'undefined') {
1420 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1421 this.shown_legend_error_
= true;
1427 * Draw dots over the selectied points in the data series. This function
1428 * takes care of cleanup of previously-drawn dots.
1431 Dygraph
.prototype.updateSelection_
= function() {
1432 // Clear the previously drawn vertical, if there is one
1433 var ctx
= this.canvas_ctx_
;
1434 if (this.previousVerticalX_
>= 0) {
1435 // Determine the maximum highlight circle size.
1436 var maxCircleSize
= 0;
1437 var labels
= this.attr_('labels');
1438 for (var i
= 1; i
< labels
.length
; i
++) {
1439 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1440 if (r
> maxCircleSize
) maxCircleSize
= r
;
1442 var px
= this.previousVerticalX_
;
1443 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1444 2 * maxCircleSize
+ 2, this.height_
);
1447 if (this.selPoints_
.length
> 0) {
1448 // Set the status message to indicate the selected point(s)
1449 if (this.attr_('showLabelsOnHighlight')) {
1450 this.setLegendHTML_(this.lastx_
, this.selPoints_
);
1453 // Draw colored circles over the center of each selected point
1454 var canvasx
= this.selPoints_
[0].canvasx
;
1456 for (var i
= 0; i
< this.selPoints_
.length
; i
++) {
1457 var pt
= this.selPoints_
[i
];
1458 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1460 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1462 ctx
.fillStyle
= this.plotter_
.colors
[pt
.name
];
1463 ctx
.arc(canvasx
, pt
.canvasy
, circleSize
, 0, 2 * Math
.PI
, false);
1468 this.previousVerticalX_
= canvasx
;
1473 * Manually set the selected points and display information about them in the
1474 * legend. The selection can be cleared using clearSelection() and queried
1475 * using getSelection().
1476 * @param { Integer } row number that should be highlighted (i.e. appear with
1477 * hover dots on the chart). Set to false to clear any selection.
1479 Dygraph
.prototype.setSelection
= function(row
) {
1480 // Extract the points we've selected
1481 this.selPoints_
= [];
1484 if (row
!== false) {
1485 row
= row
-this.boundaryIds_
[0][0];
1488 if (row
!== false && row
>= 0) {
1489 for (var i
in this.layout_
.datasets
) {
1490 if (row
< this.layout_
.datasets
[i
].length
) {
1491 var point
= this.layout_
.points
[pos
+row
];
1493 if (this.attr_("stackedGraph")) {
1494 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
1497 this.selPoints_
.push(point
);
1499 pos
+= this.layout_
.datasets
[i
].length
;
1503 if (this.selPoints_
.length
) {
1504 this.lastx_
= this.selPoints_
[0].xval
;
1505 this.updateSelection_();
1507 this.clearSelection();
1513 * The mouse has left the canvas. Clear out whatever artifacts remain
1514 * @param {Object} event the mouseout event from the browser.
1517 Dygraph
.prototype.mouseOut_
= function(event
) {
1518 if (this.attr_("unhighlightCallback")) {
1519 this.attr_("unhighlightCallback")(event
);
1522 if (this.attr_("hideOverlayOnMouseOut")) {
1523 this.clearSelection();
1528 * Clears the current selection (i.e. points that were highlighted by moving
1529 * the mouse over the chart).
1531 Dygraph
.prototype.clearSelection
= function() {
1532 // Get rid of the overlay data
1533 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1534 this.setLegendHTML_();
1535 this.selPoints_
= [];
1540 * Returns the number of the currently selected row. To get data for this row,
1541 * you can use the getValue method.
1542 * @return { Integer } row number, or -1 if nothing is selected
1544 Dygraph
.prototype.getSelection
= function() {
1545 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1549 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
1550 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
1551 return row
+ this.boundaryIds_
[0][0];
1558 * Fires when there's data available to be graphed.
1559 * @param {String} data Raw CSV data to be plotted
1562 Dygraph
.prototype.loadedEvent_
= function(data
) {
1563 this.rawData_
= this.parseCSV_(data
);
1568 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1571 Dygraph
.prototype.addXTicks_
= function() {
1572 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1574 if (this.dateWindow_
) {
1575 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
1577 range
= [this.rawData_
[0][0], this.rawData_
[this.rawData_
.length
- 1][0]];
1580 var xAxisOptionsView
= this.optionsViewForAxis_('x');
1581 var xTicks
= xAxisOptionsView('ticker')(
1584 this.width_
, // TODO(danvk): should be area.width
1587 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
1588 // console.log(msg);
1589 this.layout_
.setXTicks(xTicks
);
1594 * Computes the range of the data series (including confidence intervals).
1595 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
1596 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
1597 * @return [low, high]
1599 Dygraph
.prototype.extremeValues_
= function(series
) {
1600 var minY
= null, maxY
= null;
1602 var bars
= this.attr_("errorBars") || this.attr_("customBars");
1604 // With custom bars, maxY is the max of the high values.
1605 for (var j
= 0; j
< series
.length
; j
++) {
1606 var y
= series
[j
][1][0];
1608 var low
= y
- series
[j
][1][1];
1609 var high
= y
+ series
[j
][1][2];
1610 if (low
> y
) low
= y
; // this can happen with custom bars,
1611 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
1612 if (maxY
== null || high
> maxY
) {
1615 if (minY
== null || low
< minY
) {
1620 for (var j
= 0; j
< series
.length
; j
++) {
1621 var y
= series
[j
][1];
1622 if (y
=== null || isNaN(y
)) continue;
1623 if (maxY
== null || y
> maxY
) {
1626 if (minY
== null || y
< minY
) {
1632 return [minY
, maxY
];
1637 * This function is called once when the chart's data is changed or the options
1638 * dictionary is updated. It is _not_ called when the user pans or zooms. The
1639 * idea is that values derived from the chart's data can be computed here,
1640 * rather than every time the chart is drawn. This includes things like the
1641 * number of axes, rolling averages, etc.
1643 Dygraph
.prototype.predraw_
= function() {
1644 var start
= new Date();
1646 // TODO(danvk): move more computations out of drawGraph_ and into here.
1647 this.computeYAxes_();
1649 // Create a new plotter.
1650 if (this.plotter_
) this.plotter_
.clear();
1651 this.plotter_
= new DygraphCanvasRenderer(this,
1656 // The roller sits in the bottom left corner of the chart. We don't know where
1657 // this will be until the options are available, so it's positioned here.
1658 this.createRollInterface_();
1660 // Same thing applies for the labelsDiv. It's right edge should be flush with
1661 // the right edge of the charting area (which may not be the same as the right
1662 // edge of the div, if we have two y-axes.
1663 this.positionLabelsDiv_();
1665 // If the data or options have changed, then we'd better redraw.
1668 // This is used to determine whether to do various animations.
1669 var end
= new Date();
1670 this.drawingTimeMs_
= (end
- start
);
1674 * Update the graph with new data. This method is called when the viewing area
1675 * has changed. If the underlying data or options have changed, predraw_ will
1676 * be called before drawGraph_ is called.
1678 * clearSelection, when undefined or true, causes this.clearSelection to be
1679 * called at the end of the draw operation. This should rarely be defined,
1680 * and never true (that is it should be undefined most of the time, and
1685 Dygraph
.prototype.drawGraph_
= function(clearSelection
) {
1686 var start
= new Date();
1688 if (typeof(clearSelection
) === 'undefined') {
1689 clearSelection
= true;
1692 var data
= this.rawData_
;
1694 // This is used to set the second parameter to drawCallback, below.
1695 var is_initial_draw
= this.is_initial_draw_
;
1696 this.is_initial_draw_
= false;
1698 var minY
= null, maxY
= null;
1699 this.layout_
.removeAllDatasets();
1701 this.attrs_
['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
1703 // Loop over the fields (series). Go from the last to the first,
1704 // because if they're stacked that's how we accumulate the values.
1706 var cumulative_y
= []; // For stacked series.
1709 var extremes
= {}; // series name -> [low, high]
1711 // Loop over all fields and create datasets
1712 for (var i
= data
[0].length
- 1; i
>= 1; i
--) {
1713 if (!this.visibility()[i
- 1]) continue;
1715 var seriesName
= this.attr_("labels")[i
];
1716 var connectSeparatedPoints
= this.attr_('connectSeparatedPoints', i
);
1717 var logScale
= this.attr_('logscale', i
);
1720 for (var j
= 0; j
< data
.length
; j
++) {
1721 var date
= data
[j
][0];
1722 var point
= data
[j
][i
];
1724 // On the log scale, points less than zero do not exist.
1725 // This will create a gap in the chart. Note that this ignores
1726 // connectSeparatedPoints.
1730 series
.push([date
, point
]);
1732 if (point
!= null || !connectSeparatedPoints
) {
1733 series
.push([date
, point
]);
1738 // TODO(danvk): move this into predraw_. It's insane to do it here.
1739 series
= this.rollingAverage(series
, this.rollPeriod_
);
1741 // Prune down to the desired range, if necessary (for zooming)
1742 // Because there can be lines going to points outside of the visible area,
1743 // we actually prune to visible points, plus one on either side.
1744 var bars
= this.attr_("errorBars") || this.attr_("customBars");
1745 if (this.dateWindow_
) {
1746 var low
= this.dateWindow_
[0];
1747 var high
= this.dateWindow_
[1];
1749 // TODO(danvk): do binary search instead of linear search.
1750 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
1751 var firstIdx
= null, lastIdx
= null;
1752 for (var k
= 0; k
< series
.length
; k
++) {
1753 if (series
[k
][0] >= low
&& firstIdx
=== null) {
1756 if (series
[k
][0] <= high
) {
1760 if (firstIdx
=== null) firstIdx
= 0;
1761 if (firstIdx
> 0) firstIdx
--;
1762 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
1763 if (lastIdx
< series
.length
- 1) lastIdx
++;
1764 this.boundaryIds_
[i
-1] = [firstIdx
, lastIdx
];
1765 for (var k
= firstIdx
; k
<= lastIdx
; k
++) {
1766 pruned
.push(series
[k
]);
1770 this.boundaryIds_
[i
-1] = [0, series
.length
-1];
1773 var seriesExtremes
= this.extremeValues_(series
);
1776 for (var j
=0; j
<series
.length
; j
++) {
1777 val
= [series
[j
][0], series
[j
][1][0], series
[j
][1][1], series
[j
][1][2]];
1780 } else if (this.attr_("stackedGraph")) {
1781 var l
= series
.length
;
1783 for (var j
= 0; j
< l
; j
++) {
1784 // If one data set has a NaN, let all subsequent stacked
1785 // sets inherit the NaN -- only start at 0 for the first set.
1786 var x
= series
[j
][0];
1787 if (cumulative_y
[x
] === undefined
) {
1788 cumulative_y
[x
] = 0;
1791 actual_y
= series
[j
][1];
1792 cumulative_y
[x
] += actual_y
;
1794 series
[j
] = [x
, cumulative_y
[x
]]
1796 if (cumulative_y
[x
] > seriesExtremes
[1]) {
1797 seriesExtremes
[1] = cumulative_y
[x
];
1799 if (cumulative_y
[x
] < seriesExtremes
[0]) {
1800 seriesExtremes
[0] = cumulative_y
[x
];
1804 extremes
[seriesName
] = seriesExtremes
;
1806 datasets
[i
] = series
;
1809 for (var i
= 1; i
< datasets
.length
; i
++) {
1810 if (!this.visibility()[i
- 1]) continue;
1811 this.layout_
.addDataset(this.attr_("labels")[i
], datasets
[i
]);
1814 this.computeYAxisRanges_(extremes
);
1815 this.layout_
.setYAxes(this.axes_
);
1819 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
1820 var tmp_zoomed_x
= this.zoomed_x_
;
1821 // Tell PlotKit to use this new data and render itself
1822 this.layout_
.setDateWindow(this.dateWindow_
);
1823 this.zoomed_x_
= tmp_zoomed_x
;
1824 this.layout_
.evaluateWithError();
1825 this.renderGraph_(is_initial_draw
, false);
1827 if (this.attr_("timingName")) {
1828 var end
= new Date();
1830 console
.log(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms")
1835 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
, clearSelection
) {
1836 this.plotter_
.clear();
1837 this.plotter_
.render();
1838 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
1839 this.canvas_
.height
);
1841 if (is_initial_draw
) {
1842 // Generate a static legend before any particular point is selected.
1843 this.setLegendHTML_();
1845 if (clearSelection
) {
1846 if (typeof(this.selPoints_
) !== 'undefined' && this.selPoints_
.length
) {
1847 // We should select the point nearest the page x/y here
, but it
's easier
1848 // to just clear the selection. This prevents erroneous hover dots from
1850 this.clearSelection();
1852 this.clearSelection();
1857 if (this.attr_("drawCallback") !== null) {
1858 this.attr_("drawCallback")(this, is_initial_draw);
1864 * Determine properties of the y-axes which are independent of the data
1865 * currently being displayed. This includes things like the number of axes and
1866 * the style of the axes. It does not include the range of each axis and its
1868 * This fills in this.axes_ and this.seriesToAxisMap_.
1869 * axes_ = [ { options } ]
1870 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
1871 * indices are into the axes_ array.
1873 Dygraph.prototype.computeYAxes_ = function() {
1874 // Preserve valueWindow settings if they exist, and if the user hasn't
1875 // specified a new valueRange.
1877 if (this.axes_
!= undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") == false) {
1879 for (var index
= 0; index
< this.axes_
.length
; index
++) {
1880 valueWindows
.push(this.axes_
[index
].valueWindow
);
1884 this.axes_
= [{ yAxisId
: 0, g
: this }]; // always have at least one y-axis.
1885 this.seriesToAxisMap_
= {};
1887 // Get a list of series names.
1888 var labels
= this.attr_("labels");
1890 for (var i
= 1; i
< labels
.length
; i
++) series
[labels
[i
]] = (i
- 1);
1892 // all options which could be applied per-axis:
1900 'axisLabelFontSize',
1905 // Copy global axis options over to the first axis.
1906 for (var i
= 0; i
< axisOptions
.length
; i
++) {
1907 var k
= axisOptions
[i
];
1908 var v
= this.attr_(k
);
1909 if (v
) this.axes_
[0][k
] = v
;
1912 // Go through once and add all the axes.
1913 for (var seriesName
in series
) {
1914 if (!series
.hasOwnProperty(seriesName
)) continue;
1915 var axis
= this.attr_("axis", seriesName
);
1917 this.seriesToAxisMap_
[seriesName
] = 0;
1920 if (typeof(axis
) == 'object') {
1921 // Add a new axis, making a copy of its per-axis options.
1923 Dygraph
.update(opts
, this.axes_
[0]);
1924 Dygraph
.update(opts
, { valueRange
: null }); // shouldn't inherit this.
1925 var yAxisId
= this.axes_
.length
;
1926 opts
.yAxisId
= yAxisId
;
1928 Dygraph
.update(opts
, axis
);
1929 this.axes_
.push(opts
);
1930 this.seriesToAxisMap_
[seriesName
] = yAxisId
;
1934 // Go through one more time and assign series to an axis defined by another
1935 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
1936 for (var seriesName
in series
) {
1937 if (!series
.hasOwnProperty(seriesName
)) continue;
1938 var axis
= this.attr_("axis", seriesName
);
1939 if (typeof(axis
) == 'string') {
1940 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
1941 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
1942 "series " + axis
+ ", which does not define its own axis.");
1945 var idx
= this.seriesToAxisMap_
[axis
];
1946 this.seriesToAxisMap_
[seriesName
] = idx
;
1950 // Now we remove series from seriesToAxisMap_ which are not visible. We do
1951 // this last so that hiding the first series doesn't destroy the axis
1952 // properties of the primary axis.
1953 var seriesToAxisFiltered
= {};
1954 var vis
= this.visibility();
1955 for (var i
= 1; i
< labels
.length
; i
++) {
1957 if (vis
[i
- 1]) seriesToAxisFiltered
[s
] = this.seriesToAxisMap_
[s
];
1959 this.seriesToAxisMap_
= seriesToAxisFiltered
;
1961 if (valueWindows
!= undefined
) {
1962 // Restore valueWindow settings.
1963 for (var index
= 0; index
< valueWindows
.length
; index
++) {
1964 this.axes_
[index
].valueWindow
= valueWindows
[index
];
1970 * Returns the number of y-axes on the chart.
1971 * @return {Number} the number of axes.
1973 Dygraph
.prototype.numAxes
= function() {
1975 for (var series
in this.seriesToAxisMap_
) {
1976 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
1977 var idx
= this.seriesToAxisMap_
[series
];
1978 if (idx
> last_axis
) last_axis
= idx
;
1980 return 1 + last_axis
;
1985 * Returns axis properties for the given series.
1986 * @param { String } setName The name of the series for which to get axis
1987 * properties, e.g. 'Y1'.
1988 * @return { Object } The axis properties.
1990 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
1991 // TODO(danvk): handle errors.
1992 return this.axes_
[this.seriesToAxisMap_
[series
]];
1997 * Determine the value range and tick marks for each axis.
1998 * @param {Object} extremes A mapping from seriesName -> [low, high]
1999 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2001 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2002 // Build a map from axis number -> [list of series names]
2003 var seriesForAxis
= [];
2004 for (var series
in this.seriesToAxisMap_
) {
2005 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2006 var idx
= this.seriesToAxisMap_
[series
];
2007 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2008 seriesForAxis
[idx
].push(series
);
2011 // Compute extreme values, a span and tick marks for each axis.
2012 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2013 var axis
= this.axes_
[i
];
2015 if (!seriesForAxis
[i
]) {
2016 // If no series are defined or visible then use a reasonable default
2017 axis
.extremeRange
= [0, 1];
2019 // Calculate the extremes of extremes.
2020 var series
= seriesForAxis
[i
];
2021 var minY
= Infinity
; // extremes[series[0]][0];
2022 var maxY
= -Infinity
; // extremes[series[0]][1];
2023 var extremeMinY
, extremeMaxY
;
2024 for (var j
= 0; j
< series
.length
; j
++) {
2025 // Only use valid extremes to stop null data series' from corrupting the scale.
2026 extremeMinY
= extremes
[series
[j
]][0];
2027 if (extremeMinY
!= null) {
2028 minY
= Math
.min(extremeMinY
, minY
);
2030 extremeMaxY
= extremes
[series
[j
]][1];
2031 if (extremeMaxY
!= null) {
2032 maxY
= Math
.max(extremeMaxY
, maxY
);
2035 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2037 // Ensure we have a valid scale, otherwise defualt to zero for safety.
2038 if (minY
== Infinity
) minY
= 0;
2039 if (maxY
== -Infinity
) maxY
= 0;
2041 // Add some padding and round up to an integer to be human-friendly.
2042 var span
= maxY
- minY
;
2043 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2044 if (span
== 0) { span
= maxY
; }
2048 if (axis
.logscale
) {
2049 var maxAxisY
= maxY
+ 0.1 * span
;
2050 var minAxisY
= minY
;
2052 var maxAxisY
= maxY
+ 0.1 * span
;
2053 var minAxisY
= minY
- 0.1 * span
;
2055 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2056 if (!this.attr_("avoidMinZero")) {
2057 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2058 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2061 if (this.attr_("includeZero")) {
2062 if (maxY
< 0) maxAxisY
= 0;
2063 if (minY
> 0) minAxisY
= 0;
2066 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2068 if (axis
.valueWindow
) {
2069 // This is only set if the user has zoomed on the y-axis. It is never set
2070 // by a user. It takes precedence over axis.valueRange because, if you set
2071 // valueRange, you'd still expect to be able to pan.
2072 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2073 } else if (axis
.valueRange
) {
2074 // This is a user-set value range for this axis.
2075 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
2077 axis
.computedValueRange
= axis
.extremeRange
;
2080 // Add ticks. By default, all axes inherit the tick positions of the
2081 // primary axis. However, if an axis is specifically marked as having
2082 // independent ticks, then that is permissible as well.
2083 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2084 var ticker
= opts('ticker');
2085 if (i
== 0 || axis
.independentTicks
) {
2086 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2087 axis
.computedValueRange
[1],
2088 this.height_
, // TODO(danvk): should be area.height
2092 var p_axis
= this.axes_
[0];
2093 var p_ticks
= p_axis
.ticks
;
2094 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2095 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2096 var tick_values
= [];
2097 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2098 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2099 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2100 tick_values
.push(y_val
);
2103 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2104 axis
.computedValueRange
[1],
2105 this.height_
, // TODO(danvk): should be area.height
2115 * Calculates the rolling average of a data set.
2116 * If originalData is [label, val], rolls the average of those.
2117 * If originalData is [label, [, it's interpreted as [value, stddev]
2118 * and the roll is returned in the same form, with appropriately reduced
2119 * stddev for each value.
2120 * Note that this is where fractional input (i.e. '5/10') is converted into
2122 * @param {Array} originalData The data in the appropriate format (see above)
2123 * @param {Number} rollPeriod The number of points over which to average the
2126 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2127 if (originalData
.length
< 2)
2128 return originalData
;
2129 var rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2130 var rollingData
= [];
2131 var sigma
= this.attr_("sigma");
2133 if (this.fractions_
) {
2135 var den
= 0; // numerator/denominator
2137 for (var i
= 0; i
< originalData
.length
; i
++) {
2138 num
+= originalData
[i
][1][0];
2139 den
+= originalData
[i
][1][1];
2140 if (i
- rollPeriod
>= 0) {
2141 num
-= originalData
[i
- rollPeriod
][1][0];
2142 den
-= originalData
[i
- rollPeriod
][1][1];
2145 var date
= originalData
[i
][0];
2146 var value
= den
? num
/ den
: 0.0;
2147 if (this.attr_("errorBars")) {
2148 if (this.wilsonInterval_
) {
2149 // For more details on this confidence interval, see:
2150 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2152 var p
= value
< 0 ? 0 : value
, n
= den
;
2153 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2154 var denom
= 1 + sigma
* sigma
/ den
;
2155 var low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2156 var high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2157 rollingData
[i
] = [date
,
2158 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2160 rollingData
[i
] = [date
, [0, 0, 0]];
2163 var stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2164 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2167 rollingData
[i
] = [date
, mult
* value
];
2170 } else if (this.attr_("customBars")) {
2175 for (var i
= 0; i
< originalData
.length
; i
++) {
2176 var data
= originalData
[i
][1];
2178 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2180 if (y
!= null && !isNaN(y
)) {
2186 if (i
- rollPeriod
>= 0) {
2187 var prev
= originalData
[i
- rollPeriod
];
2188 if (prev
[1][1] != null && !isNaN(prev
[1][1])) {
2196 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2197 1.0 * (mid
- low
) / count
,
2198 1.0 * (high
- mid
) / count
]];
2200 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2204 // Calculate the rolling average for the first rollPeriod - 1 points where
2205 // there is not enough data to roll over the full number of points
2206 var num_init_points
= Math
.min(rollPeriod
- 1, originalData
.length
- 2);
2207 if (!this.attr_("errorBars")){
2208 if (rollPeriod
== 1) {
2209 return originalData
;
2212 for (var i
= 0; i
< originalData
.length
; i
++) {
2215 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2216 var y
= originalData
[j
][1];
2217 if (y
== null || isNaN(y
)) continue;
2219 sum
+= originalData
[j
][1];
2222 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2224 rollingData
[i
] = [originalData
[i
][0], null];
2229 for (var i
= 0; i
< originalData
.length
; i
++) {
2233 for (var j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2234 var y
= originalData
[j
][1][0];
2235 if (y
== null || isNaN(y
)) continue;
2237 sum
+= originalData
[j
][1][0];
2238 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2241 var stddev
= Math
.sqrt(variance
) / num_ok
;
2242 rollingData
[i
] = [originalData
[i
][0],
2243 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2245 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2255 * Detects the type of the str (date or numeric) and sets the various
2256 * formatting attributes in this.attrs_ based on this type.
2257 * @param {String} str An x value.
2260 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2262 if (str
.indexOf('-') > 0 ||
2263 str
.indexOf('/') >= 0 ||
2264 isNaN(parseFloat(str
))) {
2266 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2267 // TODO(danvk): remove support for this format.
2272 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2273 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
2274 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2275 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2277 /** @private (shut up, jsdoc!) */
2278 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2279 // TODO(danvk): use Dygraph.numberValueFormatter here?
2280 /** @private (shut up, jsdoc!) */
2281 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2282 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
2283 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2288 * Parses the value as a floating point number. This is like the parseFloat()
2289 * built-in, but with a few differences:
2290 * - the empty string is parsed as null, rather than NaN.
2291 * - if the string cannot be parsed at all, an error is logged.
2292 * If the string can't be parsed, this method returns null.
2293 * @param {String} x The string to be parsed
2294 * @param {Number} opt_line_no The line number from which the string comes.
2295 * @param {String} opt_line The text of the line from which the string comes.
2299 // Parse the x as a float or return null if it's not a number.
2300 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
2301 var val
= parseFloat(x
);
2302 if (!isNaN(val
)) return val
;
2304 // Try to figure out what happeend.
2305 // If the value is the empty string, parse it as null.
2306 if (/^ *$/.test(x
)) return null;
2308 // If it was actually "NaN", return it as NaN.
2309 if (/^ *nan *$/i.test(x
)) return NaN
;
2311 // Looks like a parsing error.
2312 var msg
= "Unable to parse '" + x
+ "' as a number";
2313 if (opt_line
!== null && opt_line_no
!== null) {
2314 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
2323 * Parses a string in a special csv format. We expect a csv file where each
2324 * line is a date point, and the first field in each line is the date string.
2325 * We also expect that all remaining fields represent series.
2326 * if the errorBars attribute is set, then interpret the fields as:
2327 * date, series1, stddev1, series2, stddev2, ...
2328 * @param {[Object]} data See above.
2330 * @return [Object] An array with one entry for each row. These entries
2331 * are an array of cells in that row. The first entry is the parsed x-value for
2332 * the row. The second, third, etc. are the y-values. These can take on one of
2333 * three forms, depending on the CSV and constructor parameters:
2335 * 2. [ value, stddev ]
2336 * 3. [ low value, center value, high value ]
2338 Dygraph
.prototype.parseCSV_
= function(data
) {
2340 var lines
= data
.split("\n");
2342 // Use the default delimiter or fall back to a tab if that makes sense.
2343 var delim
= this.attr_('delimiter');
2344 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2349 if (!('labels' in this.user_attrs_
)) {
2350 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
2352 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
2357 var defaultParserSet
= false; // attempt to auto-detect x value type
2358 var expectedCols
= this.attr_("labels").length
;
2359 var outOfOrder
= false;
2360 for (var i
= start
; i
< lines
.length
; i
++) {
2361 var line
= lines
[i
];
2363 if (line
.length
== 0) continue; // skip blank lines
2364 if (line
[0] == '#') continue; // skip comment lines
2365 var inFields
= line
.split(delim
);
2366 if (inFields
.length
< 2) continue;
2369 if (!defaultParserSet
) {
2370 this.detectTypeFromString_(inFields
[0]);
2371 xParser
= this.attr_("xValueParser");
2372 defaultParserSet
= true;
2374 fields
[0] = xParser(inFields
[0], this);
2376 // If fractions are expected, parse the numbers as "A/B
"
2377 if (this.fractions_) {
2378 for (var j = 1; j < inFields.length; j++) {
2379 // TODO(danvk): figure out an appropriate way to flag parse errors.
2380 var vals = inFields[j].split("/");
2381 if (vals.length != 2) {
2382 this.error('Expected fractional "num
/den
" values in CSV data ' +
2383 "but found a value
'" + inFields[j] + "' on line
" +
2384 (1 + i) + " ('" + line + "') which is not of
this form
.");
2387 fields[j] = [this.parseFloat_(vals[0], i, line),
2388 this.parseFloat_(vals[1], i, line)];
2391 } else if (this.attr_("errorBars
")) {
2392 // If there are error bars, values are (value, stddev) pairs
2393 if (inFields.length % 2 != 1) {
2394 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2395 'but line ' + (1 + i) + ' has an odd number of values (' +
2396 (inFields.length - 1) + "): '" + line + "'");
2398 for (var j = 1; j < inFields.length; j += 2) {
2399 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2400 this.parseFloat_(inFields[j + 1], i, line)];
2402 } else if (this.attr_("customBars
")) {
2403 // Bars are a low;center;high tuple
2404 for (var j = 1; j < inFields.length; j++) {
2405 var val = inFields[j];
2406 if (/^ *$/.test(val)) {
2407 fields[j] = [null, null, null];
2409 var vals = val.split(";");
2410 if (vals.length == 3) {
2411 fields[j] = [ this.parseFloat_(vals[0], i, line),
2412 this.parseFloat_(vals[1], i, line),
2413 this.parseFloat_(vals[2], i, line) ];
2415 this.warning('When using customBars, values must be either blank ' +
2416 'or "low
;center
;high
" tuples (got "' + val +
2417 '" on line ' + (1+i));
2422 // Values are just numbers
2423 for (var j = 1; j < inFields.length; j++) {
2424 fields[j] = this.parseFloat_(inFields[j], i, line);
2427 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2431 if (fields.length != expectedCols) {
2432 this.error("Number of columns
in line
" + i + " (" + fields.length +
2433 ") does not agree
with number of
labels (" + expectedCols +
2437 // If the user specified the 'labels' option and none of the cells of the
2438 // first row parsed correctly, then they probably double-specified the
2439 // labels. We go with the values set in the option, discard this row and
2440 // log a warning to the JS console.
2441 if (i == 0 && this.attr_('labels')) {
2442 var all_null = true;
2443 for (var j = 0; all_null && j < fields.length; j++) {
2444 if (fields[j]) all_null = false;
2447 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
2448 "CSV
data ('" + line + "') appears to also contain labels
. " +
2449 "Will drop the CSV labels and
use the option labels
.");
2457 this.warn("CSV is out of order
; order it correctly to speed loading
.");
2458 ret.sort(function(a,b) { return a[0] - b[0] });
2466 * The user has provided their data as a pre-packaged JS array. If the x values
2467 * are numeric, this is the same as dygraphs' internal format. If the x values
2468 * are dates, we need to convert them from Date objects to ms since epoch.
2469 * @param {[Object]} data
2470 * @return {[Object]} data with numeric x values.
2472 Dygraph.prototype.parseArray_ = function(data) {
2473 // Peek at the first x value to see if it's numeric.
2474 if (data.length == 0) {
2475 this.error("Can
't plot empty data set");
2478 if (data[0].length == 0) {
2479 this.error("Data set cannot contain an empty row");
2483 if (this.attr_("labels") == null) {
2484 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
2485 "in the options parameter");
2486 this.attrs_.labels = [ "X" ];
2487 for (var i = 1; i < data[0].length; i++) {
2488 this.attrs_.labels.push("Y" + i);
2492 if (Dygraph.isDateLike(data[0][0])) {
2493 // Some intelligent defaults for a date x-axis.
2494 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2495 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
2496 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2498 // Assume they're all dates
.
2499 var parsedData
= Dygraph
.clone(data
);
2500 for (var i
= 0; i
< data
.length
; i
++) {
2501 if (parsedData
[i
].length
== 0) {
2502 this.error("Row " + (1 + i
) + " of data is empty");
2505 if (parsedData
[i
][0] == null
2506 || typeof(parsedData
[i
][0].getTime
) != 'function'
2507 || isNaN(parsedData
[i
][0].getTime())) {
2508 this.error("x value in row " + (1 + i
) + " is not a Date");
2511 parsedData
[i
][0] = parsedData
[i
][0].getTime();
2515 // Some intelligent defaults for a numeric x-axis.
2516 /** @private (shut up, jsdoc!) */
2517 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2518 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
2519 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
2525 * Parses a DataTable object from gviz.
2526 * The data is expected to have a first column that is either a date or a
2527 * number. All subsequent columns must be numbers. If there is a clear mismatch
2528 * between this.xValueParser_ and the type of the first column, it will be
2529 * fixed. Fills out rawData_.
2530 * @param {[Object]} data See above.
2533 Dygraph
.prototype.parseDataTable_
= function(data
) {
2534 var cols
= data
.getNumberOfColumns();
2535 var rows
= data
.getNumberOfRows();
2537 var indepType
= data
.getColumnType(0);
2538 if (indepType
== 'date' || indepType
== 'datetime') {
2539 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2540 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
2541 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2542 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2543 } else if (indepType
== 'number') {
2544 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2545 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2546 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
2547 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2549 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2550 "column 1 of DataTable input (Got '" + indepType
+ "')");
2554 // Array of the column indices which contain data (and not annotations).
2556 var annotationCols
= {}; // data index -> [annotation cols]
2557 var hasAnnotations
= false;
2558 for (var i
= 1; i
< cols
; i
++) {
2559 var type
= data
.getColumnType(i
);
2560 if (type
== 'number') {
2562 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
2563 // This is OK -- it's an annotation column.
2564 var dataIdx
= colIdx
[colIdx
.length
- 1];
2565 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
2566 annotationCols
[dataIdx
] = [i
];
2568 annotationCols
[dataIdx
].push(i
);
2570 hasAnnotations
= true;
2572 this.error("Only 'number' is supported as a dependent type with Gviz." +
2573 " 'string' is only supported if displayAnnotations is true");
2577 // Read column labels
2578 // TODO(danvk): add support back for errorBars
2579 var labels
= [data
.getColumnLabel(0)];
2580 for (var i
= 0; i
< colIdx
.length
; i
++) {
2581 labels
.push(data
.getColumnLabel(colIdx
[i
]));
2582 if (this.attr_("errorBars")) i
+= 1;
2584 this.attrs_
.labels
= labels
;
2585 cols
= labels
.length
;
2588 var outOfOrder
= false;
2589 var annotations
= [];
2590 for (var i
= 0; i
< rows
; i
++) {
2592 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
2593 data
.getValue(i
, 0) === null) {
2594 this.warn("Ignoring row " + i
+
2595 " of DataTable because of undefined or null first column.");
2599 if (indepType
== 'date' || indepType
== 'datetime') {
2600 row
.push(data
.getValue(i
, 0).getTime());
2602 row
.push(data
.getValue(i
, 0));
2604 if (!this.attr_("errorBars")) {
2605 for (var j
= 0; j
< colIdx
.length
; j
++) {
2606 var col
= colIdx
[j
];
2607 row
.push(data
.getValue(i
, col
));
2608 if (hasAnnotations
&&
2609 annotationCols
.hasOwnProperty(col
) &&
2610 data
.getValue(i
, annotationCols
[col
][0]) != null) {
2612 ann
.series
= data
.getColumnLabel(col
);
2614 ann
.shortText
= String
.fromCharCode(65 /* A */ + annotations
.length
)
2616 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
2617 if (k
) ann
.text
+= "\n";
2618 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
2620 annotations
.push(ann
);
2624 // Strip out infinities, which give dygraphs problems later on.
2625 for (var j
= 0; j
< row
.length
; j
++) {
2626 if (!isFinite(row
[j
])) row
[j
] = null;
2629 for (var j
= 0; j
< cols
- 1; j
++) {
2630 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
2633 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
2640 this.warn("DataTable is out of order; order it correctly to speed loading.");
2641 ret
.sort(function(a
,b
) { return a
[0] - b
[0] });
2643 this.rawData_
= ret
;
2645 if (annotations
.length
> 0) {
2646 this.setAnnotations(annotations
, true);
2651 * Get the CSV data. If it's in a function, call that function. If it's in a
2652 * file, do an XMLHttpRequest to get it.
2655 Dygraph
.prototype.start_
= function() {
2656 if (typeof this.file_
== 'function') {
2657 // CSV string. Pretend we got it via XHR.
2658 this.loadedEvent_(this.file_());
2659 } else if (Dygraph
.isArrayLike(this.file_
)) {
2660 this.rawData_
= this.parseArray_(this.file_
);
2662 } else if (typeof this.file_
== 'object' &&
2663 typeof this.file_
.getColumnRange
== 'function') {
2664 // must be a DataTable from gviz.
2665 this.parseDataTable_(this.file_
);
2667 } else if (typeof this.file_
== 'string') {
2668 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2669 if (this.file_
.indexOf('\n') >= 0) {
2670 this.loadedEvent_(this.file_
);
2672 var req
= new XMLHttpRequest();
2674 req
.onreadystatechange
= function () {
2675 if (req
.readyState
== 4) {
2676 if (req
.status
== 200 || // Normal http
2677 req
.status
== 0) { // Chrome w/ --allow
-file
-access
-from
-files
2678 caller
.loadedEvent_(req
.responseText
);
2683 req
.open("GET", this.file_
, true);
2687 this.error("Unknown data format: " + (typeof this.file_
));
2692 * Changes various properties of the graph. These can include:
2694 * <li>file: changes the source data for the graph</li>
2695 * <li>errorBars: changes whether the data contains stddev</li>
2698 * There's a huge variety of options that can be passed to this method. For a
2699 * full list, see http://dygraphs.com/options.html.
2701 * @param {Object} attrs The new properties and values
2702 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
2703 * call to updateOptions(). If you know better, you can pass true to explicitly
2704 * block the redraw. This can be useful for chaining updateOptions() calls,
2705 * avoiding the occasional infinite loop and preventing redraws when it's not
2706 * necessary (e.g. when updating a callback).
2708 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
2709 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
2711 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
2712 var file
= input_attrs
['file'];
2713 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
2715 // TODO(danvk): this is a mess. Move these options into attr_.
2716 if ('rollPeriod' in attrs
) {
2717 this.rollPeriod_
= attrs
.rollPeriod
;
2719 if ('dateWindow' in attrs
) {
2720 this.dateWindow_
= attrs
.dateWindow
;
2721 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
2722 this.zoomed_x_
= attrs
.dateWindow
!= null;
2725 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
2726 this.zoomed_y_
= attrs
.valueRange
!= null;
2729 // TODO(danvk): validate per-series options.
2734 // highlightCircleSize
2736 // Check if this set options will require new points.
2737 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
2739 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
2743 if (!block_redraw
) this.start_();
2745 if (!block_redraw
) {
2746 if (requiresNewPoints
) {
2749 this.renderGraph_(false, false);
2756 * Returns a copy of the options with deprecated names converted into current
2757 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
2758 * interested in that, they should save a copy before calling this.
2761 Dygraph
.mapLegacyOptions_
= function(attrs
) {
2763 for (var k
in attrs
) {
2764 if (k
== 'file') continue;
2765 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
2768 var set
= function(axis
, opt
, value
) {
2769 if (!my_attrs
.axes
) my_attrs
.axes
= {};
2770 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
2771 my_attrs
.axes
[axis
][opt
] = value
;
2773 var map
= function(opt
, axis
, new_opt
) {
2774 if (typeof(attrs
[opt
]) != 'undefined') {
2775 set(axis
, new_opt
, attrs
[opt
]);
2776 delete my_attrs
[opt
];
2780 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
2781 map('xValueFormatter', 'x', 'valueFormatter');
2782 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
2783 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
2784 map('xTicker', 'x', 'ticker');
2785 map('yValueFormatter', 'y', 'valueFormatter');
2786 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
2787 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
2788 map('yTicker', 'y', 'ticker');
2793 * Resizes the dygraph. If no parameters are specified, resizes to fill the
2794 * containing div (which has presumably changed size since the dygraph was
2795 * instantiated. If the width/height are specified, the div will be resized.
2797 * This is far more efficient than destroying and re-instantiating a
2798 * Dygraph, since it doesn't have to reparse the underlying data.
2800 * @param {Number} [width] Width (in pixels)
2801 * @param {Number} [height] Height (in pixels)
2803 Dygraph
.prototype.resize
= function(width
, height
) {
2804 if (this.resize_lock
) {
2807 this.resize_lock
= true;
2809 if ((width
=== null) != (height
=== null)) {
2810 this.warn("Dygraph.resize() should be called with zero parameters or " +
2811 "two non-NULL parameters. Pretending it was zero.");
2812 width
= height
= null;
2815 var old_width
= this.width_
;
2816 var old_height
= this.height_
;
2819 this.maindiv_
.style
.width
= width
+ "px";
2820 this.maindiv_
.style
.height
= height
+ "px";
2821 this.width_
= width
;
2822 this.height_
= height
;
2824 this.width_
= this.maindiv_
.offsetWidth
;
2825 this.height_
= this.maindiv_
.offsetHeight
;
2828 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
2829 // TODO(danvk): there should be a clear() method.
2830 this.maindiv_
.innerHTML
= "";
2831 this.roller_
= null;
2832 this.attrs_
.labelsDiv
= null;
2833 this.createInterface_();
2837 this.resize_lock
= false;
2841 * Adjusts the number of points in the rolling average. Updates the graph to
2842 * reflect the new averaging period.
2843 * @param {Number} length Number of points over which to average the data.
2845 Dygraph
.prototype.adjustRoll
= function(length
) {
2846 this.rollPeriod_
= length
;
2851 * Returns a boolean array of visibility statuses.
2853 Dygraph
.prototype.visibility
= function() {
2854 // Do lazy-initialization, so that this happens after we know the number of
2856 if (!this.attr_("visibility")) {
2857 this.attrs_
["visibility"] = [];
2859 while (this.attr_("visibility").length
< this.rawData_
[0].length
- 1) {
2860 this.attr_("visibility").push(true);
2862 return this.attr_("visibility");
2866 * Changes the visiblity of a series.
2868 Dygraph
.prototype.setVisibility
= function(num
, value
) {
2869 var x
= this.visibility();
2870 if (num
< 0 || num
>= x
.length
) {
2871 this.warn("invalid series number in setVisibility: " + num
);
2879 * How large of an area will the dygraph render itself in?
2880 * This is used for testing.
2881 * @return A {width: w, height: h} object.
2884 Dygraph
.prototype.size
= function() {
2885 return { width
: this.width_
, height
: this.height_
};
2889 * Update the list of annotations and redraw the chart.
2891 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
2892 // Only add the annotation CSS rule once we know it will be used.
2893 Dygraph
.addAnnotationRule();
2894 this.annotations_
= ann
;
2895 this.layout_
.setAnnotations(this.annotations_
);
2896 if (!suppressDraw
) {
2902 * Return the list of annotations.
2904 Dygraph
.prototype.annotations
= function() {
2905 return this.annotations_
;
2909 * Get the index of a series (column) given its name. The first column is the
2910 * x-axis, so the data series start with index 1.
2912 Dygraph
.prototype.indexFromSetName
= function(name
) {
2913 var labels
= this.attr_("labels");
2914 for (var i
= 0; i
< labels
.length
; i
++) {
2915 if (labels
[i
] == name
) return i
;
2922 * Adds a default style for the annotation CSS classes to the document. This is
2923 * only executed when annotations are actually used. It is designed to only be
2924 * called once -- all calls after the first will return immediately.
2926 Dygraph
.addAnnotationRule
= function() {
2927 if (Dygraph
.addedAnnotationCSS
) return;
2929 var rule
= "border: 1px solid black; " +
2930 "background-color: white; " +
2931 "text-align: center;";
2933 var styleSheetElement
= document
.createElement("style");
2934 styleSheetElement
.type
= "text/css";
2935 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
2937 // Find the first style sheet that we can access.
2938 // We may not add a rule to a style sheet from another domain for security
2939 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
2940 // adds its own style sheets from google.com.
2941 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
2942 if (document
.styleSheets
[i
].disabled
) continue;
2943 var mysheet
= document
.styleSheets
[i
];
2945 if (mysheet
.insertRule
) { // Firefox
2946 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
2947 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
2948 } else if (mysheet
.addRule
) { // IE
2949 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
2951 Dygraph
.addedAnnotationCSS
= true;
2954 // Was likely a security exception.
2958 this.warn("Unable to add default annotation CSS rule; display may be off.");
2961 // Older pages may still use this name.
2962 DateGraph
= Dygraph
;