3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
9 * string. Dygraph can handle multiple series with or without error bars. The
10 * date/value ranges will be automatically set. Dygraph uses the
11 * <canvas> tag, so it only works in FF1.5+.
12 * @author danvdk@gmail.com (Dan Vanderkam)
15 <div id="graphdiv" style="width:800px; height:500px;"></div>
16 <script type="text/javascript">
17 new Dygraph(document.getElementById("graphdiv"),
18 "datafile.csv", // CSV file with headers
22 The CSV file is of the form
24 Date,SeriesA,SeriesB,SeriesC
28 If the 'errorBars' option is set in the constructor, the input should be of
30 Date,SeriesA,SeriesB,...
31 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
32 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
34 If the 'fractions' option is set, the input should be of the form:
36 Date,SeriesA,SeriesB,...
37 YYYYMMDD,A1/B1,A2/B2,...
38 YYYYMMDD,A1/B1,A2/B2,...
40 And error bars will be calculated automatically using a binomial distribution.
42 For further documentation and examples, see http://dygraphs.com/
46 /*jshint globalstrict: true */
47 /*global DygraphRangeSelector:false, DygraphLayout:false, DygraphCanvasRenderer:false, G_vmlCanvasManager:false */
51 * Creates an interactive, zoomable chart.
54 * @param {div | String} div A div or the id of a div into which to construct
56 * @param {String | Function} file A file containing CSV data or a function
57 * that returns this data. The most basic expected format for each line is
58 * "YYYY/MM/DD,val1,val2,...". For more information, see
59 * http://dygraphs.com/data.html.
60 * @param {Object} attrs Various other attributes, e.g. errorBars determines
61 * whether the input data contains error ranges. For a complete list of
62 * options, see http://dygraphs.com/options.html.
64 var Dygraph
= function(div
, data
, opts
, opt_fourth_param
) {
65 if (opt_fourth_param
!== undefined
) {
66 // Old versions of dygraphs took in the series labels as a constructor
67 // parameter. This doesn't make sense anymore, but it's easy to continue
68 // to support this usage.
69 this.warn("Using deprecated four-argument dygraph constructor");
70 this.__old_init__(div
, data
, opts
, opt_fourth_param
);
72 this.__init__(div
, data
, opts
);
76 Dygraph
.NAME
= "Dygraph";
77 Dygraph
.VERSION
= "1.2";
78 Dygraph
.__repr__
= function() {
79 return "[" + this.NAME
+ " " + this.VERSION
+ "]";
83 * Returns information about the Dygraph class.
85 Dygraph
.toString
= function() {
86 return this.__repr__();
89 // Various default values
90 Dygraph
.DEFAULT_ROLL_PERIOD
= 1;
91 Dygraph
.DEFAULT_WIDTH
= 480;
92 Dygraph
.DEFAULT_HEIGHT
= 320;
94 Dygraph
.ANIMATION_STEPS
= 10;
95 Dygraph
.ANIMATION_DURATION
= 200;
97 // These are defined before DEFAULT_ATTRS so that it can refer to them.
100 * Return a string version of a number. This respects the digitsAfterDecimal
101 * and maxNumberWidth options.
102 * @param {Number} x The number to be formatted
103 * @param {Dygraph} opts An options view
104 * @param {String} name The name of the point's data series
105 * @param {Dygraph} g The dygraph object
107 Dygraph
.numberValueFormatter
= function(x
, opts
, pt
, g
) {
108 var sigFigs
= opts('sigFigs');
110 if (sigFigs
!== null) {
111 // User has opted for a fixed number of significant figures.
112 return Dygraph
.floatFormat(x
, sigFigs
);
115 var digits
= opts('digitsAfterDecimal');
116 var maxNumberWidth
= opts('maxNumberWidth');
118 // switch to scientific notation if we underflow or overflow fixed display.
120 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
121 Math
.abs(x
) < Math
.pow(10, -digits
))) {
122 return x
.toExponential(digits
);
124 return '' + Dygraph
.round_(x
, digits
);
129 * variant for use as an axisLabelFormatter.
132 Dygraph
.numberAxisLabelFormatter
= function(x
, granularity
, opts
, g
) {
133 return Dygraph
.numberValueFormatter(x
, opts
, g
);
137 * Convert a JS date (millis since epoch) to YYYY/MM/DD
138 * @param {Number} date The JavaScript date (ms since epoch)
139 * @return {String} A date of the form "YYYY/MM/DD"
142 Dygraph
.dateString_
= function(date
) {
143 var zeropad
= Dygraph
.zeropad
;
144 var d
= new Date(date
);
147 var year
= "" + d
.getFullYear();
148 // Get a 0 padded month string
149 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
150 // Get a 0 padded day string
151 var day
= zeropad(d
.getDate());
154 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
155 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
157 return year
+ "/" + month + "/" + day
+ ret
;
161 * Convert a JS date to a string appropriate to display on an axis that
162 * is displaying values at the stated granularity.
163 * @param {Date} date The date to format
164 * @param {Number} granularity One of the Dygraph granularity constants
165 * @return {String} The formatted date
168 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
169 if (granularity
>= Dygraph
.DECADAL
) {
170 return date
.strftime('%Y');
171 } else if (granularity
>= Dygraph
.MONTHLY
) {
172 return date
.strftime('%b %y');
174 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
175 if (frac
=== 0 || granularity
>= Dygraph
.DAILY
) {
176 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
178 return Dygraph
.hmsString_(date
.getTime());
184 // Default attribute values.
185 Dygraph
.DEFAULT_ATTRS
= {
186 highlightCircleSize
: 3,
187 highlightSeriesOpts
: null,
188 highlightSeriesBackgroundAlpha
: 0.5,
192 // TODO(danvk): move defaults from createStatusMessage_ here.
194 labelsSeparateLines
: false,
195 labelsShowZeroValues
: true,
198 showLabelsOnHighlight
: true,
200 digitsAfterDecimal
: 2,
205 strokeBorderWidth
: 0,
206 strokeBorderColor
: "white",
209 axisLabelFontSize
: 14,
215 xValueParser
: Dygraph
.dateParser
,
222 wilsonInterval
: true, // only relevant if fractions is true
226 connectSeparatedPoints
: false,
229 hideOverlayOnMouseOut
: true,
231 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
232 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
237 // Sizes of the various chart labels.
244 axisLineColor
: "black",
247 axisLabelColor
: "black",
248 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
252 gridLineColor
: "rgb(128,128,128)",
254 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
255 animatedZooms
: false, // (for now)
257 // Range selector options
258 showRangeSelector
: false,
259 rangeSelectorHeight
: 40,
260 rangeSelectorPlotStrokeColor
: "#808FAB",
261 rangeSelectorPlotFillColor
: "#A7B1C4",
267 axisLabelFormatter
: Dygraph
.dateAxisFormatter
,
268 valueFormatter
: Dygraph
.dateString_
,
269 ticker
: null // will be set in dygraph-tickers.js
273 valueFormatter
: Dygraph
.numberValueFormatter
,
274 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
275 ticker
: null // will be set in dygraph-tickers.js
279 valueFormatter
: Dygraph
.numberValueFormatter
,
280 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
281 ticker
: null // will be set in dygraph-tickers.js
286 // Directions for panning and zooming. Use bit operations when combined
287 // values are possible.
288 Dygraph
.HORIZONTAL
= 1;
289 Dygraph
.VERTICAL
= 2;
291 // Used for initializing annotation CSS rules only once.
292 Dygraph
.addedAnnotationCSS
= false;
294 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
295 // Labels is no longer a constructor parameter, since it's typically set
296 // directly from the data source. It also conains a name for the x-axis,
297 // which the previous constructor form did not.
298 if (labels
!== null) {
299 var new_labels
= ["Date"];
300 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
301 Dygraph
.update(attrs
, { 'labels': new_labels
});
303 this.__init__(div
, file
, attrs
);
307 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
308 * and context <canvas> inside of it. See the constructor for details.
310 * @param {Element} div the Element to render the graph into.
311 * @param {String | Function} file Source data
312 * @param {Object} attrs Miscellaneous other options
315 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
316 // Hack for IE: if we're using excanvas and the document hasn't finished
317 // loading yet (and hence may not have initialized whatever it needs to
318 // initialize), then keep calling this routine periodically until it has.
319 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
320 typeof(G_vmlCanvasManager
) != 'undefined' &&
321 document
.readyState
!= 'complete') {
323 setTimeout(function() { self
.__init__(div
, file
, attrs
); }, 100);
327 // Support two-argument constructor
328 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
330 attrs
= Dygraph
.mapLegacyOptions_(attrs
);
333 Dygraph
.error("Constructing dygraph with a non-existent div!");
337 this.isUsingExcanvas_
= typeof(G_vmlCanvasManager
) != 'undefined';
339 // Copy the important bits into the object
340 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
343 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
344 this.previousVerticalX_
= -1;
345 this.fractions_
= attrs
.fractions
|| false;
346 this.dateWindow_
= attrs
.dateWindow
|| null;
348 this.is_initial_draw_
= true;
349 this.annotations_
= [];
351 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
352 this.zoomed_x_
= false;
353 this.zoomed_y_
= false;
355 // Clear the div. This ensure that, if multiple dygraphs are passed the same
356 // div, then only one will be drawn.
359 // For historical reasons, the 'width' and 'height' options trump all CSS
360 // rules _except_ for an explicit 'width' or 'height' on the div.
361 // As an added convenience, if the div has zero height (like <div></div> does
362 // without any styles), then we use a default height/width
.
363 if (div
.style
.width
=== '' && attrs
.width
) {
364 div
.style
.width
= attrs
.width
+ "px";
366 if (div
.style
.height
=== '' && attrs
.height
) {
367 div
.style
.height
= attrs
.height
+ "px";
369 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
370 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
371 if (div
.style
.width
=== '') {
372 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
375 // these will be zero if the dygraph's div is hidden.
376 this.width_
= div
.clientWidth
;
377 this.height_
= div
.clientHeight
;
379 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
380 if (attrs
.stackedGraph
) {
381 attrs
.fillGraph
= true;
382 // TODO(nikhilk): Add any other stackedGraph checks here.
385 // Dygraphs has many options, some of which interact with one another.
386 // To keep track of everything, we maintain two sets of options:
388 // this.user_attrs_ only options explicitly set by the user.
389 // this.attrs_ defaults, options derived from user_attrs_, data.
391 // Options are then accessed this.attr_('attr'), which first looks at
392 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
393 // defaults without overriding behavior that the user specifically asks for.
394 this.user_attrs_
= {};
395 Dygraph
.update(this.user_attrs_
, attrs
);
397 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
399 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
401 this.boundaryIds_
= [];
402 this.setIndexByName_
= {};
403 this.datasetIndex_
= [];
405 // Create the containing DIV and other interactive elements
406 this.createInterface_();
412 * Returns the zoomed status of the chart for one or both axes.
414 * Axis is an optional parameter. Can be set to 'x' or 'y'.
416 * The zoomed status for an axis is set whenever a user zooms using the mouse
417 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
418 * option is also specified).
420 Dygraph
.prototype.isZoomed
= function(axis
) {
421 if (axis
== null) return this.zoomed_x_
|| this.zoomed_y_
;
422 if (axis
=== 'x') return this.zoomed_x_
;
423 if (axis
=== 'y') return this.zoomed_y_
;
424 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
428 * Returns information about the Dygraph object, including its containing ID.
430 Dygraph
.prototype.toString
= function() {
431 var maindiv
= this.maindiv_
;
432 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
433 return "[Dygraph " + id
+ "]";
438 * Returns the value of an option. This may be set by the user (either in the
439 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
441 * @param { String } name The name of the option, e.g. 'rollPeriod'.
442 * @param { String } [seriesName] The name of the series to which the option
443 * will be applied. If no per-series value of this option is available, then
444 * the global value is returned. This is optional.
445 * @return { ... } The value of the option.
447 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
448 // <REMOVE_FOR_COMBINED>
449 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
450 this.error('Must include options reference JS for testing');
451 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
452 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
453 'in the Dygraphs.OPTIONS_REFERENCE listing.');
454 // Only log this error once.
455 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
457 // </REMOVE_FOR_COMBINED
>
460 sources
.push(this.attrs_
);
461 if (this.user_attrs_
) {
462 sources
.push(this.user_attrs_
);
464 if (this.user_attrs_
.hasOwnProperty(seriesName
)) {
465 sources
.push(this.user_attrs_
[seriesName
]);
467 if (seriesName
=== this.highlightSet_
&&
468 this.user_attrs_
.hasOwnProperty('highlightSeriesOpts')) {
469 sources
.push(this.user_attrs_
['highlightSeriesOpts']);
475 for (var i
= sources
.length
- 1; i
>= 0; --i
) {
476 var source
= sources
[i
];
477 if (source
.hasOwnProperty(name
)) {
487 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
488 * @return { ... } A function mapping string -> option value
490 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
492 return function(opt
) {
493 var axis_opts
= self
.user_attrs_
.axes
;
494 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
495 return axis_opts
[axis
][opt
];
497 // user-specified attributes always trump defaults, even if they're less
499 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
500 return self
.user_attrs_
[opt
];
503 axis_opts
= self
.attrs_
.axes
;
504 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
505 return axis_opts
[axis
][opt
];
507 // check old-style axis options
508 // TODO(danvk): add a deprecation warning if either of these match.
509 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
510 return self
.axes_
[0][opt
];
511 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
512 return self
.axes_
[1][opt
];
514 return self
.attr_(opt
);
519 * Returns the current rolling period, as set by the user or an option.
520 * @return {Number} The number of points in the rolling window
522 Dygraph
.prototype.rollPeriod
= function() {
523 return this.rollPeriod_
;
527 * Returns the currently-visible x-range. This can be affected by zooming,
528 * panning or a call to updateOptions.
529 * Returns a two-element array: [left, right].
530 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
532 Dygraph
.prototype.xAxisRange
= function() {
533 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
537 * Returns the lower- and upper-bound x-axis values of the
540 Dygraph
.prototype.xAxisExtremes
= function() {
541 var left
= this.rawData_
[0][0];
542 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
543 return [left
, right
];
547 * Returns the currently-visible y-range for an axis. This can be affected by
548 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
549 * called with no arguments, returns the range of the first axis.
550 * Returns a two-element array: [bottom, top].
552 Dygraph
.prototype.yAxisRange
= function(idx
) {
553 if (typeof(idx
) == "undefined") idx
= 0;
554 if (idx
< 0 || idx
>= this.axes_
.length
) {
557 var axis
= this.axes_
[idx
];
558 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
562 * Returns the currently-visible y-ranges for each axis. This can be affected by
563 * zooming, panning, calls to updateOptions, etc.
564 * Returns an array of [bottom, top] pairs, one for each y-axis.
566 Dygraph
.prototype.yAxisRanges
= function() {
568 for (var i
= 0; i
< this.axes_
.length
; i
++) {
569 ret
.push(this.yAxisRange(i
));
574 // TODO(danvk): use these functions throughout dygraphs.
576 * Convert from data coordinates to canvas/div X/Y coordinates.
577 * If specified, do this conversion for the coordinate system of a particular
578 * axis. Uses the first axis by default.
579 * Returns a two-element array: [X, Y]
581 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
582 * instead of toDomCoords(null, y, axis).
584 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
585 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
589 * Convert from data x coordinates to canvas/div X coordinate.
590 * If specified, do this conversion for the coordinate system of a particular
592 * Returns a single value or null if x is null.
594 Dygraph
.prototype.toDomXCoord
= function(x
) {
599 var area
= this.plotter_
.area
;
600 var xRange
= this.xAxisRange();
601 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
605 * Convert from data x coordinates to canvas/div Y coordinate and optional
606 * axis. Uses the first axis by default.
608 * returns a single value or null if y is null.
610 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
611 var pct
= this.toPercentYCoord(y
, axis
);
616 var area
= this.plotter_
.area
;
617 return area
.y
+ pct
* area
.h
;
621 * Convert from canvas/div coords to data coordinates.
622 * If specified, do this conversion for the coordinate system of a particular
623 * axis. Uses the first axis by default.
624 * Returns a two-element array: [X, Y].
626 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
627 * instead of toDataCoords(null, y, axis).
629 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
630 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
634 * Convert from canvas/div x coordinate to data coordinate.
636 * If x is null, this returns null.
638 Dygraph
.prototype.toDataXCoord
= function(x
) {
643 var area
= this.plotter_
.area
;
644 var xRange
= this.xAxisRange();
645 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
649 * Convert from canvas/div y coord to value.
651 * If y is null, this returns null.
652 * if axis is null, this uses the first axis.
654 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
659 var area
= this.plotter_
.area
;
660 var yRange
= this.yAxisRange(axis
);
662 if (typeof(axis
) == "undefined") axis
= 0;
663 if (!this.axes_
[axis
].logscale
) {
664 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
666 // Computing the inverse of toDomCoord.
667 var pct
= (y
- area
.y
) / area
.h
;
669 // Computing the inverse of toPercentYCoord. The function was arrived at with
670 // the following steps:
672 // Original calcuation:
673 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
675 // Move denominator to both sides:
676 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
678 // subtract logr1, and take the negative value.
679 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
681 // Swap both sides of the equation, and we can compute the log of the
682 // return value. Which means we just need to use that as the exponent in
684 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
686 var logr1
= Dygraph
.log10(yRange
[1]);
687 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
688 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
694 * Converts a y for an axis to a percentage from the top to the
695 * bottom of the drawing area.
697 * If the coordinate represents a value visible on the canvas, then
698 * the value will be between 0 and 1, where 0 is the top of the canvas.
699 * However, this method will return values outside the range, as
700 * values can fall outside the canvas.
702 * If y is null, this returns null.
703 * if axis is null, this uses the first axis.
705 * @param { Number } y The data y-coordinate.
706 * @param { Number } [axis] The axis number on which the data coordinate lives.
707 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
709 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
713 if (typeof(axis
) == "undefined") axis
= 0;
715 var yRange
= this.yAxisRange(axis
);
718 if (!this.axes_
[axis
].logscale
) {
719 // yRange[1] - y is unit distance from the bottom.
720 // yRange[1] - yRange[0] is the scale of the range.
721 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
722 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
724 var logr1
= Dygraph
.log10(yRange
[1]);
725 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
731 * Converts an x value to a percentage from the left to the right of
734 * If the coordinate represents a value visible on the canvas, then
735 * the value will be between 0 and 1, where 0 is the left of the canvas.
736 * However, this method will return values outside the range, as
737 * values can fall outside the canvas.
739 * If x is null, this returns null.
740 * @param { Number } x The data x-coordinate.
741 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
743 Dygraph
.prototype.toPercentXCoord
= function(x
) {
748 var xRange
= this.xAxisRange();
749 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
753 * Returns the number of columns (including the independent variable).
754 * @return { Integer } The number of columns.
756 Dygraph
.prototype.numColumns
= function() {
757 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
761 * Returns the number of rows (excluding any header/label row).
762 * @return { Integer } The number of rows, less any header.
764 Dygraph
.prototype.numRows
= function() {
765 return this.rawData_
.length
;
769 * Returns the full range of the x-axis, as determined by the most extreme
770 * values in the data set. Not affected by zooming, visibility, etc.
771 * TODO(danvk): merge w/ xAxisExtremes
772 * @return { Array<Number> } A [low, high] pair
775 Dygraph
.prototype.fullXRange_
= function() {
776 if (this.numRows() > 0) {
777 return [this.rawData_
[0][0], this.rawData_
[this.numRows() - 1][0]];
784 * Returns the value in the given row and column. If the row and column exceed
785 * the bounds on the data, returns null. Also returns null if the value is
787 * @param { Number} row The row number of the data (0-based). Row 0 is the
788 * first row of data, not a header row.
789 * @param { Number} col The column number of the data (0-based)
790 * @return { Number } The value in the specified cell or null if the row/col
793 Dygraph
.prototype.getValue
= function(row
, col
) {
794 if (row
< 0 || row
> this.rawData_
.length
) return null;
795 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
797 return this.rawData_
[row
][col
];
801 * Generates interface elements for the Dygraph: a containing div, a div to
802 * display the current point, and a textbox to adjust the rolling average
803 * period. Also creates the Renderer/Layout elements.
806 Dygraph
.prototype.createInterface_
= function() {
807 // Create the all-enclosing graph div
808 var enclosing
= this.maindiv_
;
810 this.graphDiv
= document
.createElement("div");
811 this.graphDiv
.style
.width
= this.width_
+ "px";
812 this.graphDiv
.style
.height
= this.height_
+ "px";
813 enclosing
.appendChild(this.graphDiv
);
815 // Create the canvas for interactive parts of the chart.
816 this.canvas_
= Dygraph
.createCanvas();
817 this.canvas_
.style
.position
= "absolute";
818 this.canvas_
.width
= this.width_
;
819 this.canvas_
.height
= this.height_
;
820 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
821 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
823 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
825 // ... and for static parts of the chart.
826 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
827 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
829 if (this.attr_('showRangeSelector')) {
830 // The range selector must be created here so that its canvases and contexts get created here.
831 // For some reason, if the canvases and contexts don't get created here, things don't work in IE.
832 // The range selector also sets xAxisHeight in order to reserve space.
833 this.rangeSelector_
= new DygraphRangeSelector(this);
836 // The interactive parts of the graph are drawn on top of the chart.
837 this.graphDiv
.appendChild(this.hidden_
);
838 this.graphDiv
.appendChild(this.canvas_
);
839 this.mouseEventElement_
= this.createMouseEventElement_();
841 // Create the grapher
842 this.layout_
= new DygraphLayout(this);
844 if (this.rangeSelector_
) {
845 // This needs to happen after the graph canvases are added to the div and the layout object is created.
846 this.rangeSelector_
.addToGraph(this.graphDiv
, this.layout_
);
851 this.mouseMoveHandler
= function(e
) {
852 dygraph
.mouseMove_(e
);
854 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler
);
856 this.mouseOutHandler
= function(e
) {
857 dygraph
.mouseOut_(e
);
859 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', this.mouseOutHandler
);
861 this.createStatusMessage_();
862 this.createDragInterface_();
864 this.resizeHandler
= function(e
) {
868 // Update when the window is resized.
869 // TODO(danvk): drop frames depending on complexity of the chart.
870 Dygraph
.addEvent(window
, 'resize', this.resizeHandler
);
874 * Detach DOM elements in the dygraph and null out all data references.
875 * Calling this when you're done with a dygraph can dramatically reduce memory
876 * usage. See, e.g., the tests/perf.html example.
878 Dygraph
.prototype.destroy
= function() {
879 var removeRecursive
= function(node
) {
880 while (node
.hasChildNodes()) {
881 removeRecursive(node
.firstChild
);
882 node
.removeChild(node
.firstChild
);
886 // remove mouse event handlers
887 Dygraph
.removeEvent(this.mouseEventElement_
, 'mouseout', this.mouseOutHandler
);
888 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler
);
889 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseUpHandler_
);
890 removeRecursive(this.maindiv_
);
892 var nullOut
= function(obj
) {
894 if (typeof(obj
[n
]) === 'object') {
899 // remove event handlers
900 Dygraph
.removeEvent(window
,'resize',this.resizeHandler
);
901 this.resizeHandler
= null;
902 // These may not all be necessary, but it can't hurt...
903 nullOut(this.layout_
);
904 nullOut(this.plotter_
);
909 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
910 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
911 * or the zoom rectangles) is done on this.canvas_.
912 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
913 * @return {Object} The newly-created canvas
916 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
917 var h
= Dygraph
.createCanvas();
918 h
.style
.position
= "absolute";
919 // TODO(danvk): h should be offset from canvas. canvas needs to include
920 // some extra area to make it easier to zoom in on the far left and far
921 // right. h needs to be precisely the plot area, so that clipping occurs.
922 h
.style
.top
= canvas
.style
.top
;
923 h
.style
.left
= canvas
.style
.left
;
924 h
.width
= this.width_
;
925 h
.height
= this.height_
;
926 h
.style
.width
= this.width_
+ "px"; // for IE
927 h
.style
.height
= this.height_
+ "px"; // for IE
932 * Creates an overlay element used to handle mouse events.
933 * @return {Object} The mouse event element.
936 Dygraph
.prototype.createMouseEventElement_
= function() {
937 if (this.isUsingExcanvas_
) {
938 var elem
= document
.createElement("div");
939 elem
.style
.position
= 'absolute';
940 elem
.style
.backgroundColor
= 'white';
941 elem
.style
.filter
= 'alpha(opacity=0)';
942 elem
.style
.width
= this.width_
+ "px";
943 elem
.style
.height
= this.height_
+ "px";
944 this.graphDiv
.appendChild(elem
);
952 * Generate a set of distinct colors for the data series. This is done with a
953 * color wheel. Saturation/Value are customizable, and the hue is
954 * equally-spaced around the color wheel. If a custom set of colors is
955 * specified, that is used instead.
958 Dygraph
.prototype.setColors_
= function() {
959 var num
= this.attr_("labels").length
- 1;
961 var colors
= this.attr_('colors');
964 var sat
= this.attr_('colorSaturation') || 1.0;
965 var val
= this.attr_('colorValue') || 0.5;
966 var half
= Math
.ceil(num
/ 2);
967 for (i
= 1; i
<= num
; i
++) {
968 if (!this.visibility()[i
-1]) continue;
969 // alternate colors for high contrast.
970 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
971 var hue
= (1.0 * idx
/ (1 + num
));
972 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
975 for (i
= 0; i
< num
; i
++) {
976 if (!this.visibility()[i
]) continue;
977 var colorStr
= colors
[i
% colors
.length
];
978 this.colors_
.push(colorStr
);
982 this.plotter_
.setColors(this.colors_
);
986 * Return the list of colors. This is either the list of colors passed in the
987 * attributes or the autogenerated list of rgb(r,g,b) strings.
988 * @return {Array<string>} The list of colors.
990 Dygraph
.prototype.getColors
= function() {
995 * Create the div that contains information on the selected point(s)
996 * This goes in the top right of the canvas, unless an external div has already
1000 Dygraph
.prototype.createStatusMessage_
= function() {
1001 var userLabelsDiv
= this.user_attrs_
.labelsDiv
;
1002 if (userLabelsDiv
&& null !== userLabelsDiv
&&
1003 (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
)) {
1004 this.user_attrs_
.labelsDiv
= document
.getElementById(userLabelsDiv
);
1006 if (!this.attr_("labelsDiv")) {
1007 var divWidth
= this.attr_('labelsDivWidth');
1008 var messagestyle
= {
1009 "position": "absolute",
1012 "width": divWidth
+ "px",
1014 "left": (this.width_
- divWidth
- 2) + "px",
1015 "background": "white",
1016 "lineHeight": "normal",
1017 "textAlign": "left",
1018 "overflow": "hidden"};
1019 Dygraph
.update(messagestyle
, this.attr_('labelsDivStyles'));
1020 var div
= document
.createElement("div");
1021 div
.className
= "dygraph-legend";
1022 for (var name
in messagestyle
) {
1023 if (messagestyle
.hasOwnProperty(name
)) {
1025 div
.style
[name
] = messagestyle
[name
];
1027 this.warn("You are using unsupported css properties for your browser in labelsDivStyles");
1031 this.graphDiv
.appendChild(div
);
1032 this.attrs_
.labelsDiv
= div
;
1037 * Position the labels div so that:
1038 * - its right edge is flush with the right edge of the charting area
1039 * - its top edge is flush with the top edge of the charting area
1042 Dygraph
.prototype.positionLabelsDiv_
= function() {
1043 // Don't touch a user-specified labelsDiv.
1044 if (this.user_attrs_
.hasOwnProperty("labelsDiv")) return;
1046 var area
= this.plotter_
.area
;
1047 var div
= this.attr_("labelsDiv");
1048 div
.style
.left
= area
.x
+ area
.w
- this.attr_("labelsDivWidth") - 1 + "px";
1049 div
.style
.top
= area
.y
+ "px";
1053 * Create the text box to adjust the averaging period
1056 Dygraph
.prototype.createRollInterface_
= function() {
1057 // Create a roller if one doesn't exist already.
1058 if (!this.roller_
) {
1059 this.roller_
= document
.createElement("input");
1060 this.roller_
.type
= "text";
1061 this.roller_
.style
.display
= "none";
1062 this.graphDiv
.appendChild(this.roller_
);
1065 var display
= this.attr_('showRoller') ? 'block' : 'none';
1067 var area
= this.plotter_
.area
;
1068 var textAttr
= { "position": "absolute",
1070 "top": (area
.y
+ area
.h
- 25) + "px",
1071 "left": (area
.x
+ 1) + "px",
1074 this.roller_
.size
= "2";
1075 this.roller_
.value
= this.rollPeriod_
;
1076 for (var name
in textAttr
) {
1077 if (textAttr
.hasOwnProperty(name
)) {
1078 this.roller_
.style
[name
] = textAttr
[name
];
1083 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1088 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1089 * canvas (i.e. DOM Coords).
1091 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1092 return Dygraph
.pageX(e
) - context
.px
;
1097 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1098 * canvas (i.e. DOM Coords).
1100 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1101 return Dygraph
.pageY(e
) - context
.py
;
1105 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1109 Dygraph
.prototype.createDragInterface_
= function() {
1111 // Tracks whether the mouse is down right now
1113 isPanning
: false, // is this drag part of a pan?
1114 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1115 dragStartX
: null, // pixel coordinates
1116 dragStartY
: null, // pixel coordinates
1117 dragEndX
: null, // pixel coordinates
1118 dragEndY
: null, // pixel coordinates
1119 dragDirection
: null,
1120 prevEndX
: null, // pixel coordinates
1121 prevEndY
: null, // pixel coordinates
1122 prevDragDirection
: null,
1123 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1125 // The value on the left side of the graph when a pan operation starts.
1126 initialLeftmostDate
: null,
1128 // The number of units each pixel spans. (This won't be valid for log
1130 xUnitsPerPixel
: null,
1132 // TODO(danvk): update this comment
1133 // The range in second/value units that the viewport encompasses during a
1134 // panning operation.
1137 // Top-left corner of the canvas, in DOM coords
1138 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1142 // Values for use with panEdgeFraction, which limit how far outside the
1143 // graph's data boundaries it can be panned.
1144 boundedDates
: null, // [minDate, maxDate]
1145 boundedValues
: null, // [[minValue, maxValue] ...]
1147 initializeMouseDown
: function(event
, g
, context
) {
1148 // prevents mouse drags from selecting page text.
1149 if (event
.preventDefault
) {
1150 event
.preventDefault(); // Firefox, Chrome, etc.
1152 event
.returnValue
= false; // IE
1153 event
.cancelBubble
= true;
1156 context
.px
= Dygraph
.findPosX(g
.canvas_
);
1157 context
.py
= Dygraph
.findPosY(g
.canvas_
);
1158 context
.dragStartX
= g
.dragGetX_(event
, context
);
1159 context
.dragStartY
= g
.dragGetY_(event
, context
);
1160 context
.cancelNextDblclick
= false;
1164 var interactionModel
= this.attr_("interactionModel");
1166 // Self is the graph.
1169 // Function that binds the graph and context to the handler.
1170 var bindHandler
= function(handler
) {
1171 return function(event
) {
1172 handler(event
, self
, context
);
1176 for (var eventName
in interactionModel
) {
1177 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1178 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
1179 bindHandler(interactionModel
[eventName
]));
1182 // If the user releases the mouse button during a drag, but not over the
1183 // canvas, then it doesn't count as a zooming action.
1184 this.mouseUpHandler_
= function(event
) {
1185 if (context
.isZooming
|| context
.isPanning
) {
1186 context
.isZooming
= false;
1187 context
.dragStartX
= null;
1188 context
.dragStartY
= null;
1191 if (context
.isPanning
) {
1192 context
.isPanning
= false;
1193 context
.draggingDate
= null;
1194 context
.dateRange
= null;
1195 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1196 delete self
.axes_
[i
].draggingValue
;
1197 delete self
.axes_
[i
].dragValueRange
;
1202 Dygraph
.addEvent(document
, 'mouseup', this.mouseUpHandler_
);
1206 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1207 * up any previous zoom rectangles that were drawn. This could be optimized to
1208 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1211 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1212 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1213 * @param {Number} startX The X position where the drag started, in canvas
1215 * @param {Number} endX The current X position of the drag, in canvas coords.
1216 * @param {Number} startY The Y position where the drag started, in canvas
1218 * @param {Number} endY The current Y position of the drag, in canvas coords.
1219 * @param {Number} prevDirection the value of direction on the previous call to
1220 * this function. Used to avoid excess redrawing
1221 * @param {Number} prevEndX The value of endX on the previous call to this
1222 * function. Used to avoid excess redrawing
1223 * @param {Number} prevEndY The value of endY on the previous call to this
1224 * function. Used to avoid excess redrawing
1227 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1228 endY
, prevDirection
, prevEndX
,
1230 var ctx
= this.canvas_ctx_
;
1232 // Clean up from the previous rect if necessary
1233 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1234 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1235 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1236 } else if (prevDirection
== Dygraph
.VERTICAL
){
1237 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1238 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1241 // Draw a light-grey rectangle to show the new viewing area
1242 if (direction
== Dygraph
.HORIZONTAL
) {
1243 if (endX
&& startX
) {
1244 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1245 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1246 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1248 } else if (direction
== Dygraph
.VERTICAL
) {
1249 if (endY
&& startY
) {
1250 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1251 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1252 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1256 if (this.isUsingExcanvas_
) {
1257 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1262 * Clear the zoom rectangle (and perform no zoom).
1265 Dygraph
.prototype.clearZoomRect_
= function() {
1266 this.currentZoomRectArgs_
= null;
1267 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1271 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1272 * the canvas. The exact zoom window may be slightly larger if there are no data
1273 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1274 * which accepts dates that match the raw data. This function redraws the graph.
1276 * @param {Number} lowX The leftmost pixel value that should be visible.
1277 * @param {Number} highX The rightmost pixel value that should be visible.
1280 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1281 this.currentZoomRectArgs_
= null;
1282 // Find the earliest and latest dates contained in this canvasx range.
1283 // Convert the call to date ranges of the raw data.
1284 var minDate
= this.toDataXCoord(lowX
);
1285 var maxDate
= this.toDataXCoord(highX
);
1286 this.doZoomXDates_(minDate
, maxDate
);
1290 * Transition function to use in animations. Returns values between 0.0
1291 * (totally old values) and 1.0 (totally new values) for each frame.
1294 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1296 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1300 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1301 * method with doZoomX which accepts pixel coordinates. This function redraws
1304 * @param {Number} minDate The minimum date that should be visible.
1305 * @param {Number} maxDate The maximum date that should be visible.
1308 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1309 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1310 // can produce strange effects. Rather than the y-axis transitioning slowly
1311 // between values, it can jerk around.)
1312 var old_window
= this.xAxisRange();
1313 var new_window
= [minDate
, maxDate
];
1314 this.zoomed_x_
= true;
1316 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1317 if (that
.attr_("zoomCallback")) {
1318 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1324 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1325 * the canvas. This function redraws the graph.
1327 * @param {Number} lowY The topmost pixel value that should be visible.
1328 * @param {Number} highY The lowest pixel value that should be visible.
1331 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1332 this.currentZoomRectArgs_
= null;
1333 // Find the highest and lowest values in pixel range for each axis.
1334 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1335 // This is because pixels increase as you go down on the screen, whereas data
1336 // coordinates increase as you go up the screen.
1337 var oldValueRanges
= this.yAxisRanges();
1338 var newValueRanges
= [];
1339 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1340 var hi
= this.toDataYCoord(lowY
, i
);
1341 var low
= this.toDataYCoord(highY
, i
);
1342 newValueRanges
.push([low
, hi
]);
1345 this.zoomed_y_
= true;
1347 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1348 if (that
.attr_("zoomCallback")) {
1349 var xRange
= that
.xAxisRange();
1350 that
.attr_("zoomCallback")(xRange
[0], xRange
[1], that
.yAxisRanges());
1356 * Reset the zoom to the original view coordinates. This is the same as
1357 * double-clicking on the graph.
1361 Dygraph
.prototype.doUnzoom_
= function() {
1362 var dirty
= false, dirtyX
= false, dirtyY
= false;
1363 if (this.dateWindow_
!== null) {
1368 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1369 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1375 // Clear any selection, since it's likely to be drawn in the wrong place.
1376 this.clearSelection();
1379 this.zoomed_x_
= false;
1380 this.zoomed_y_
= false;
1382 var minDate
= this.rawData_
[0][0];
1383 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1385 // With only one frame, don't bother calculating extreme ranges.
1386 // TODO(danvk): merge this block w/ the code below
.
1387 if (!this.attr_("animatedZooms")) {
1388 this.dateWindow_
= null;
1389 for (i
= 0; i
< this.axes_
.length
; i
++) {
1390 if (this.axes_
[i
].valueWindow
!== null) {
1391 delete this.axes_
[i
].valueWindow
;
1395 if (this.attr_("zoomCallback")) {
1396 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1401 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1403 oldWindow
= this.xAxisRange();
1404 newWindow
= [minDate
, maxDate
];
1408 oldValueRanges
= this.yAxisRanges();
1409 // TODO(danvk): this is pretty inefficient
1410 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1411 var extremes
= packed
[1];
1413 // this has the side-effect of modifying this.axes_.
1414 // this doesn't make much sense in this context, but it's convenient (we
1415 // need this.axes_[*].extremeValues) and not harmful since we'll be
1416 // calling drawGraph_ shortly, which clobbers these values.
1417 this.computeYAxisRanges_(extremes
);
1419 newValueRanges
= [];
1420 for (i
= 0; i
< this.axes_
.length
; i
++) {
1421 var axis
= this.axes_
[i
];
1422 newValueRanges
.push(axis
.valueRange
!= null ? axis
.valueRange
: axis
.extremeRange
);
1427 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1429 that
.dateWindow_
= null;
1430 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1431 if (that
.axes_
[i
].valueWindow
!== null) {
1432 delete that
.axes_
[i
].valueWindow
;
1435 if (that
.attr_("zoomCallback")) {
1436 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1443 * Combined animation logic for all zoom functions.
1444 * either the x parameters or y parameters may be null.
1447 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1448 var steps
= this.attr_("animatedZooms") ? Dygraph
.ANIMATION_STEPS
: 1;
1451 var valueRanges
= [];
1454 if (oldXRange
!== null && newXRange
!== null) {
1455 for (step
= 1; step
<= steps
; step
++) {
1456 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1457 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1458 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1462 if (oldYRanges
!== null && newYRanges
!== null) {
1463 for (step
= 1; step
<= steps
; step
++) {
1464 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1466 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1467 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1468 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1470 valueRanges
[step
-1] = thisRange
;
1475 Dygraph
.repeatAndCleanup(function(step
) {
1476 if (valueRanges
.length
) {
1477 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1478 var w
= valueRanges
[step
][i
];
1479 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1482 if (windows
.length
) {
1483 that
.dateWindow_
= windows
[step
];
1486 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1490 * Get the current graph's area object.
1492 * Returns: {x, y, w, h}
1494 Dygraph
.prototype.getArea
= function() {
1495 return this.plotter_
.area
;
1499 * Convert a mouse event to DOM coordinates relative to the graph origin.
1501 * Returns a two-element array: [X, Y].
1503 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1504 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1505 var canvasy
= Dygraph
.pageY(event
) - Dygraph
.findPosY(this.mouseEventElement_
);
1506 return [canvasx
, canvasy
];
1510 * Given a canvas X coordinate, find the closest row.
1511 * @param {Number} domX graph-relative DOM X coordinate
1512 * Returns: row number, integer
1515 Dygraph
.prototype.findClosestRow
= function(domX
) {
1516 var minDistX
= Infinity
;
1518 var points
= this.layout_
.points
;
1519 var l
= points
.length
;
1520 for (var i
= 0; i
< l
; i
++) {
1521 var point
= points
[i
];
1522 if (!Dygraph
.isValidPoint(point
, true)) continue;
1523 var dist
= Math
.abs(point
.canvasx
- domX
);
1524 if (dist
< minDistX
) {
1529 return this.idxToRow_(idx
);
1533 * Given canvas X,Y coordinates, find the closest point.
1535 * This finds the individual data point across all visible series
1536 * that's closest to the supplied DOM coordinates using the standard
1537 * Euclidean X,Y distance.
1539 * @param {Number} domX graph-relative DOM X coordinate
1540 * @param {Number} domY graph-relative DOM Y coordinate
1541 * Returns: {row, seriesName, point}
1544 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1545 var minDist
= Infinity
;
1547 var points
= this.layout_
.points
;
1548 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
;
1549 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1550 var first
= this.layout_
.setPointsOffsets
[setIdx
];
1551 var len
= this.layout_
.setPointsLengths
[setIdx
];
1552 for (var i
= 0; i
< len
; ++i
) {
1553 var point
= points
[first
+ i
];
1554 if (!Dygraph
.isValidPoint(point
)) continue;
1555 dx
= point
.canvasx
- domX
;
1556 dy
= point
.canvasy
- domY
;
1557 dist
= dx
* dx
+ dy
* dy
;
1558 if (dist
< minDist
) {
1560 closestPoint
= point
;
1561 closestSeries
= setIdx
;
1566 var name
= this.layout_
.setNames
[closestSeries
];
1568 row
: idx
+ this.getLeftBoundary_(),
1575 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1577 * This first finds the X data point closest to the supplied DOM X coordinate,
1578 * then finds the series which puts the Y coordinate on top of its filled area,
1579 * using linear interpolation between adjacent point pairs.
1581 * @param {Number} domX graph-relative DOM X coordinate
1582 * @param {Number} domY graph-relative DOM Y coordinate
1583 * Returns: {row, seriesName, point}
1586 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1587 var row
= this.findClosestRow(domX
);
1588 var boundary
= this.getLeftBoundary_();
1589 var rowIdx
= row
- boundary
;
1590 var points
= this.layout_
.points
;
1591 var closestPoint
, closestSeries
;
1592 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1593 var first
= this.layout_
.setPointsOffsets
[setIdx
];
1594 var len
= this.layout_
.setPointsLengths
[setIdx
];
1595 if (rowIdx
>= len
) continue;
1596 var p1
= points
[first
+ rowIdx
];
1597 if (!Dygraph
.isValidPoint(p1
)) continue;
1598 var py
= p1
.canvasy
;
1599 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < len
) {
1600 // interpolate series Y value using next point
1601 var p2
= points
[first
+ rowIdx
+ 1];
1602 if (Dygraph
.isValidPoint(p2
)) {
1603 var dx
= p2
.canvasx
- p1
.canvasx
;
1605 var r
= (domX
- p1
.canvasx
) / dx
;
1606 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1609 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1610 // interpolate series Y value using previous point
1611 var p0
= points
[first
+ rowIdx
- 1];
1612 if (Dygraph
.isValidPoint(p0
)) {
1613 var dx
= p1
.canvasx
- p0
.canvasx
;
1615 var r
= (p1
.canvasx
- domX
) / dx
;
1616 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1620 // Stop if the point (domX, py) is above this series' upper edge
1621 if (setIdx
== 0 || py
< domY
) {
1623 closestSeries
= setIdx
;
1626 var name
= this.layout_
.setNames
[closestSeries
];
1635 * When the mouse moves in the canvas, display information about a nearby data
1636 * point and draw dots over those points in the data series. This function
1637 * takes care of cleanup of previously-drawn dots.
1638 * @param {Object} event The mousemove event from the browser.
1641 Dygraph
.prototype.mouseMove_
= function(event
) {
1642 // This prevents JS errors when mousing over the canvas before data loads.
1643 var points
= this.layout_
.points
;
1644 if (points
=== undefined
) return;
1646 var canvasCoords
= this.eventToDomCoords(event
);
1647 var canvasx
= canvasCoords
[0];
1648 var canvasy
= canvasCoords
[1];
1650 var highlightSeriesOpts
= this.attr_("highlightSeriesOpts");
1651 var selectionChanged
= false;
1652 if (highlightSeriesOpts
) {
1654 if (this.attr_("stackedGraph")) {
1655 closest
= this.findStackedPoint(canvasx
, canvasy
);
1657 closest
= this.findClosestPoint(canvasx
, canvasy
);
1659 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1661 var idx
= this.findClosestRow(canvasx
);
1662 selectionChanged
= this.setSelection(idx
);
1665 var callback
= this.attr_("highlightCallback");
1666 if (callback
&& selectionChanged
) {
1667 callback(event
, this.lastx_
, this.selPoints_
, this.lastRow_
, this.highlightSet_
);
1672 * Fetch left offset from first defined boundaryIds record (see bug #236).
1674 Dygraph
.prototype.getLeftBoundary_
= function() {
1675 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1676 if (this.boundaryIds_
[i
] !== undefined
) {
1677 return this.boundaryIds_
[i
][0];
1684 * Transforms layout_.points index into data row number.
1685 * @param int layout_.points index
1686 * @return int row number, or -1 if none could be found.
1689 Dygraph
.prototype.idxToRow_
= function(idx
) {
1690 if (idx
< 0) return -1;
1692 var boundary
= this.getLeftBoundary_();
1693 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1694 var set
= this.layout_
.datasets
[setIdx
];
1695 if (idx
< set
.length
) {
1696 return boundary
+ idx
;
1705 * Generates legend html dash for any stroke pattern. It will try to scale the
1706 * pattern to fit in 1em width. Or if small enough repeat the partern for 1em
1708 * @param strokePattern The pattern
1709 * @param color The color of the series.
1710 * @param oneEmWidth The width in pixels of 1em in the legend.
1712 Dygraph
.prototype.generateLegendDashHTML_
= function(strokePattern
, color
, oneEmWidth
) {
1714 var i
, j
, paddingLeft
, marginRight
;
1715 var strokePixelLength
= 0, segmentLoop
= 0;
1716 var normalizedPattern
= [];
1718 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
1719 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
1723 if (!strokePattern
|| strokePattern
.length
<= 1) {
1725 dash
= "<div style=\"display: inline-block; position: relative; " +
1726 "bottom: .5ex; padding-left: 1em; height: 1px; " +
1727 "border-bottom: 2px solid " + color
+ ";\"></div>";
1729 // Compute the length of the pixels including the first segment twice,
1730 // since we repeat it.
1731 for (i
= 0; i
<= strokePattern
.length
; i
++) {
1732 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
1735 // See if we can loop the pattern by itself at least twice.
1736 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
1738 // This pattern fits at least two times, no scaling just convert to em;
1739 for (i
= 0; i
< strokePattern
.length
; i
++) {
1740 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
1742 // Since we are repeating the pattern, we don't worry about repeating the
1743 // first segment in one draw.
1744 segmentLoop
= normalizedPattern
.length
;
1746 // If the pattern doesn't fit in the legend we scale it to fit.
1748 for (i
= 0; i
< strokePattern
.length
; i
++) {
1749 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
1751 // For the scaled patterns we do redraw the first segment.
1752 segmentLoop
= normalizedPattern
.length
+1;
1754 // Now make the pattern.
1755 for (j
= 0; j
< loop
; j
++) {
1756 for (i
= 0; i
< segmentLoop
; i
+=2) {
1757 // The padding is the drawn segment.
1758 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
1759 if (i
< strokePattern
.length
) {
1760 // The margin is the space segment.
1761 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
1763 // The repeated first segment has no right margin.
1766 dash
+= "<div style=\"display: inline-block; position: relative; " +
1767 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
1768 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+
1778 * Generates HTML for the legend which is displayed when hovering over the
1779 * chart. If no selected points are specified, a default legend is returned
1780 * (this may just be the empty string).
1781 * @param { Number } [x] The x-value of the selected points.
1782 * @param { [Object] } [sel_points] List of selected points for the given
1783 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1784 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend.
1786 Dygraph
.prototype.generateLegendHTML_
= function(x
, sel_points
, oneEmWidth
) {
1787 // If no points are selected, we display a default legend. Traditionally,
1788 // this has been blank. But a better default would be a conventional legend,
1789 // which provides essential information for a non-interactive chart.
1790 var html
, sepLines
, i
, c
, dash
, strokePattern
;
1791 if (typeof(x
) === 'undefined') {
1792 if (this.attr_('legend') != 'always') return '';
1794 sepLines
= this.attr_('labelsSeparateLines');
1795 var labels
= this.attr_('labels');
1797 for (i
= 1; i
< labels
.length
; i
++) {
1798 if (!this.visibility()[i
- 1]) continue;
1799 c
= this.plotter_
.colors
[labels
[i
]];
1800 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
1801 strokePattern
= this.attr_("strokePattern", labels
[i
]);
1802 dash
= this.generateLegendDashHTML_(strokePattern
, c
, oneEmWidth
);
1803 html
+= "<span style='font-weight: bold; color: " + c
+ ";'>" + dash
+
1804 " " + labels
[i
] + "</span>";
1809 var xOptView
= this.optionsViewForAxis_('x');
1810 var xvf
= xOptView('valueFormatter');
1811 html
= xvf(x
, xOptView
, this.attr_('labels')[0], this) + ":";
1814 var num_axes
= this.numAxes();
1815 for (i
= 0; i
< num_axes
; i
++) {
1816 yOptViews
[i
] = this.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
1818 var showZeros
= this.attr_("labelsShowZeroValues");
1819 sepLines
= this.attr_("labelsSeparateLines");
1820 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1821 var pt
= this.selPoints_
[i
];
1822 if (pt
.yval
=== 0 && !showZeros
) continue;
1823 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1824 if (sepLines
) html
+= "<br/>";
1826 var yOptView
= yOptViews
[this.seriesToAxisMap_
[pt
.name
]];
1827 var fmtFunc
= yOptView('valueFormatter');
1828 c
= this.plotter_
.colors
[pt
.name
];
1829 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, this);
1831 var cls
= (pt
.name
== this.highlightSet_
) ? " class='highlight'" : "";
1832 // TODO(danvk): use a template string here and make it an attribute.
1833 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + c
+ ";'>" + pt
.name
+
1834 "</span></b>:" + yval
+ "</span>";
1841 * Displays information about the selected points in the legend. If there is no
1842 * selection, the legend will be cleared.
1843 * @param { Number } [x] The x-value of the selected points.
1844 * @param { [Object] } [sel_points] List of selected points for the given
1845 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1847 Dygraph
.prototype.setLegendHTML_
= function(x
, sel_points
) {
1848 var labelsDiv
= this.attr_("labelsDiv");
1849 if (!labelsDiv
) return;
1851 var sizeSpan
= document
.createElement('span');
1852 // Calculates the width of 1em in pixels for the legend.
1853 sizeSpan
.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
1854 labelsDiv
.appendChild(sizeSpan
);
1855 var oneEmWidth
=sizeSpan
.offsetWidth
;
1857 var html
= this.generateLegendHTML_(x
, sel_points
, oneEmWidth
);
1858 if (labelsDiv
!== null) {
1859 labelsDiv
.innerHTML
= html
;
1861 if (typeof(this.shown_legend_error_
) == 'undefined') {
1862 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1863 this.shown_legend_error_
= true;
1868 Dygraph
.prototype.animateSelection_
= function(direction
) {
1869 var totalSteps
= 10;
1871 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1872 if (this.animateId
=== undefined
) this.animateId
= 0;
1873 var start
= this.fadeLevel
;
1874 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1876 if (this.fadeLevel
) {
1877 this.updateSelection_(1.0);
1882 var thisId
= ++this.animateId
;
1884 Dygraph
.repeatAndCleanup(
1886 // ignore simultaneous animations
1887 if (that
.animateId
!= thisId
) return;
1889 that
.fadeLevel
+= direction
;
1890 if (that
.fadeLevel
=== 0) {
1891 that
.clearSelection();
1893 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1896 steps
, millis
, function() {});
1900 * Draw dots over the selectied points in the data series. This function
1901 * takes care of cleanup of previously-drawn dots.
1904 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1905 // Clear the previously drawn vertical, if there is one
1907 var ctx
= this.canvas_ctx_
;
1908 if (this.attr_('highlightSeriesOpts')) {
1909 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1910 var alpha
= 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
1912 // Activating background fade includes an animation effect for a gradual
1913 // fade. TODO(klausw): make this independently configurable if it causes
1914 // issues? Use a shared preference to control animations?
1915 var animateBackgroundFade
= true;
1916 if (animateBackgroundFade
) {
1917 if (opt_animFraction
=== undefined
) {
1918 // start a new animation
1919 this.animateSelection_(1);
1922 alpha
*= opt_animFraction
;
1924 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1925 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1927 var setIdx
= this.datasetIndexFromSetName_(this.highlightSet_
);
1928 this.plotter_
._drawLine(ctx
, setIdx
);
1929 } else if (this.previousVerticalX_
>= 0) {
1930 // Determine the maximum highlight circle size.
1931 var maxCircleSize
= 0;
1932 var labels
= this.attr_('labels');
1933 for (i
= 1; i
< labels
.length
; i
++) {
1934 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1935 if (r
> maxCircleSize
) maxCircleSize
= r
;
1937 var px
= this.previousVerticalX_
;
1938 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1939 2 * maxCircleSize
+ 2, this.height_
);
1942 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
1943 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
1946 if (this.selPoints_
.length
> 0) {
1947 // Set the status message to indicate the selected point(s)
1948 if (this.attr_('showLabelsOnHighlight')) {
1949 this.setLegendHTML_(this.lastx_
, this.selPoints_
);
1952 // Draw colored circles over the center of each selected point
1953 var canvasx
= this.selPoints_
[0].canvasx
;
1955 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1956 var pt
= this.selPoints_
[i
];
1957 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1959 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1960 var callback
= this.attr_("drawHighlightPointCallback", pt
.name
);
1961 var color
= this.plotter_
.colors
[pt
.name
];
1963 callback
= Dygraph
.Circles
.DEFAULT
;
1965 ctx
.lineWidth
= this.attr_('strokeWidth', pt
.name
);
1966 ctx
.strokeStyle
= color
;
1967 ctx
.fillStyle
= color
;
1968 callback(this.g
, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1973 this.previousVerticalX_
= canvasx
;
1978 * Manually set the selected points and display information about them in the
1979 * legend. The selection can be cleared using clearSelection() and queried
1980 * using getSelection().
1981 * @param { Integer } row number that should be highlighted (i.e. appear with
1982 * hover dots on the chart). Set to false to clear any selection.
1983 * @param { seriesName } optional series name to highlight that series with the
1984 * the highlightSeriesOpts setting.
1986 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
) {
1987 // Extract the points we've selected
1988 this.selPoints_
= [];
1991 if (row
!== false) {
1992 row
-= this.getLeftBoundary_();
1995 var changed
= false;
1996 if (row
!== false && row
>= 0) {
1997 if (row
!= this.lastRow_
) changed
= true;
1998 this.lastRow_
= row
;
1999 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
2000 var set
= this.layout_
.datasets
[setIdx
];
2001 if (row
< set
.length
) {
2002 var point
= this.layout_
.points
[pos
+row
];
2004 if (this.attr_("stackedGraph")) {
2005 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
2008 if (!(point
.yval
=== null)) this.selPoints_
.push(point
);
2013 if (this.lastRow_
>= 0) changed
= true;
2017 if (this.selPoints_
.length
) {
2018 this.lastx_
= this.selPoints_
[0].xval
;
2023 if (opt_seriesName
!== undefined
) {
2024 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
2025 this.highlightSet_
= opt_seriesName
;
2029 this.updateSelection_(undefined
);
2035 * The mouse has left the canvas. Clear out whatever artifacts remain
2036 * @param {Object} event the mouseout event from the browser.
2039 Dygraph
.prototype.mouseOut_
= function(event
) {
2040 if (this.attr_("unhighlightCallback")) {
2041 this.attr_("unhighlightCallback")(event
);
2044 if (this.attr_("hideOverlayOnMouseOut")) {
2045 this.clearSelection();
2050 * Clears the current selection (i.e. points that were highlighted by moving
2051 * the mouse over the chart).
2053 Dygraph
.prototype.clearSelection
= function() {
2054 // Get rid of the overlay data
2055 if (this.fadeLevel
) {
2056 this.animateSelection_(-1);
2059 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
2061 this.setLegendHTML_();
2062 this.selPoints_
= [];
2065 this.highlightSet_
= null;
2069 * Returns the number of the currently selected row. To get data for this row,
2070 * you can use the getValue method.
2071 * @return { Integer } row number, or -1 if nothing is selected
2073 Dygraph
.prototype.getSelection
= function() {
2074 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
2078 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
2079 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
2080 return row
+ this.getLeftBoundary_();
2086 Dygraph
.prototype.getHighlightSeries
= function() {
2087 return this.highlightSet_
;
2091 * Fires when there's data available to be graphed.
2092 * @param {String} data Raw CSV data to be plotted
2095 Dygraph
.prototype.loadedEvent_
= function(data
) {
2096 this.rawData_
= this.parseCSV_(data
);
2101 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2104 Dygraph
.prototype.addXTicks_
= function() {
2105 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2107 if (this.dateWindow_
) {
2108 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2110 range
= this.fullXRange_();
2113 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2114 var xTicks
= xAxisOptionsView('ticker')(
2117 this.width_
, // TODO(danvk): should be area.width
2120 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2121 // console.log(msg);
2122 this.layout_
.setXTicks(xTicks
);
2127 * Computes the range of the data series (including confidence intervals).
2128 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2129 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2130 * @return [low, high]
2132 Dygraph
.prototype.extremeValues_
= function(series
) {
2133 var minY
= null, maxY
= null, j
, y
;
2135 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2137 // With custom bars, maxY is the max of the high values.
2138 for (j
= 0; j
< series
.length
; j
++) {
2139 y
= series
[j
][1][0];
2141 var low
= y
- series
[j
][1][1];
2142 var high
= y
+ series
[j
][1][2];
2143 if (low
> y
) low
= y
; // this can happen with custom bars,
2144 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2145 if (maxY
=== null || high
> maxY
) {
2148 if (minY
=== null || low
< minY
) {
2153 for (j
= 0; j
< series
.length
; j
++) {
2155 if (y
=== null || isNaN(y
)) continue;
2156 if (maxY
=== null || y
> maxY
) {
2159 if (minY
=== null || y
< minY
) {
2165 return [minY
, maxY
];
2170 * This function is called once when the chart's data is changed or the options
2171 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2172 * idea is that values derived from the chart's data can be computed here,
2173 * rather than every time the chart is drawn. This includes things like the
2174 * number of axes, rolling averages, etc.
2176 Dygraph
.prototype.predraw_
= function() {
2177 var start
= new Date();
2179 // TODO(danvk): move more computations out of drawGraph_ and into here.
2180 this.computeYAxes_();
2182 // Create a new plotter.
2183 if (this.plotter_
) this.plotter_
.clear();
2184 this.plotter_
= new DygraphCanvasRenderer(this,
2189 // The roller sits in the bottom left corner of the chart. We don't know where
2190 // this will be until the options are available, so it's positioned here.
2191 this.createRollInterface_();
2193 // Same thing applies for the labelsDiv. It's right edge should be flush with
2194 // the right edge of the charting area (which may not be the same as the right
2195 // edge of the div, if we have two y-axes.
2196 this.positionLabelsDiv_();
2198 if (this.rangeSelector_
) {
2199 this.rangeSelector_
.renderStaticLayer();
2202 // Convert the raw data (a 2D array) into the internal format and compute
2203 // rolling averages.
2204 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2205 for (var i
= 1; i
< this.numColumns(); i
++) {
2206 var logScale
= this.attr_('logscale', i
); // TODO(klausw): this looks wrong
2207 var series
= this.extractSeries_(this.rawData_
, i
, logScale
);
2208 series
= this.rollingAverage(series
, this.rollPeriod_
);
2209 this.rolledSeries_
.push(series
);
2212 // If the data or options have changed, then we'd better redraw.
2215 // This is used to determine whether to do various animations.
2216 var end
= new Date();
2217 this.drawingTimeMs_
= (end
- start
);
2221 * Loop over all fields and create datasets, calculating extreme y-values for
2222 * each series and extreme x-indices as we go.
2224 * dateWindow is passed in as an explicit parameter so that we can compute
2225 * extreme values "speculatively", i.e. without actually setting state on the
2228 * TODO(danvk): make this more of a true function
2229 * @return [ datasets, seriesExtremes, boundaryIds ]
2232 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2233 var boundaryIds
= [];
2234 var cumulative_y
= []; // For stacked series.
2236 var extremes
= {}; // series name -> [low, high]
2239 // Loop over the fields (series). Go from the last to the first,
2240 // because if they're stacked that's how we accumulate the values.
2241 var num_series
= rolledSeries
.length
- 1;
2242 for (i
= num_series
; i
>= 1; i
--) {
2243 if (!this.visibility()[i
- 1]) continue;
2245 // TODO(danvk): is this copy really necessary?
2247 for (j
= 0; j
< rolledSeries
[i
].length
; j
++) {
2248 series
.push(rolledSeries
[i
][j
]);
2251 // Prune down to the desired range, if necessary (for zooming)
2252 // Because there can be lines going to points outside of the visible area,
2253 // we actually prune to visible points, plus one on either side.
2254 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2256 var low
= dateWindow
[0];
2257 var high
= dateWindow
[1];
2259 // TODO(danvk): do binary search instead of linear search.
2260 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2261 var firstIdx
= null, lastIdx
= null;
2262 for (k
= 0; k
< series
.length
; k
++) {
2263 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2266 if (series
[k
][0] <= high
) {
2270 if (firstIdx
=== null) firstIdx
= 0;
2271 if (firstIdx
> 0) firstIdx
--;
2272 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2273 if (lastIdx
< series
.length
- 1) lastIdx
++;
2274 boundaryIds
[i
-1] = [firstIdx
, lastIdx
];
2275 for (k
= firstIdx
; k
<= lastIdx
; k
++) {
2276 pruned
.push(series
[k
]);
2280 boundaryIds
[i
-1] = [0, series
.length
-1];
2283 var seriesExtremes
= this.extremeValues_(series
);
2286 for (j
=0; j
<series
.length
; j
++) {
2287 series
[j
] = [series
[j
][0],
2292 } else if (this.attr_("stackedGraph")) {
2293 var l
= series
.length
;
2295 for (j
= 0; j
< l
; j
++) {
2296 // If one data set has a NaN, let all subsequent stacked
2297 // sets inherit the NaN -- only start at 0 for the first set.
2298 var x
= series
[j
][0];
2299 if (cumulative_y
[x
] === undefined
) {
2300 cumulative_y
[x
] = 0;
2303 actual_y
= series
[j
][1];
2304 if (actual_y
=== null) {
2305 series
[j
] = [x
, null];
2309 cumulative_y
[x
] += actual_y
;
2311 series
[j
] = [x
, cumulative_y
[x
]];
2313 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2314 seriesExtremes
[1] = cumulative_y
[x
];
2316 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2317 seriesExtremes
[0] = cumulative_y
[x
];
2322 var seriesName
= this.attr_("labels")[i
];
2323 extremes
[seriesName
] = seriesExtremes
;
2324 datasets
[i
] = series
;
2327 // For stacked graphs, a NaN value for any point in the sum should create a
2328 // clean gap in the graph. Back-propagate NaNs to all points at this X value.
2329 if (this.attr_("stackedGraph")) {
2330 for (k
= datasets
.length
- 1; k
>= 0; --k
) {
2331 // Use the first nonempty dataset to get X values.
2332 if (!datasets
[k
]) continue;
2333 for (j
= 0; j
< datasets
[k
].length
; j
++) {
2334 var x
= datasets
[k
][j
][0];
2335 if (isNaN(cumulative_y
[x
])) {
2336 // Set all Y values to NaN at that X value.
2337 for (i
= datasets
.length
- 1; i
>= 0; i
--) {
2338 if (!datasets
[i
]) continue;
2339 datasets
[i
][j
][1] = NaN
;
2347 return [ datasets
, extremes
, boundaryIds
];
2351 * Update the graph with new data. This method is called when the viewing area
2352 * has changed. If the underlying data or options have changed, predraw_ will
2353 * be called before drawGraph_ is called.
2355 * clearSelection, when undefined or true, causes this.clearSelection to be
2356 * called at the end of the draw operation. This should rarely be defined,
2357 * and never true (that is it should be undefined most of the time, and
2362 Dygraph
.prototype.drawGraph_
= function(clearSelection
) {
2363 var start
= new Date();
2365 if (typeof(clearSelection
) === 'undefined') {
2366 clearSelection
= true;
2369 // This is used to set the second parameter to drawCallback, below.
2370 var is_initial_draw
= this.is_initial_draw_
;
2371 this.is_initial_draw_
= false;
2373 this.layout_
.removeAllDatasets();
2375 this.attrs_
.pointSize
= 0.5 * this.attr_('highlightCircleSize');
2377 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2378 var datasets
= packed
[0];
2379 var extremes
= packed
[1];
2380 this.boundaryIds_
= packed
[2];
2382 this.setIndexByName_
= {};
2383 var labels
= this.attr_("labels");
2384 if (labels
.length
> 0) {
2385 this.setIndexByName_
[labels
[0]] = 0;
2388 for (var i
= 1; i
< datasets
.length
; i
++) {
2389 this.setIndexByName_
[labels
[i
]] = i
;
2390 if (!this.visibility()[i
- 1]) continue;
2391 this.layout_
.addDataset(labels
[i
], datasets
[i
]);
2392 this.datasetIndex_
[i
] = dataIdx
++;
2395 this.computeYAxisRanges_(extremes
);
2396 this.layout_
.setYAxes(this.axes_
);
2400 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2401 var tmp_zoomed_x
= this.zoomed_x_
;
2402 // Tell PlotKit to use this new data and render itself
2403 this.layout_
.setDateWindow(this.dateWindow_
);
2404 this.zoomed_x_
= tmp_zoomed_x
;
2405 this.layout_
.evaluateWithError();
2406 this.renderGraph_(is_initial_draw
, false);
2408 if (this.attr_("timingName")) {
2409 var end
= new Date();
2411 console
.log(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2416 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
, clearSelection
) {
2417 this.plotter_
.clear();
2418 this.plotter_
.render();
2419 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2420 this.canvas_
.height
);
2422 // Generate a static legend before any particular point is selected.
2423 this.setLegendHTML_();
2425 if (!is_initial_draw
) {
2426 if (clearSelection
) {
2427 if (typeof(this.selPoints_
) !== 'undefined' && this.selPoints_
.length
) {
2428 // We should select the point nearest the page x/y here
, but it
's easier
2429 // to just clear the selection. This prevents erroneous hover dots from
2431 this.clearSelection();
2433 this.clearSelection();
2438 if (this.rangeSelector_) {
2439 this.rangeSelector_.renderInteractiveLayer();
2442 if (this.attr_("drawCallback") !== null) {
2443 this.attr_("drawCallback")(this, is_initial_draw);
2449 * Determine properties of the y-axes which are independent of the data
2450 * currently being displayed. This includes things like the number of axes and
2451 * the style of the axes. It does not include the range of each axis and its
2453 * This fills in this.axes_ and this.seriesToAxisMap_.
2454 * axes_ = [ { options } ]
2455 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2456 * indices are into the axes_ array.
2458 Dygraph.prototype.computeYAxes_ = function() {
2459 // Preserve valueWindow settings if they exist, and if the user hasn't
2460 // specified a new valueRange.
2461 var i
, valueWindows
, seriesName
, axis
, index
, opts
, v
;
2462 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2464 for (index
= 0; index
< this.axes_
.length
; index
++) {
2465 valueWindows
.push(this.axes_
[index
].valueWindow
);
2469 this.axes_
= [{ yAxisId
: 0, g
: this }]; // always have at least one y-axis.
2470 this.seriesToAxisMap_
= {};
2472 // Get a list of series names.
2473 var labels
= this.attr_("labels");
2475 for (i
= 1; i
< labels
.length
; i
++) series
[labels
[i
]] = (i
- 1);
2477 // all options which could be applied per-axis:
2485 'axisLabelFontSize',
2490 // Copy global axis options over to the first axis.
2491 for (i
= 0; i
< axisOptions
.length
; i
++) {
2492 var k
= axisOptions
[i
];
2494 if (v
) this.axes_
[0][k
] = v
;
2497 // Go through once and add all the axes.
2498 for (seriesName
in series
) {
2499 if (!series
.hasOwnProperty(seriesName
)) continue;
2500 axis
= this.attr_("axis", seriesName
);
2501 if (axis
=== null) {
2502 this.seriesToAxisMap_
[seriesName
] = 0;
2505 if (typeof(axis
) == 'object') {
2506 // Add a new axis, making a copy of its per-axis options.
2508 Dygraph
.update(opts
, this.axes_
[0]);
2509 Dygraph
.update(opts
, { valueRange
: null }); // shouldn't inherit this.
2510 var yAxisId
= this.axes_
.length
;
2511 opts
.yAxisId
= yAxisId
;
2513 Dygraph
.update(opts
, axis
);
2514 this.axes_
.push(opts
);
2515 this.seriesToAxisMap_
[seriesName
] = yAxisId
;
2519 // Go through one more time and assign series to an axis defined by another
2520 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2521 for (seriesName
in series
) {
2522 if (!series
.hasOwnProperty(seriesName
)) continue;
2523 axis
= this.attr_("axis", seriesName
);
2524 if (typeof(axis
) == 'string') {
2525 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
2526 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
2527 "series " + axis
+ ", which does not define its own axis.");
2530 var idx
= this.seriesToAxisMap_
[axis
];
2531 this.seriesToAxisMap_
[seriesName
] = idx
;
2535 if (valueWindows
!== undefined
) {
2536 // Restore valueWindow settings.
2537 for (index
= 0; index
< valueWindows
.length
; index
++) {
2538 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2543 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2545 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2546 v
= opts("valueRange");
2547 if (v
) this.axes_
[axis
].valueRange
= v
;
2548 } else { // To keep old behavior
2549 var axes
= this.user_attrs_
.axes
;
2550 if (axes
&& axes
.y2
) {
2551 v
= axes
.y2
.valueRange
;
2552 if (v
) this.axes_
[axis
].valueRange
= v
;
2560 * Returns the number of y-axes on the chart.
2561 * @return {Number} the number of axes.
2563 Dygraph
.prototype.numAxes
= function() {
2565 for (var series
in this.seriesToAxisMap_
) {
2566 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2567 var idx
= this.seriesToAxisMap_
[series
];
2568 if (idx
> last_axis
) last_axis
= idx
;
2570 return 1 + last_axis
;
2575 * Returns axis properties for the given series.
2576 * @param { String } setName The name of the series for which to get axis
2577 * properties, e.g. 'Y1'.
2578 * @return { Object } The axis properties.
2580 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2581 // TODO(danvk): handle errors.
2582 return this.axes_
[this.seriesToAxisMap_
[series
]];
2587 * Determine the value range and tick marks for each axis.
2588 * @param {Object} extremes A mapping from seriesName -> [low, high]
2589 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2591 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2592 // Build a map from axis number -> [list of series names]
2593 var seriesForAxis
= [], series
;
2594 for (series
in this.seriesToAxisMap_
) {
2595 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2596 var idx
= this.seriesToAxisMap_
[series
];
2597 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2598 seriesForAxis
[idx
].push(series
);
2601 // Compute extreme values, a span and tick marks for each axis.
2602 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2603 var axis
= this.axes_
[i
];
2605 if (!seriesForAxis
[i
]) {
2606 // If no series are defined or visible then use a reasonable default
2607 axis
.extremeRange
= [0, 1];
2609 // Calculate the extremes of extremes.
2610 series
= seriesForAxis
[i
];
2611 var minY
= Infinity
; // extremes[series[0]][0];
2612 var maxY
= -Infinity
; // extremes[series[0]][1];
2613 var extremeMinY
, extremeMaxY
;
2615 for (var j
= 0; j
< series
.length
; j
++) {
2616 // this skips invisible series
2617 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2619 // Only use valid extremes to stop null data series' from corrupting the scale.
2620 extremeMinY
= extremes
[series
[j
]][0];
2621 if (extremeMinY
!== null) {
2622 minY
= Math
.min(extremeMinY
, minY
);
2624 extremeMaxY
= extremes
[series
[j
]][1];
2625 if (extremeMaxY
!== null) {
2626 maxY
= Math
.max(extremeMaxY
, maxY
);
2629 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2631 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2632 if (minY
== Infinity
) minY
= 0;
2633 if (maxY
== -Infinity
) maxY
= 1;
2635 // Add some padding and round up to an integer to be human-friendly.
2636 var span
= maxY
- minY
;
2637 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2638 if (span
=== 0) { span
= maxY
; }
2640 var maxAxisY
, minAxisY
;
2641 if (axis
.logscale
) {
2642 maxAxisY
= maxY
+ 0.1 * span
;
2645 maxAxisY
= maxY
+ 0.1 * span
;
2646 minAxisY
= minY
- 0.1 * span
;
2648 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2649 if (!this.attr_("avoidMinZero")) {
2650 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2651 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2654 if (this.attr_("includeZero")) {
2655 if (maxY
< 0) maxAxisY
= 0;
2656 if (minY
> 0) minAxisY
= 0;
2659 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2661 if (axis
.valueWindow
) {
2662 // This is only set if the user has zoomed on the y-axis. It is never set
2663 // by a user. It takes precedence over axis.valueRange because, if you set
2664 // valueRange, you'd still expect to be able to pan.
2665 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2666 } else if (axis
.valueRange
) {
2667 // This is a user-set value range for this axis.
2668 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
2670 axis
.computedValueRange
= axis
.extremeRange
;
2673 // Add ticks. By default, all axes inherit the tick positions of the
2674 // primary axis. However, if an axis is specifically marked as having
2675 // independent ticks, then that is permissible as well.
2676 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2677 var ticker
= opts('ticker');
2678 if (i
=== 0 || axis
.independentTicks
) {
2679 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2680 axis
.computedValueRange
[1],
2681 this.height_
, // TODO(danvk): should be area.height
2685 var p_axis
= this.axes_
[0];
2686 var p_ticks
= p_axis
.ticks
;
2687 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2688 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2689 var tick_values
= [];
2690 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2691 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2692 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2693 tick_values
.push(y_val
);
2696 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2697 axis
.computedValueRange
[1],
2698 this.height_
, // TODO(danvk): should be area.height
2707 * Extracts one series from the raw data (a 2D array) into an array of (date,
2710 * This is where undesirable points (i.e. negative values on log scales and
2711 * missing values through which we wish to connect lines) are dropped.
2715 Dygraph
.prototype.extractSeries_
= function(rawData
, i
, logScale
) {
2717 for (var j
= 0; j
< rawData
.length
; j
++) {
2718 var x
= rawData
[j
][0];
2719 var point
= rawData
[j
][i
];
2721 // On the log scale, points less than zero do not exist.
2722 // This will create a gap in the chart.
2727 series
.push([x
, point
]);
2734 * Calculates the rolling average of a data set.
2735 * If originalData is [label, val], rolls the average of those.
2736 * If originalData is [label, [, it's interpreted as [value, stddev]
2737 * and the roll is returned in the same form, with appropriately reduced
2738 * stddev for each value.
2739 * Note that this is where fractional input (i.e. '5/10') is converted into
2741 * @param {Array} originalData The data in the appropriate format (see above)
2742 * @param {Number} rollPeriod The number of points over which to average the
2745 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2746 if (originalData
.length
< 2)
2747 return originalData
;
2748 rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2749 var rollingData
= [];
2750 var sigma
= this.attr_("sigma");
2752 var low
, high
, i
, j
, y
, sum
, num_ok
, stddev
;
2753 if (this.fractions_
) {
2755 var den
= 0; // numerator/denominator
2757 for (i
= 0; i
< originalData
.length
; i
++) {
2758 num
+= originalData
[i
][1][0];
2759 den
+= originalData
[i
][1][1];
2760 if (i
- rollPeriod
>= 0) {
2761 num
-= originalData
[i
- rollPeriod
][1][0];
2762 den
-= originalData
[i
- rollPeriod
][1][1];
2765 var date
= originalData
[i
][0];
2766 var value
= den
? num
/ den
: 0.0;
2767 if (this.attr_("errorBars")) {
2768 if (this.attr_("wilsonInterval")) {
2769 // For more details on this confidence interval, see:
2770 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2772 var p
= value
< 0 ? 0 : value
, n
= den
;
2773 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2774 var denom
= 1 + sigma
* sigma
/ den
;
2775 low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2776 high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2777 rollingData
[i
] = [date
,
2778 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2780 rollingData
[i
] = [date
, [0, 0, 0]];
2783 stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2784 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2787 rollingData
[i
] = [date
, mult
* value
];
2790 } else if (this.attr_("customBars")) {
2795 for (i
= 0; i
< originalData
.length
; i
++) {
2796 var data
= originalData
[i
][1];
2798 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2800 if (y
!== null && !isNaN(y
)) {
2806 if (i
- rollPeriod
>= 0) {
2807 var prev
= originalData
[i
- rollPeriod
];
2808 if (prev
[1][1] !== null && !isNaN(prev
[1][1])) {
2816 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2817 1.0 * (mid
- low
) / count
,
2818 1.0 * (high
- mid
) / count
]];
2820 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2824 // Calculate the rolling average for the first rollPeriod - 1 points where
2825 // there is not enough data to roll over the full number of points
2826 if (!this.attr_("errorBars")){
2827 if (rollPeriod
== 1) {
2828 return originalData
;
2831 for (i
= 0; i
< originalData
.length
; i
++) {
2834 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2835 y
= originalData
[j
][1];
2836 if (y
=== null || isNaN(y
)) continue;
2838 sum
+= originalData
[j
][1];
2841 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2843 rollingData
[i
] = [originalData
[i
][0], null];
2848 for (i
= 0; i
< originalData
.length
; i
++) {
2852 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2853 y
= originalData
[j
][1][0];
2854 if (y
=== null || isNaN(y
)) continue;
2856 sum
+= originalData
[j
][1][0];
2857 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2860 stddev
= Math
.sqrt(variance
) / num_ok
;
2861 rollingData
[i
] = [originalData
[i
][0],
2862 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2864 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2874 * Detects the type of the str (date or numeric) and sets the various
2875 * formatting attributes in this.attrs_ based on this type.
2876 * @param {String} str An x value.
2879 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2881 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2882 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
2883 str
.indexOf('/') >= 0 ||
2884 isNaN(parseFloat(str
))) {
2886 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2887 // TODO(danvk): remove support for this format.
2892 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2893 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
2894 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2895 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2897 /** @private (shut up, jsdoc!) */
2898 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2899 // TODO(danvk): use Dygraph.numberValueFormatter here?
2900 /** @private (shut up, jsdoc!) */
2901 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2902 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
2903 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2908 * Parses the value as a floating point number. This is like the parseFloat()
2909 * built-in, but with a few differences:
2910 * - the empty string is parsed as null, rather than NaN.
2911 * - if the string cannot be parsed at all, an error is logged.
2912 * If the string can't be parsed, this method returns null.
2913 * @param {String} x The string to be parsed
2914 * @param {Number} opt_line_no The line number from which the string comes.
2915 * @param {String} opt_line The text of the line from which the string comes.
2919 // Parse the x as a float or return null if it's not a number.
2920 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
2921 var val
= parseFloat(x
);
2922 if (!isNaN(val
)) return val
;
2924 // Try to figure out what happeend.
2925 // If the value is the empty string, parse it as null.
2926 if (/^ *$/.test(x
)) return null;
2928 // If it was actually "NaN", return it as NaN.
2929 if (/^ *nan *$/i.test(x
)) return NaN
;
2931 // Looks like a parsing error.
2932 var msg
= "Unable to parse '" + x
+ "' as a number";
2933 if (opt_line
!== null && opt_line_no
!== null) {
2934 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
2943 * Parses a string in a special csv format. We expect a csv file where each
2944 * line is a date point, and the first field in each line is the date string.
2945 * We also expect that all remaining fields represent series.
2946 * if the errorBars attribute is set, then interpret the fields as:
2947 * date, series1, stddev1, series2, stddev2, ...
2948 * @param {[Object]} data See above.
2950 * @return [Object] An array with one entry for each row. These entries
2951 * are an array of cells in that row. The first entry is the parsed x-value for
2952 * the row. The second, third, etc. are the y-values. These can take on one of
2953 * three forms, depending on the CSV and constructor parameters:
2955 * 2. [ value, stddev ]
2956 * 3. [ low value, center value, high value ]
2958 Dygraph
.prototype.parseCSV_
= function(data
) {
2960 var lines
= data
.split("\n");
2963 // Use the default delimiter or fall back to a tab if that makes sense.
2964 var delim
= this.attr_('delimiter');
2965 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2970 if (!('labels' in this.user_attrs_
)) {
2971 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
2973 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
2978 var defaultParserSet
= false; // attempt to auto-detect x value type
2979 var expectedCols
= this.attr_("labels").length
;
2980 var outOfOrder
= false;
2981 for (var i
= start
; i
< lines
.length
; i
++) {
2982 var line
= lines
[i
];
2984 if (line
.length
=== 0) continue; // skip blank lines
2985 if (line
[0] == '#') continue; // skip comment lines
2986 var inFields
= line
.split(delim
);
2987 if (inFields
.length
< 2) continue;
2990 if (!defaultParserSet
) {
2991 this.detectTypeFromString_(inFields
[0]);
2992 xParser
= this.attr_("xValueParser");
2993 defaultParserSet
= true;
2995 fields
[0] = xParser(inFields
[0], this);
2997 // If fractions are expected, parse the numbers as "A/B
"
2998 if (this.fractions_) {
2999 for (j = 1; j < inFields.length; j++) {
3000 // TODO(danvk): figure out an appropriate way to flag parse errors.
3001 vals = inFields[j].split("/");
3002 if (vals.length != 2) {
3003 this.error('Expected fractional "num
/den
" values in CSV data ' +
3004 "but found a value
'" + inFields[j] + "' on line
" +
3005 (1 + i) + " ('" + line + "') which is not of
this form
.");
3008 fields[j] = [this.parseFloat_(vals[0], i, line),
3009 this.parseFloat_(vals[1], i, line)];
3012 } else if (this.attr_("errorBars
")) {
3013 // If there are error bars, values are (value, stddev) pairs
3014 if (inFields.length % 2 != 1) {
3015 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3016 'but line ' + (1 + i) + ' has an odd number of values (' +
3017 (inFields.length - 1) + "): '" + line + "'");
3019 for (j = 1; j < inFields.length; j += 2) {
3020 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3021 this.parseFloat_(inFields[j + 1], i, line)];
3023 } else if (this.attr_("customBars
")) {
3024 // Bars are a low;center;high tuple
3025 for (j = 1; j < inFields.length; j++) {
3026 var val = inFields[j];
3027 if (/^ *$/.test(val)) {
3028 fields[j] = [null, null, null];
3030 vals = val.split(";");
3031 if (vals.length == 3) {
3032 fields[j] = [ this.parseFloat_(vals[0], i, line),
3033 this.parseFloat_(vals[1], i, line),
3034 this.parseFloat_(vals[2], i, line) ];
3036 this.warn('When using customBars, values must be either blank ' +
3037 'or "low
;center
;high
" tuples (got "' + val +
3038 '" on line ' + (1+i));
3043 // Values are just numbers
3044 for (j = 1; j < inFields.length; j++) {
3045 fields[j] = this.parseFloat_(inFields[j], i, line);
3048 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3052 if (fields.length != expectedCols) {
3053 this.error("Number of columns
in line
" + i + " (" + fields.length +
3054 ") does not agree
with number of
labels (" + expectedCols +
3058 // If the user specified the 'labels' option and none of the cells of the
3059 // first row parsed correctly, then they probably double-specified the
3060 // labels. We go with the values set in the option, discard this row and
3061 // log a warning to the JS console.
3062 if (i === 0 && this.attr_('labels')) {
3063 var all_null = true;
3064 for (j = 0; all_null && j < fields.length; j++) {
3065 if (fields[j]) all_null = false;
3068 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
3069 "CSV
data ('" + line + "') appears to also contain labels
. " +
3070 "Will drop the CSV labels and
use the option labels
.");
3078 this.warn("CSV is out of order
; order it correctly to speed loading
.");
3079 ret.sort(function(a,b) { return a[0] - b[0]; });
3087 * The user has provided their data as a pre-packaged JS array. If the x values
3088 * are numeric, this is the same as dygraphs' internal format. If the x values
3089 * are dates, we need to convert them from Date objects to ms since epoch.
3090 * @param {[Object]} data
3091 * @return {[Object]} data with numeric x values.
3093 Dygraph.prototype.parseArray_ = function(data) {
3094 // Peek at the first x value to see if it's numeric.
3095 if (data.length === 0) {
3096 this.error("Can
't plot empty data set");
3099 if (data[0].length === 0) {
3100 this.error("Data set cannot contain an empty row");
3105 if (this.attr_("labels") === null) {
3106 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3107 "in the options parameter");
3108 this.attrs_.labels = [ "X" ];
3109 for (i = 1; i < data[0].length; i++) {
3110 this.attrs_.labels.push("Y" + i);
3114 if (Dygraph.isDateLike(data[0][0])) {
3115 // Some intelligent defaults for a date x-axis.
3116 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3117 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3118 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3120 // Assume they're all dates
.
3121 var parsedData
= Dygraph
.clone(data
);
3122 for (i
= 0; i
< data
.length
; i
++) {
3123 if (parsedData
[i
].length
=== 0) {
3124 this.error("Row " + (1 + i
) + " of data is empty");
3127 if (parsedData
[i
][0] === null ||
3128 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3129 isNaN(parsedData
[i
][0].getTime())) {
3130 this.error("x value in row " + (1 + i
) + " is not a Date");
3133 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3137 // Some intelligent defaults for a numeric x-axis.
3138 /** @private (shut up, jsdoc!) */
3139 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3140 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3141 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3147 * Parses a DataTable object from gviz.
3148 * The data is expected to have a first column that is either a date or a
3149 * number. All subsequent columns must be numbers. If there is a clear mismatch
3150 * between this.xValueParser_ and the type of the first column, it will be
3151 * fixed. Fills out rawData_.
3152 * @param {[Object]} data See above.
3155 Dygraph
.prototype.parseDataTable_
= function(data
) {
3156 var shortTextForAnnotationNum
= function(num
) {
3157 // converts [0-9]+ [A-Z][a-z]*
3158 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3159 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3160 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3161 num
= Math
.floor(num
/ 26);
3163 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3164 num
= Math
.floor((num
- 1) / 26);
3169 var cols
= data
.getNumberOfColumns();
3170 var rows
= data
.getNumberOfRows();
3172 var indepType
= data
.getColumnType(0);
3173 if (indepType
== 'date' || indepType
== 'datetime') {
3174 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3175 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3176 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3177 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3178 } else if (indepType
== 'number') {
3179 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3180 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3181 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3182 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3184 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3185 "column 1 of DataTable input (Got '" + indepType
+ "')");
3189 // Array of the column indices which contain data (and not annotations).
3191 var annotationCols
= {}; // data index -> [annotation cols]
3192 var hasAnnotations
= false;
3194 for (i
= 1; i
< cols
; i
++) {
3195 var type
= data
.getColumnType(i
);
3196 if (type
== 'number') {
3198 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3199 // This is OK -- it's an annotation column.
3200 var dataIdx
= colIdx
[colIdx
.length
- 1];
3201 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3202 annotationCols
[dataIdx
] = [i
];
3204 annotationCols
[dataIdx
].push(i
);
3206 hasAnnotations
= true;
3208 this.error("Only 'number' is supported as a dependent type with Gviz." +
3209 " 'string' is only supported if displayAnnotations is true");
3213 // Read column labels
3214 // TODO(danvk): add support back for errorBars
3215 var labels
= [data
.getColumnLabel(0)];
3216 for (i
= 0; i
< colIdx
.length
; i
++) {
3217 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3218 if (this.attr_("errorBars")) i
+= 1;
3220 this.attrs_
.labels
= labels
;
3221 cols
= labels
.length
;
3224 var outOfOrder
= false;
3225 var annotations
= [];
3226 for (i
= 0; i
< rows
; i
++) {
3228 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3229 data
.getValue(i
, 0) === null) {
3230 this.warn("Ignoring row " + i
+
3231 " of DataTable because of undefined or null first column.");
3235 if (indepType
== 'date' || indepType
== 'datetime') {
3236 row
.push(data
.getValue(i
, 0).getTime());
3238 row
.push(data
.getValue(i
, 0));
3240 if (!this.attr_("errorBars")) {
3241 for (j
= 0; j
< colIdx
.length
; j
++) {
3242 var col
= colIdx
[j
];
3243 row
.push(data
.getValue(i
, col
));
3244 if (hasAnnotations
&&
3245 annotationCols
.hasOwnProperty(col
) &&
3246 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3248 ann
.series
= data
.getColumnLabel(col
);
3250 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3252 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3253 if (k
) ann
.text
+= "\n";
3254 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3256 annotations
.push(ann
);
3260 // Strip out infinities, which give dygraphs problems later on.
3261 for (j
= 0; j
< row
.length
; j
++) {
3262 if (!isFinite(row
[j
])) row
[j
] = null;
3265 for (j
= 0; j
< cols
- 1; j
++) {
3266 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3269 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3276 this.warn("DataTable is out of order; order it correctly to speed loading.");
3277 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3279 this.rawData_
= ret
;
3281 if (annotations
.length
> 0) {
3282 this.setAnnotations(annotations
, true);
3287 * Get the CSV data. If it's in a function, call that function. If it's in a
3288 * file, do an XMLHttpRequest to get it.
3291 Dygraph
.prototype.start_
= function() {
3292 var data
= this.file_
;
3294 // Functions can return references of all other types.
3295 if (typeof data
== 'function') {
3299 if (Dygraph
.isArrayLike(data
)) {
3300 this.rawData_
= this.parseArray_(data
);
3302 } else if (typeof data
== 'object' &&
3303 typeof data
.getColumnRange
== 'function') {
3304 // must be a DataTable from gviz.
3305 this.parseDataTable_(data
);
3307 } else if (typeof data
== 'string') {
3308 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3309 if (data
.indexOf('\n') >= 0) {
3310 this.loadedEvent_(data
);
3312 var req
= new XMLHttpRequest();
3314 req
.onreadystatechange
= function () {
3315 if (req
.readyState
== 4) {
3316 if (req
.status
=== 200 || // Normal http
3317 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3318 caller
.loadedEvent_(req
.responseText
);
3323 req
.open("GET", data
, true);
3327 this.error("Unknown data format: " + (typeof data
));
3332 * Changes various properties of the graph. These can include:
3334 * <li>file: changes the source data for the graph</li>
3335 * <li>errorBars: changes whether the data contains stddev</li>
3338 * There's a huge variety of options that can be passed to this method. For a
3339 * full list, see http://dygraphs.com/options.html.
3341 * @param {Object} attrs The new properties and values
3342 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3343 * call to updateOptions(). If you know better, you can pass true to explicitly
3344 * block the redraw. This can be useful for chaining updateOptions() calls,
3345 * avoiding the occasional infinite loop and preventing redraws when it's not
3346 * necessary (e.g. when updating a callback).
3348 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3349 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3351 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3352 var file
= input_attrs
.file
;
3353 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3355 // TODO(danvk): this is a mess. Move these options into attr_.
3356 if ('rollPeriod' in attrs
) {
3357 this.rollPeriod_
= attrs
.rollPeriod
;
3359 if ('dateWindow' in attrs
) {
3360 this.dateWindow_
= attrs
.dateWindow
;
3361 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3362 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3365 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3366 this.zoomed_y_
= (attrs
.valueRange
!== null);
3369 // TODO(danvk): validate per-series options.
3374 // highlightCircleSize
3376 // Check if this set options will require new points.
3377 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3379 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3383 if (!block_redraw
) this.start_();
3385 if (!block_redraw
) {
3386 if (requiresNewPoints
) {
3389 this.renderGraph_(false, false);
3396 * Returns a copy of the options with deprecated names converted into current
3397 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3398 * interested in that, they should save a copy before calling this.
3401 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3403 for (var k
in attrs
) {
3404 if (k
== 'file') continue;
3405 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3408 var set
= function(axis
, opt
, value
) {
3409 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3410 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3411 my_attrs
.axes
[axis
][opt
] = value
;
3413 var map
= function(opt
, axis
, new_opt
) {
3414 if (typeof(attrs
[opt
]) != 'undefined') {
3415 set(axis
, new_opt
, attrs
[opt
]);
3416 delete my_attrs
[opt
];
3420 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3421 map('xValueFormatter', 'x', 'valueFormatter');
3422 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3423 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3424 map('xTicker', 'x', 'ticker');
3425 map('yValueFormatter', 'y', 'valueFormatter');
3426 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3427 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3428 map('yTicker', 'y', 'ticker');
3433 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3434 * containing div (which has presumably changed size since the dygraph was
3435 * instantiated. If the width/height are specified, the div will be resized.
3437 * This is far more efficient than destroying and re-instantiating a
3438 * Dygraph, since it doesn't have to reparse the underlying data.
3440 * @param {Number} [width] Width (in pixels)
3441 * @param {Number} [height] Height (in pixels)
3443 Dygraph
.prototype.resize
= function(width
, height
) {
3444 if (this.resize_lock
) {
3447 this.resize_lock
= true;
3449 if ((width
=== null) != (height
=== null)) {
3450 this.warn("Dygraph.resize() should be called with zero parameters or " +
3451 "two non-NULL parameters. Pretending it was zero.");
3452 width
= height
= null;
3455 var old_width
= this.width_
;
3456 var old_height
= this.height_
;
3459 this.maindiv_
.style
.width
= width
+ "px";
3460 this.maindiv_
.style
.height
= height
+ "px";
3461 this.width_
= width
;
3462 this.height_
= height
;
3464 this.width_
= this.maindiv_
.clientWidth
;
3465 this.height_
= this.maindiv_
.clientHeight
;
3468 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3469 // TODO(danvk): there should be a clear() method.
3470 this.maindiv_
.innerHTML
= "";
3471 this.roller_
= null;
3472 this.attrs_
.labelsDiv
= null;
3473 this.createInterface_();
3474 if (this.annotations_
.length
) {
3475 // createInterface_ reset the layout, so we need to do this.
3476 this.layout_
.setAnnotations(this.annotations_
);
3481 this.resize_lock
= false;
3485 * Adjusts the number of points in the rolling average. Updates the graph to
3486 * reflect the new averaging period.
3487 * @param {Number} length Number of points over which to average the data.
3489 Dygraph
.prototype.adjustRoll
= function(length
) {
3490 this.rollPeriod_
= length
;
3495 * Returns a boolean array of visibility statuses.
3497 Dygraph
.prototype.visibility
= function() {
3498 // Do lazy-initialization, so that this happens after we know the number of
3500 if (!this.attr_("visibility")) {
3501 this.attrs_
.visibility
= [];
3503 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3504 while (this.attr_("visibility").length
< this.numColumns() - 1) {
3505 this.attrs_
.visibility
.push(true);
3507 return this.attr_("visibility");
3511 * Changes the visiblity of a series.
3513 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3514 var x
= this.visibility();
3515 if (num
< 0 || num
>= x
.length
) {
3516 this.warn("invalid series number in setVisibility: " + num
);
3524 * How large of an area will the dygraph render itself in?
3525 * This is used for testing.
3526 * @return A {width: w, height: h} object.
3529 Dygraph
.prototype.size
= function() {
3530 return { width
: this.width_
, height
: this.height_
};
3534 * Update the list of annotations and redraw the chart.
3535 * See dygraphs.com/annotations.html for more info on how to use annotations.
3536 * @param ann {Array} An array of annotation objects.
3537 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3539 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3540 // Only add the annotation CSS rule once we know it will be used.
3541 Dygraph
.addAnnotationRule();
3542 this.annotations_
= ann
;
3543 this.layout_
.setAnnotations(this.annotations_
);
3544 if (!suppressDraw
) {
3550 * Return the list of annotations.
3552 Dygraph
.prototype.annotations
= function() {
3553 return this.annotations_
;
3557 * Get the list of label names for this graph. The first column is the
3558 * x-axis, so the data series names start at index 1.
3560 Dygraph
.prototype.getLabels
= function(name
) {
3561 return this.attr_("labels").slice();
3565 * Get the index of a series (column) given its name. The first column is the
3566 * x-axis, so the data series start with index 1.
3568 Dygraph
.prototype.indexFromSetName
= function(name
) {
3569 return this.setIndexByName_
[name
];
3573 * Get the internal dataset index given its name. These are numbered starting from 0,
3574 * and only count visible sets.
3577 Dygraph
.prototype.datasetIndexFromSetName_
= function(name
) {
3578 return this.datasetIndex_
[this.indexFromSetName(name
)];
3583 * Adds a default style for the annotation CSS classes to the document. This is
3584 * only executed when annotations are actually used. It is designed to only be
3585 * called once -- all calls after the first will return immediately.
3587 Dygraph
.addAnnotationRule
= function() {
3588 if (Dygraph
.addedAnnotationCSS
) return;
3590 var rule
= "border: 1px solid black; " +
3591 "background-color: white; " +
3592 "text-align: center;";
3594 var styleSheetElement
= document
.createElement("style");
3595 styleSheetElement
.type
= "text/css";
3596 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3598 // Find the first style sheet that we can access.
3599 // We may not add a rule to a style sheet from another domain for security
3600 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3601 // adds its own style sheets from google.com.
3602 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3603 if (document
.styleSheets
[i
].disabled
) continue;
3604 var mysheet
= document
.styleSheets
[i
];
3606 if (mysheet
.insertRule
) { // Firefox
3607 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3608 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3609 } else if (mysheet
.addRule
) { // IE
3610 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3612 Dygraph
.addedAnnotationCSS
= true;
3615 // Was likely a security exception.
3619 this.warn("Unable to add default annotation CSS rule; display may be off.");
3622 // Older pages may still use this name.
3623 var DateGraph
= Dygraph
;