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 // For "production" code, this gets set to false by uglifyjs.
47 // if (typeof(DEBUG) === 'undefined') DEBUG=true;
50 import DygraphLayout from
'./dygraph-layout';
51 import DygraphCanvasRenderer from
'./dygraph-canvas';
52 import DygraphOptions from
'./dygraph-options';
53 import DygraphInteraction from
'./dygraph-interaction-model';
54 import * as DygraphTickers from
'./dygraph-tickers';
55 import * as utils from
'./dygraph-utils';
56 import DEFAULT_ATTRS from
'./dygraph-default-attrs';
57 import DygraphDataHandler from
'./datahandler/datahandler';
58 import DefaultHandler from
'./datahandler/default';
60 import AnnotationsPlugin from
'./plugins/annotations';
61 import AxesPlugin from
'./plugins/axes';
62 import ChartLabelsPlugin from
'./plugins/chart-labels';
63 import GridPlugin from
'./plugins/grid';
64 import LegendPlugin from
'./plugins/legend';
65 import RangeSelectorPlugin from
'./plugins/range-selector';
67 /*global DygraphLayout:false, DygraphCanvasRenderer:false, DygraphOptions:false, G_vmlCanvasManager:false,ActiveXObject:false */
71 * Creates an interactive, zoomable chart.
74 * @param {div | String} div A div or the id of a div into which to construct
76 * @param {String | Function} file A file containing CSV data or a function
77 * that returns this data. The most basic expected format for each line is
78 * "YYYY/MM/DD,val1,val2,...". For more information, see
79 * http://dygraphs.com/data.html.
80 * @param {Object} attrs Various other attributes, e.g. errorBars determines
81 * whether the input data contains error ranges. For a complete list of
82 * options, see http://dygraphs.com/options.html.
84 var Dygraph
= function(div
, data
, opts
) {
85 this.__init__(div
, data
, opts
);
88 Dygraph
.NAME
= "Dygraph";
89 Dygraph
.VERSION
= "1.1.0";
91 // Various default values
92 Dygraph
.DEFAULT_ROLL_PERIOD
= 1;
93 Dygraph
.DEFAULT_WIDTH
= 480;
94 Dygraph
.DEFAULT_HEIGHT
= 320;
96 // For max 60 Hz. animation:
97 Dygraph
.ANIMATION_STEPS
= 12;
98 Dygraph
.ANIMATION_DURATION
= 200;
101 * Standard plotters. These may be used by clients.
102 * Available plotters are:
103 * - Dygraph.Plotters.linePlotter: draws central lines (most common)
104 * - Dygraph.Plotters.errorPlotter: draws error bars
105 * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph)
107 * By default, the plotter is [fillPlotter, errorPlotter, linePlotter].
108 * This causes all the lines to be drawn over all the fills/error bars.
110 Dygraph
.Plotters
= DygraphCanvasRenderer
._Plotters
;
113 // Used for initializing annotation CSS rules only once.
114 Dygraph
.addedAnnotationCSS
= false;
117 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
118 * and context <canvas> inside of it. See the constructor for details.
120 * @param {Element} div the Element to render the graph into.
121 * @param {string | Function} file Source data
122 * @param {Object} attrs Miscellaneous other options
125 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
126 this.is_initial_draw_
= true;
129 // Support two-argument constructor
130 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
132 attrs
= Dygraph
.copyUserAttrs_(attrs
);
134 if (typeof(div
) == 'string') {
135 div
= document
.getElementById(div
);
139 throw new Error('Constructing dygraph with a non-existent div!');
142 // Copy the important bits into the object
143 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
146 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
147 this.previousVerticalX_
= -1;
148 this.fractions_
= attrs
.fractions
|| false;
149 this.dateWindow_
= attrs
.dateWindow
|| null;
151 this.annotations_
= [];
153 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
154 this.zoomed_x_
= false;
155 this.zoomed_y_
= false;
157 // Clear the div. This ensure that, if multiple dygraphs are passed the same
158 // div, then only one will be drawn.
161 // For historical reasons, the 'width' and 'height' options trump all CSS
162 // rules _except_ for an explicit 'width' or 'height' on the div.
163 // As an added convenience, if the div has zero height (like <div></div> does
164 // without any styles), then we use a default height/width
.
165 if (div
.style
.width
=== '' && attrs
.width
) {
166 div
.style
.width
= attrs
.width
+ "px";
168 if (div
.style
.height
=== '' && attrs
.height
) {
169 div
.style
.height
= attrs
.height
+ "px";
171 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
172 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
173 if (div
.style
.width
=== '') {
174 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
177 // These will be zero if the dygraph's div is hidden. In that case,
178 // use the user-specified attributes if present. If not, use zero
179 // and assume the user will call resize to fix things later.
180 this.width_
= div
.clientWidth
|| attrs
.width
|| 0;
181 this.height_
= div
.clientHeight
|| attrs
.height
|| 0;
183 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
184 if (attrs
.stackedGraph
) {
185 attrs
.fillGraph
= true;
186 // TODO(nikhilk): Add any other stackedGraph checks here.
189 // DEPRECATION WARNING: All option processing should be moved from
190 // attrs_ and user_attrs_ to options_, which holds all this information.
192 // Dygraphs has many options, some of which interact with one another.
193 // To keep track of everything, we maintain two sets of options:
195 // this.user_attrs_ only options explicitly set by the user.
196 // this.attrs_ defaults, options derived from user_attrs_, data.
198 // Options are then accessed this.attr_('attr'), which first looks at
199 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
200 // defaults without overriding behavior that the user specifically asks for.
201 this.user_attrs_
= {};
202 utils
.update(this.user_attrs_
, attrs
);
204 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
206 utils
.updateDeep(this.attrs_
, DEFAULT_ATTRS
);
208 this.boundaryIds_
= [];
209 this.setIndexByName_
= {};
210 this.datasetIndex_
= [];
212 this.registeredEvents_
= [];
213 this.eventListeners_
= {};
215 this.attributes_
= new DygraphOptions(this);
217 // Create the containing DIV and other interactive elements
218 this.createInterface_();
222 var plugins
= Dygraph
.PLUGINS
.concat(this.getOption('plugins'));
223 for (var i
= 0; i
< plugins
.length
; i
++) {
224 // the plugins option may contain either plugin classes or instances.
225 // Plugin instances contain an activate method.
226 var Plugin
= plugins
[i
]; // either a constructor or an instance.
228 if (typeof(Plugin
.activate
) !== 'undefined') {
229 pluginInstance
= Plugin
;
231 pluginInstance
= new Plugin();
235 plugin
: pluginInstance
,
241 var handlers
= pluginInstance
.activate(this);
242 for (var eventName
in handlers
) {
243 if (!handlers
.hasOwnProperty(eventName
)) continue;
244 // TODO(danvk): validate eventName.
245 pluginDict
.events
[eventName
] = handlers
[eventName
];
248 this.plugins_
.push(pluginDict
);
251 // At this point, plugins can no longer register event handlers.
252 // Construct a map from event -> ordered list of [callback, plugin].
253 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
254 var plugin_dict
= this.plugins_
[i
];
255 for (var eventName
in plugin_dict
.events
) {
256 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
257 var callback
= plugin_dict
.events
[eventName
];
259 var pair
= [plugin_dict
.plugin
, callback
];
260 if (!(eventName
in this.eventListeners_
)) {
261 this.eventListeners_
[eventName
] = [pair
];
263 this.eventListeners_
[eventName
].push(pair
);
268 this.createDragInterface_();
274 * Triggers a cascade of events to the various plugins which are interested in them.
275 * Returns true if the "default behavior" should be prevented, i.e. if one
276 * of the event listeners called event.preventDefault().
279 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
280 if (!(name
in this.eventListeners_
)) return false;
282 // QUESTION: can we use objects & prototypes to speed this up?
286 defaultPrevented
: false,
287 preventDefault
: function() {
288 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
289 e
.defaultPrevented
= true;
291 propagationStopped
: false,
292 stopPropagation
: function() {
293 e
.propagationStopped
= true;
296 utils
.update(e
, extra_props
);
298 var callback_plugin_pairs
= this.eventListeners_
[name
];
299 if (callback_plugin_pairs
) {
300 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
301 var plugin
= callback_plugin_pairs
[i
][0];
302 var callback
= callback_plugin_pairs
[i
][1];
303 callback
.call(plugin
, e
);
304 if (e
.propagationStopped
) break;
307 return e
.defaultPrevented
;
311 * Fetch a plugin instance of a particular class. Only for testing.
313 * @param {!Class} type The type of the plugin.
314 * @return {Object} Instance of the plugin, or null if there is none.
316 Dygraph
.prototype.getPluginInstance_
= function(type
) {
317 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
318 var p
= this.plugins_
[i
];
319 if (p
.plugin
instanceof type
) {
327 * Returns the zoomed status of the chart for one or both axes.
329 * Axis is an optional parameter. Can be set to 'x' or 'y'.
331 * The zoomed status for an axis is set whenever a user zooms using the mouse
332 * or when the dateWindow or valueRange are updated (unless the
333 * isZoomedIgnoreProgrammaticZoom option is also specified).
335 Dygraph
.prototype.isZoomed
= function(axis
) {
336 if (axis
=== null || axis
=== undefined
) {
337 return this.zoomed_x_
|| this.zoomed_y_
;
339 if (axis
=== 'x') return this.zoomed_x_
;
340 if (axis
=== 'y') return this.zoomed_y_
;
341 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
345 * Returns information about the Dygraph object, including its containing ID.
347 Dygraph
.prototype.toString
= function() {
348 var maindiv
= this.maindiv_
;
349 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
350 return "[Dygraph " + id
+ "]";
355 * Returns the value of an option. This may be set by the user (either in the
356 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
358 * @param {string} name The name of the option, e.g. 'rollPeriod'.
359 * @param {string} [seriesName] The name of the series to which the option
360 * will be applied. If no per-series value of this option is available, then
361 * the global value is returned. This is optional.
362 * @return { ... } The value of the option.
364 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
366 // if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
367 // console.error('Must include options reference JS for testing');
368 // } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
369 // console.error('Dygraphs is using property ' + name + ', which has no ' +
370 // 'entry in the Dygraphs.OPTIONS_REFERENCE listing.');
371 // // Only log
this error once
.
372 // Dygraph.OPTIONS_REFERENCE[name] = true;
375 return seriesName
? this.attributes_
.getForSeries(name
, seriesName
) : this.attributes_
.get(name
);
379 * Returns the current value for an option, as set in the constructor or via
380 * updateOptions. You may pass in an (optional) series name to get per-series
381 * values for the option.
383 * All values returned by this method should be considered immutable. If you
384 * modify them, there is no guarantee that the changes will be honored or that
385 * dygraphs will remain in a consistent state. If you want to modify an option,
386 * use updateOptions() instead.
388 * @param {string} name The name of the option (e.g. 'strokeWidth')
389 * @param {string=} opt_seriesName Series name to get per-series values.
390 * @return {*} The value of the option.
392 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
393 return this.attr_(name
, opt_seriesName
);
397 * Like getOption(), but specifically returns a number.
398 * This is a convenience function for working with the Closure Compiler.
399 * @param {string} name The name of the option (e.g. 'strokeWidth')
400 * @param {string=} opt_seriesName Series name to get per-series values.
401 * @return {number} The value of the option.
404 Dygraph
.prototype.getNumericOption
= function(name
, opt_seriesName
) {
405 return /** @type{number} */(this.getOption(name
, opt_seriesName
));
409 * Like getOption(), but specifically returns a string.
410 * This is a convenience function for working with the Closure Compiler.
411 * @param {string} name The name of the option (e.g. 'strokeWidth')
412 * @param {string=} opt_seriesName Series name to get per-series values.
413 * @return {string} The value of the option.
416 Dygraph
.prototype.getStringOption
= function(name
, opt_seriesName
) {
417 return /** @type{string} */(this.getOption(name
, opt_seriesName
));
421 * Like getOption(), but specifically returns a boolean.
422 * This is a convenience function for working with the Closure Compiler.
423 * @param {string} name The name of the option (e.g. 'strokeWidth')
424 * @param {string=} opt_seriesName Series name to get per-series values.
425 * @return {boolean} The value of the option.
428 Dygraph
.prototype.getBooleanOption
= function(name
, opt_seriesName
) {
429 return /** @type{boolean} */(this.getOption(name
, opt_seriesName
));
433 * Like getOption(), but specifically returns a function.
434 * This is a convenience function for working with the Closure Compiler.
435 * @param {string} name The name of the option (e.g. 'strokeWidth')
436 * @param {string=} opt_seriesName Series name to get per-series values.
437 * @return {function(...)} The value of the option.
440 Dygraph
.prototype.getFunctionOption
= function(name
, opt_seriesName
) {
441 return /** @type{function(...)} */(this.getOption(name
, opt_seriesName
));
444 Dygraph
.prototype.getOptionForAxis
= function(name
, axis
) {
445 return this.attributes_
.getForAxis(name
, axis
);
450 * @param {string} axis The name of the axis (i.e. 'x', 'y' or 'y2')
451 * @return { ... } A function mapping string -> option value
453 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
455 return function(opt
) {
456 var axis_opts
= self
.user_attrs_
.axes
;
457 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
458 return axis_opts
[axis
][opt
];
461 // I don't like that this is in a second spot.
462 if (axis
=== 'x' && opt
=== 'logscale') {
463 // return the default value.
464 // TODO(konigsberg): pull the default from a global default.
468 // user-specified attributes always trump defaults, even if they're less
470 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
471 return self
.user_attrs_
[opt
];
474 axis_opts
= self
.attrs_
.axes
;
475 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
476 return axis_opts
[axis
][opt
];
478 // check old-style axis options
479 // TODO(danvk): add a deprecation warning if either of these match.
480 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
481 return self
.axes_
[0][opt
];
482 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
483 return self
.axes_
[1][opt
];
485 return self
.attr_(opt
);
490 * Returns the current rolling period, as set by the user or an option.
491 * @return {number} The number of points in the rolling window
493 Dygraph
.prototype.rollPeriod
= function() {
494 return this.rollPeriod_
;
498 * Returns the currently-visible x-range. This can be affected by zooming,
499 * panning or a call to updateOptions.
500 * Returns a two-element array: [left, right].
501 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
503 Dygraph
.prototype.xAxisRange
= function() {
504 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
508 * Returns the lower- and upper-bound x-axis values of the
511 Dygraph
.prototype.xAxisExtremes
= function() {
512 var pad
= this.getNumericOption('xRangePad') / this.plotter_
.area
.w
;
513 if (this.numRows() === 0) {
514 return [0 - pad
, 1 + pad
];
516 var left
= this.rawData_
[0][0];
517 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
519 // Must keep this in sync with dygraph-layout _evaluateLimits()
520 var range
= right
- left
;
522 right
+= range
* pad
;
524 return [left
, right
];
528 * Returns the currently-visible y-range for an axis. This can be affected by
529 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
530 * called with no arguments, returns the range of the first axis.
531 * Returns a two-element array: [bottom, top].
533 Dygraph
.prototype.yAxisRange
= function(idx
) {
534 if (typeof(idx
) == "undefined") idx
= 0;
535 if (idx
< 0 || idx
>= this.axes_
.length
) {
538 var axis
= this.axes_
[idx
];
539 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
543 * Returns the currently-visible y-ranges for each axis. This can be affected by
544 * zooming, panning, calls to updateOptions, etc.
545 * Returns an array of [bottom, top] pairs, one for each y-axis.
547 Dygraph
.prototype.yAxisRanges
= function() {
549 for (var i
= 0; i
< this.axes_
.length
; i
++) {
550 ret
.push(this.yAxisRange(i
));
555 // TODO(danvk): use these functions throughout dygraphs.
557 * Convert from data coordinates to canvas/div X/Y coordinates.
558 * If specified, do this conversion for the coordinate system of a particular
559 * axis. Uses the first axis by default.
560 * Returns a two-element array: [X, Y]
562 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
563 * instead of toDomCoords(null, y, axis).
565 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
566 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
570 * Convert from data x coordinates to canvas/div X coordinate.
571 * If specified, do this conversion for the coordinate system of a particular
573 * Returns a single value or null if x is null.
575 Dygraph
.prototype.toDomXCoord
= function(x
) {
580 var area
= this.plotter_
.area
;
581 var xRange
= this.xAxisRange();
582 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
586 * Convert from data x coordinates to canvas/div Y coordinate and optional
587 * axis. Uses the first axis by default.
589 * returns a single value or null if y is null.
591 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
592 var pct
= this.toPercentYCoord(y
, axis
);
597 var area
= this.plotter_
.area
;
598 return area
.y
+ pct
* area
.h
;
602 * Convert from canvas/div coords to data coordinates.
603 * If specified, do this conversion for the coordinate system of a particular
604 * axis. Uses the first axis by default.
605 * Returns a two-element array: [X, Y].
607 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
608 * instead of toDataCoords(null, y, axis).
610 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
611 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
615 * Convert from canvas/div x coordinate to data coordinate.
617 * If x is null, this returns null.
619 Dygraph
.prototype.toDataXCoord
= function(x
) {
624 var area
= this.plotter_
.area
;
625 var xRange
= this.xAxisRange();
627 if (!this.attributes_
.getForAxis("logscale", 'x')) {
628 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
630 // TODO: remove duplicate code?
631 // Computing the inverse of toDomCoord.
632 var pct
= (x
- area
.x
) / area
.w
;
634 // Computing the inverse of toPercentXCoord. The function was arrived at with
635 // the following steps:
637 // Original calcuation:
638 // pct = (log(x) - log(xRange[0])) / (log(xRange
[1]) - log(xRange
[0])));
640 // Multiply both sides by the right-side demoninator.
641 // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0])
643 // add log(xRange[0]) to both sides
644 // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) = log(x);
646 // Swap both sides of the equation,
647 // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))
649 // Use both sides as the exponent in 10^exp and we're done.
650 // x = 10 ^ (log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])))
651 var logr0
= Dygraph
.log10(xRange
[0]);
652 var logr1
= Dygraph
.log10(xRange
[1]);
653 var exponent
= logr0
+ (pct
* (logr1
- logr0
));
654 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
660 * Convert from canvas/div y coord to value.
662 * If y is null, this returns null.
663 * if axis is null, this uses the first axis.
665 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
670 var area
= this.plotter_
.area
;
671 var yRange
= this.yAxisRange(axis
);
673 if (typeof(axis
) == "undefined") axis
= 0;
674 if (!this.attributes_
.getForAxis("logscale", axis
)) {
675 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
677 // Computing the inverse of toDomCoord.
678 var pct
= (y
- area
.y
) / area
.h
;
680 // Computing the inverse of toPercentYCoord. The function was arrived at with
681 // the following steps:
683 // Original calcuation:
684 // pct = (log(yRange[1]) - log(y)) / (log(yRange
[1]) - log(yRange
[0]));
686 // Multiply both sides by the right-side demoninator.
687 // pct * (log(yRange[1]) - log(yRange[0])) = log(yRange[1]) - log(y);
689 // subtract log(yRange[1]) from both sides.
690 // (pct * (log(yRange[1]) - log(yRange[0]))) - log(yRange[1]) = -log(y);
692 // and multiply both sides by -1.
693 // log(yRange[1]) - (pct * (logr1 - log(yRange[0])) = log(y);
695 // Swap both sides of the equation,
696 // log(y) = log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0])));
698 // Use both sides as the exponent in 10^exp and we're done.
699 // y = 10 ^ (log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0]))));
700 var logr0
= Dygraph
.log10(yRange
[0]);
701 var logr1
= Dygraph
.log10(yRange
[1]);
702 var exponent
= logr1
- (pct
* (logr1
- logr0
));
703 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
709 * Converts a y for an axis to a percentage from the top to the
710 * bottom of the drawing area.
712 * If the coordinate represents a value visible on the canvas, then
713 * the value will be between 0 and 1, where 0 is the top of the canvas.
714 * However, this method will return values outside the range, as
715 * values can fall outside the canvas.
717 * If y is null, this returns null.
718 * if axis is null, this uses the first axis.
720 * @param {number} y The data y-coordinate.
721 * @param {number} [axis] The axis number on which the data coordinate lives.
722 * @return {number} A fraction in [0, 1] where 0 = the top edge.
724 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
728 if (typeof(axis
) == "undefined") axis
= 0;
730 var yRange
= this.yAxisRange(axis
);
733 var logscale
= this.attributes_
.getForAxis("logscale", axis
);
735 var logr0
= Dygraph
.log10(yRange
[0]);
736 var logr1
= Dygraph
.log10(yRange
[1]);
737 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- logr0
);
739 // yRange[1] - y is unit distance from the bottom.
740 // yRange[1] - yRange[0] is the scale of the range.
741 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
742 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
748 * Converts an x value to a percentage from the left to the right of
751 * If the coordinate represents a value visible on the canvas, then
752 * the value will be between 0 and 1, where 0 is the left of the canvas.
753 * However, this method will return values outside the range, as
754 * values can fall outside the canvas.
756 * If x is null, this returns null.
757 * @param {number} x The data x-coordinate.
758 * @return {number} A fraction in [0, 1] where 0 = the left edge.
760 Dygraph
.prototype.toPercentXCoord
= function(x
) {
765 var xRange
= this.xAxisRange();
767 var logscale
= this.attributes_
.getForAxis("logscale", 'x') ;
768 if (logscale
=== true) { // logscale can be null so we test for true explicitly.
769 var logr0
= Dygraph
.log10(xRange
[0]);
770 var logr1
= Dygraph
.log10(xRange
[1]);
771 pct
= (Dygraph
.log10(x
) - logr0
) / (logr1
- logr0
);
773 // x - xRange[0] is unit distance from the left.
774 // xRange[1] - xRange[0] is the scale of the range.
775 // The full expression below is the % from the left.
776 pct
= (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
782 * Returns the number of columns (including the independent variable).
783 * @return {number} The number of columns.
785 Dygraph
.prototype.numColumns
= function() {
786 if (!this.rawData_
) return 0;
787 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
791 * Returns the number of rows (excluding any header/label row).
792 * @return {number} The number of rows, less any header.
794 Dygraph
.prototype.numRows
= function() {
795 if (!this.rawData_
) return 0;
796 return this.rawData_
.length
;
800 * Returns the value in the given row and column. If the row and column exceed
801 * the bounds on the data, returns null. Also returns null if the value is
803 * @param {number} row The row number of the data (0-based). Row 0 is the
804 * first row of data, not a header row.
805 * @param {number} col The column number of the data (0-based)
806 * @return {number} The value in the specified cell or null if the row/col
809 Dygraph
.prototype.getValue
= function(row
, col
) {
810 if (row
< 0 || row
> this.rawData_
.length
) return null;
811 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
813 return this.rawData_
[row
][col
];
817 * Generates interface elements for the Dygraph: a containing div, a div to
818 * display the current point, and a textbox to adjust the rolling average
819 * period. Also creates the Renderer/Layout elements.
822 Dygraph
.prototype.createInterface_
= function() {
823 // Create the all-enclosing graph div
824 var enclosing
= this.maindiv_
;
826 this.graphDiv
= document
.createElement("div");
828 // TODO(danvk): any other styles that are useful to set here?
829 this.graphDiv
.style
.textAlign
= 'left'; // This is a CSS "reset"
830 this.graphDiv
.style
.position
= 'relative';
831 enclosing
.appendChild(this.graphDiv
);
833 // Create the canvas for interactive parts of the chart.
834 this.canvas_
= utils
.createCanvas();
835 this.canvas_
.style
.position
= "absolute";
837 // ... and for static parts of the chart.
838 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
840 this.canvas_ctx_
= utils
.getContext(this.canvas_
);
841 this.hidden_ctx_
= utils
.getContext(this.hidden_
);
843 this.resizeElements_();
845 // The interactive parts of the graph are drawn on top of the chart.
846 this.graphDiv
.appendChild(this.hidden_
);
847 this.graphDiv
.appendChild(this.canvas_
);
848 this.mouseEventElement_
= this.createMouseEventElement_();
850 // Create the grapher
851 this.layout_
= new DygraphLayout(this);
855 this.mouseMoveHandler_
= function(e
) {
856 dygraph
.mouseMove_(e
);
859 this.mouseOutHandler_
= function(e
) {
860 // The mouse has left the chart if:
861 // 1. e.target is inside the chart
862 // 2. e.relatedTarget is outside the chart
863 var target
= e
.target
|| e
.fromElement
;
864 var relatedTarget
= e
.relatedTarget
|| e
.toElement
;
865 if (utils
.isNodeContainedBy(target
, dygraph
.graphDiv
) &&
866 !utils
.isNodeContainedBy(relatedTarget
, dygraph
.graphDiv
)) {
867 dygraph
.mouseOut_(e
);
871 this.addAndTrackEvent(window
, 'mouseout', this.mouseOutHandler_
);
872 this.addAndTrackEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
874 // Don't recreate and register the resize handler on subsequent calls.
875 // This happens when the graph is resized.
876 if (!this.resizeHandler_
) {
877 this.resizeHandler_
= function(e
) {
881 // Update when the window is resized.
882 // TODO(danvk): drop frames depending on complexity of the chart.
883 this.addAndTrackEvent(window
, 'resize', this.resizeHandler_
);
887 Dygraph
.prototype.resizeElements_
= function() {
888 this.graphDiv
.style
.width
= this.width_
+ "px";
889 this.graphDiv
.style
.height
= this.height_
+ "px";
891 var canvasScale
= utils
.getContextPixelRatio(this.canvas_ctx_
);
892 this.canvas_
.width
= this.width_
* canvasScale
;
893 this.canvas_
.height
= this.height_
* canvasScale
;
894 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
895 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
896 if (canvasScale
!== 1) {
897 this.canvas_ctx_
.scale(canvasScale
, canvasScale
);
900 var hiddenScale
= utils
.getContextPixelRatio(this.hidden_ctx_
);
901 this.hidden_
.width
= this.width_
* hiddenScale
;
902 this.hidden_
.height
= this.height_
* hiddenScale
;
903 this.hidden_
.style
.width
= this.width_
+ "px"; // for IE
904 this.hidden_
.style
.height
= this.height_
+ "px"; // for IE
905 if (hiddenScale
!== 1) {
906 this.hidden_ctx_
.scale(hiddenScale
, hiddenScale
);
911 * Detach DOM elements in the dygraph and null out all data references.
912 * Calling this when you're done with a dygraph can dramatically reduce memory
913 * usage. See, e.g., the tests/perf.html example.
915 Dygraph
.prototype.destroy
= function() {
916 this.canvas_ctx_
.restore();
917 this.hidden_ctx_
.restore();
919 // Destroy any plugins, in the reverse order that they were registered.
920 for (var i
= this.plugins_
.length
- 1; i
>= 0; i
--) {
921 var p
= this.plugins_
.pop();
922 if (p
.plugin
.destroy
) p
.plugin
.destroy();
925 var removeRecursive
= function(node
) {
926 while (node
.hasChildNodes()) {
927 removeRecursive(node
.firstChild
);
928 node
.removeChild(node
.firstChild
);
932 this.removeTrackedEvents_();
934 // remove mouse event handlers (This may not be necessary anymore)
935 Dygraph
.removeEvent(window
, 'mouseout', this.mouseOutHandler_
);
936 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
938 // remove window handlers
939 Dygraph
.removeEvent(window
,'resize', this.resizeHandler_
);
940 this.resizeHandler_
= null;
942 removeRecursive(this.maindiv_
);
944 var nullOut
= function(obj
) {
946 if (typeof(obj
[n
]) === 'object') {
951 // These may not all be necessary, but it can't hurt...
952 nullOut(this.layout_
);
953 nullOut(this.plotter_
);
958 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
959 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
960 * or the zoom rectangles) is done on this.canvas_.
961 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
962 * @return {Object} The newly-created canvas
965 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
966 var h
= utils
.createCanvas();
967 h
.style
.position
= "absolute";
968 // TODO(danvk): h should be offset from canvas. canvas needs to include
969 // some extra area to make it easier to zoom in on the far left and far
970 // right. h needs to be precisely the plot area, so that clipping occurs.
971 h
.style
.top
= canvas
.style
.top
;
972 h
.style
.left
= canvas
.style
.left
;
973 h
.width
= this.width_
;
974 h
.height
= this.height_
;
975 h
.style
.width
= this.width_
+ "px"; // for IE
976 h
.style
.height
= this.height_
+ "px"; // for IE
981 * Creates an overlay element used to handle mouse events.
982 * @return {Object} The mouse event element.
985 Dygraph
.prototype.createMouseEventElement_
= function() {
990 * Generate a set of distinct colors for the data series. This is done with a
991 * color wheel. Saturation/Value are customizable, and the hue is
992 * equally-spaced around the color wheel. If a custom set of colors is
993 * specified, that is used instead.
996 Dygraph
.prototype.setColors_
= function() {
997 var labels
= this.getLabels();
998 var num
= labels
.length
- 1;
1000 this.colorsMap_
= {};
1002 // These are used for when no custom colors are specified.
1003 var sat
= this.getNumericOption('colorSaturation') || 1.0;
1004 var val
= this.getNumericOption('colorValue') || 0.5;
1005 var half
= Math
.ceil(num
/ 2);
1007 var colors
= this.getOption('colors');
1008 var visibility
= this.visibility();
1009 for (var i
= 0; i
< num
; i
++) {
1010 if (!visibility
[i
]) {
1013 var label
= labels
[i
+ 1];
1014 var colorStr
= this.attributes_
.getForSeries('color', label
);
1017 colorStr
= colors
[i
% colors
.length
];
1019 // alternate colors for high contrast.
1020 var idx
= i
% 2 ? (half
+ (i
+ 1)/ 2) : Math.ceil((i + 1) / 2);
1021 var hue
= (1.0 * idx
/ (1 + num
));
1022 colorStr
= Dygraph
.hsvToRGB(hue
, sat
, val
);
1025 this.colors_
.push(colorStr
);
1026 this.colorsMap_
[label
] = colorStr
;
1031 * Return the list of colors. This is either the list of colors passed in the
1032 * attributes or the autogenerated list of rgb(r,g,b) strings.
1033 * This does not return colors for invisible series.
1034 * @return {Array.<string>} The list of colors.
1036 Dygraph
.prototype.getColors
= function() {
1037 return this.colors_
;
1041 * Returns a few attributes of a series, i.e. its color, its visibility, which
1042 * axis it's assigned to, and its column in the original data.
1043 * Returns null if the series does not exist.
1044 * Otherwise, returns an object with column, visibility, color and axis properties.
1045 * The "axis" property will be set to 1 for y1 and 2 for y2.
1046 * The "column" property can be fed back into getValue(row, column) to get
1047 * values for this series.
1049 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1051 var labels
= this.getLabels();
1052 for (var i
= 1; i
< labels
.length
; i
++) {
1053 if (labels
[i
] == series_name
) {
1058 if (idx
== -1) return null;
1063 visible
: this.visibility()[idx
- 1],
1064 color
: this.colorsMap_
[series_name
],
1065 axis
: 1 + this.attributes_
.axisForSeries(series_name
)
1070 * Create the text box to adjust the averaging period
1073 Dygraph
.prototype.createRollInterface_
= function() {
1074 // Create a roller if one doesn't exist already.
1075 if (!this.roller_
) {
1076 this.roller_
= document
.createElement("input");
1077 this.roller_
.type
= "text";
1078 this.roller_
.style
.display
= "none";
1079 this.graphDiv
.appendChild(this.roller_
);
1082 var display
= this.getBooleanOption('showRoller') ? 'block' : 'none';
1084 var area
= this.plotter_
.area
;
1085 var textAttr
= { "position": "absolute",
1087 "top": (area
.y
+ area
.h
- 25) + "px",
1088 "left": (area
.x
+ 1) + "px",
1091 this.roller_
.size
= "2";
1092 this.roller_
.value
= this.rollPeriod_
;
1093 for (var name
in textAttr
) {
1094 if (textAttr
.hasOwnProperty(name
)) {
1095 this.roller_
.style
[name
] = textAttr
[name
];
1100 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1104 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1108 Dygraph
.prototype.createDragInterface_
= function() {
1110 // Tracks whether the mouse is down right now
1112 isPanning
: false, // is this drag part of a pan?
1113 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1114 dragStartX
: null, // pixel coordinates
1115 dragStartY
: null, // pixel coordinates
1116 dragEndX
: null, // pixel coordinates
1117 dragEndY
: null, // pixel coordinates
1118 dragDirection
: null,
1119 prevEndX
: null, // pixel coordinates
1120 prevEndY
: null, // pixel coordinates
1121 prevDragDirection
: null,
1122 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1124 // The value on the left side of the graph when a pan operation starts.
1125 initialLeftmostDate
: null,
1127 // The number of units each pixel spans. (This won't be valid for log
1129 xUnitsPerPixel
: null,
1131 // TODO(danvk): update this comment
1132 // The range in second/value units that the viewport encompasses during a
1133 // panning operation.
1136 // Top-left corner of the canvas, in DOM coords
1137 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1141 // Values for use with panEdgeFraction, which limit how far outside the
1142 // graph's data boundaries it can be panned.
1143 boundedDates
: null, // [minDate, maxDate]
1144 boundedValues
: null, // [[minValue, maxValue] ...]
1146 // We cover iframes during mouse interactions. See comments in
1147 // dygraph-utils.js for more info on why this is a good idea.
1148 tarp
: new utils
.IFrameTarp(),
1150 // contextB is the same thing as this context object but renamed.
1151 initializeMouseDown
: function(event
, g
, contextB
) {
1152 // prevents mouse drags from selecting page text.
1153 if (event
.preventDefault
) {
1154 event
.preventDefault(); // Firefox, Chrome, etc.
1156 event
.returnValue
= false; // IE
1157 event
.cancelBubble
= true;
1160 var canvasPos
= utils
.findPos(g
.canvas_
);
1161 contextB
.px
= canvasPos
.x
;
1162 contextB
.py
= canvasPos
.y
;
1163 contextB
.dragStartX
= utils
.dragGetX_(event
, contextB
);
1164 contextB
.dragStartY
= utils
.dragGetY_(event
, contextB
);
1165 contextB
.cancelNextDblclick
= false;
1166 contextB
.tarp
.cover();
1168 destroy
: function() {
1170 if (context
.isZooming
|| context
.isPanning
) {
1171 context
.isZooming
= false;
1172 context
.dragStartX
= null;
1173 context
.dragStartY
= null;
1176 if (context
.isPanning
) {
1177 context
.isPanning
= false;
1178 context
.draggingDate
= null;
1179 context
.dateRange
= null;
1180 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1181 delete self
.axes_
[i
].draggingValue
;
1182 delete self
.axes_
[i
].dragValueRange
;
1186 context
.tarp
.uncover();
1190 var interactionModel
= this.getOption("interactionModel");
1192 // Self is the graph.
1195 // Function that binds the graph and context to the handler.
1196 var bindHandler
= function(handler
) {
1197 return function(event
) {
1198 handler(event
, self
, context
);
1202 for (var eventName
in interactionModel
) {
1203 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1204 this.addAndTrackEvent(this.mouseEventElement_
, eventName
,
1205 bindHandler(interactionModel
[eventName
]));
1208 // If the user releases the mouse button during a drag, but not over the
1209 // canvas, then it doesn't count as a zooming action.
1210 if (!interactionModel
.willDestroyContextMyself
) {
1211 var mouseUpHandler
= function(event
) {
1215 this.addAndTrackEvent(document
, 'mouseup', mouseUpHandler
);
1220 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1221 * up any previous zoom rectangles that were drawn. This could be optimized to
1222 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1225 * @param {number} direction the direction of the zoom rectangle. Acceptable
1226 * values are utils.HORIZONTAL and utils.VERTICAL.
1227 * @param {number} startX The X position where the drag started, in canvas
1229 * @param {number} endX The current X position of the drag, in canvas coords.
1230 * @param {number} startY The Y position where the drag started, in canvas
1232 * @param {number} endY The current Y position of the drag, in canvas coords.
1233 * @param {number} prevDirection the value of direction on the previous call to
1234 * this function. Used to avoid excess redrawing
1235 * @param {number} prevEndX The value of endX on the previous call to this
1236 * function. Used to avoid excess redrawing
1237 * @param {number} prevEndY The value of endY on the previous call to this
1238 * function. Used to avoid excess redrawing
1241 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1242 endY
, prevDirection
, prevEndX
,
1244 var ctx
= this.canvas_ctx_
;
1246 // Clean up from the previous rect if necessary
1247 if (prevDirection
== utils
.HORIZONTAL
) {
1248 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1249 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1250 } else if (prevDirection
== utils
.VERTICAL
) {
1251 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1252 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1255 // Draw a light-grey rectangle to show the new viewing area
1256 if (direction
== utils
.HORIZONTAL
) {
1257 if (endX
&& startX
) {
1258 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1259 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1260 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1262 } else if (direction
== utils
.VERTICAL
) {
1263 if (endY
&& startY
) {
1264 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1265 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1266 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1272 * Clear the zoom rectangle (and perform no zoom).
1275 Dygraph
.prototype.clearZoomRect_
= function() {
1276 this.currentZoomRectArgs_
= null;
1277 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1281 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1282 * the canvas. The exact zoom window may be slightly larger if there are no data
1283 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1284 * which accepts dates that match the raw data. This function redraws the graph.
1286 * @param {number} lowX The leftmost pixel value that should be visible.
1287 * @param {number} highX The rightmost pixel value that should be visible.
1290 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1291 this.currentZoomRectArgs_
= null;
1292 // Find the earliest and latest dates contained in this canvasx range.
1293 // Convert the call to date ranges of the raw data.
1294 var minDate
= this.toDataXCoord(lowX
);
1295 var maxDate
= this.toDataXCoord(highX
);
1296 this.doZoomXDates_(minDate
, maxDate
);
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 xAxisRange is null (i.e. "fit to data", the animation
1310 // can produce strange effects. Rather than the x-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
.getFunctionOption("zoomCallback")) {
1318 that
.getFunctionOption("zoomCallback").call(that
,
1319 minDate
, maxDate
, that
.yAxisRanges());
1325 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1326 * the canvas. This function redraws the graph.
1328 * @param {number} lowY The topmost pixel value that should be visible.
1329 * @param {number} highY The lowest pixel value that should be visible.
1332 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1333 this.currentZoomRectArgs_
= null;
1334 // Find the highest and lowest values in pixel range for each axis.
1335 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1336 // This is because pixels increase as you go down on the screen, whereas data
1337 // coordinates increase as you go up the screen.
1338 var oldValueRanges
= this.yAxisRanges();
1339 var newValueRanges
= [];
1340 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1341 var hi
= this.toDataYCoord(lowY
, i
);
1342 var low
= this.toDataYCoord(highY
, i
);
1343 newValueRanges
.push([low
, hi
]);
1346 this.zoomed_y_
= true;
1348 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1349 if (that
.getFunctionOption("zoomCallback")) {
1350 var xRange
= that
.xAxisRange();
1351 that
.getFunctionOption("zoomCallback").call(that
,
1352 xRange
[0], xRange
[1], that
.yAxisRanges());
1358 * Transition function to use in animations. Returns values between 0.0
1359 * (totally old values) and 1.0 (totally new values) for each frame.
1362 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1364 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1368 * Reset the zoom to the original view coordinates. This is the same as
1369 * double-clicking on the graph.
1371 Dygraph
.prototype.resetZoom
= function() {
1372 var dirty
= false, dirtyX
= false, dirtyY
= false;
1373 if (this.dateWindow_
!== null) {
1378 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1379 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1385 // Clear any selection, since it's likely to be drawn in the wrong place.
1386 this.clearSelection();
1389 this.zoomed_x_
= false;
1390 this.zoomed_y_
= false;
1392 //calculate extremes to avoid lack of padding on reset.
1393 var extremes
= this.xAxisExtremes();
1394 var minDate
= extremes
[0],
1395 maxDate
= extremes
[1];
1397 // TODO(danvk): merge this block w/ the code below
.
1398 if (!this.getBooleanOption("animatedZooms")) {
1399 this.dateWindow_
= null;
1400 for (i
= 0; i
< this.axes_
.length
; i
++) {
1401 if (this.axes_
[i
].valueWindow
!== null) {
1402 delete this.axes_
[i
].valueWindow
;
1406 if (this.getFunctionOption("zoomCallback")) {
1407 this.getFunctionOption("zoomCallback").call(this,
1408 minDate
, maxDate
, this.yAxisRanges());
1413 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1415 oldWindow
= this.xAxisRange();
1416 newWindow
= [minDate
, maxDate
];
1420 oldValueRanges
= this.yAxisRanges();
1421 // TODO(danvk): this is pretty inefficient
1422 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1423 var extremes
= packed
.extremes
;
1425 // this has the side-effect of modifying this.axes_.
1426 // this doesn't make much sense in this context, but it's convenient (we
1427 // need this.axes_[*].extremeValues) and not harmful since we'll be
1428 // calling drawGraph_ shortly, which clobbers these values.
1429 this.computeYAxisRanges_(extremes
);
1431 newValueRanges
= [];
1432 for (i
= 0; i
< this.axes_
.length
; i
++) {
1433 var axis
= this.axes_
[i
];
1434 newValueRanges
.push((axis
.valueRange
!== null &&
1435 axis
.valueRange
!== undefined
) ?
1436 axis
.valueRange
: axis
.extremeRange
);
1441 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1443 that
.dateWindow_
= null;
1444 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1445 if (that
.axes_
[i
].valueWindow
!== null) {
1446 delete that
.axes_
[i
].valueWindow
;
1449 if (that
.getFunctionOption("zoomCallback")) {
1450 that
.getFunctionOption("zoomCallback").call(that
,
1451 minDate
, maxDate
, that
.yAxisRanges());
1458 * Combined animation logic for all zoom functions.
1459 * either the x parameters or y parameters may be null.
1462 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1463 var steps
= this.getBooleanOption("animatedZooms") ?
1464 Dygraph
.ANIMATION_STEPS
: 1;
1467 var valueRanges
= [];
1470 if (oldXRange
!== null && newXRange
!== null) {
1471 for (step
= 1; step
<= steps
; step
++) {
1472 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1473 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1474 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1478 if (oldYRanges
!== null && newYRanges
!== null) {
1479 for (step
= 1; step
<= steps
; step
++) {
1480 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1482 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1483 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1484 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1486 valueRanges
[step
-1] = thisRange
;
1491 utils
.repeatAndCleanup(function(step
) {
1492 if (valueRanges
.length
) {
1493 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1494 var w
= valueRanges
[step
][i
];
1495 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1498 if (windows
.length
) {
1499 that
.dateWindow_
= windows
[step
];
1502 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1506 * Get the current graph's area object.
1508 * Returns: {x, y, w, h}
1510 Dygraph
.prototype.getArea
= function() {
1511 return this.plotter_
.area
;
1515 * Convert a mouse event to DOM coordinates relative to the graph origin.
1517 * Returns a two-element array: [X, Y].
1519 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1520 if (event
.offsetX
&& event
.offsetY
) {
1521 return [ event
.offsetX
, event
.offsetY
];
1523 var eventElementPos
= utils
.findPos(this.mouseEventElement_
);
1524 var canvasx
= utils
.pageX(event
) - eventElementPos
.x
;
1525 var canvasy
= utils
.pageY(event
) - eventElementPos
.y
;
1526 return [canvasx
, canvasy
];
1531 * Given a canvas X coordinate, find the closest row.
1532 * @param {number} domX graph-relative DOM X coordinate
1533 * Returns {number} row number.
1536 Dygraph
.prototype.findClosestRow
= function(domX
) {
1537 var minDistX
= Infinity
;
1538 var closestRow
= -1;
1539 var sets
= this.layout_
.points
;
1540 for (var i
= 0; i
< sets
.length
; i
++) {
1541 var points
= sets
[i
];
1542 var len
= points
.length
;
1543 for (var j
= 0; j
< len
; j
++) {
1544 var point
= points
[j
];
1545 if (!utils
.isValidPoint(point
, true)) continue;
1546 var dist
= Math
.abs(point
.canvasx
- domX
);
1547 if (dist
< minDistX
) {
1549 closestRow
= point
.idx
;
1558 * Given canvas X,Y coordinates, find the closest point.
1560 * This finds the individual data point across all visible series
1561 * that's closest to the supplied DOM coordinates using the standard
1562 * Euclidean X,Y distance.
1564 * @param {number} domX graph-relative DOM X coordinate
1565 * @param {number} domY graph-relative DOM Y coordinate
1566 * Returns: {row, seriesName, point}
1569 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1570 var minDist
= Infinity
;
1571 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
, closestRow
;
1572 for ( var setIdx
= this.layout_
.points
.length
- 1 ; setIdx
>= 0 ; --setIdx
) {
1573 var points
= this.layout_
.points
[setIdx
];
1574 for (var i
= 0; i
< points
.length
; ++i
) {
1576 if (!Dygraph
.isValidPoint(point
)) continue;
1577 dx
= point
.canvasx
- domX
;
1578 dy
= point
.canvasy
- domY
;
1579 dist
= dx
* dx
+ dy
* dy
;
1580 if (dist
< minDist
) {
1582 closestPoint
= point
;
1583 closestSeries
= setIdx
;
1584 closestRow
= point
.idx
;
1588 var name
= this.layout_
.setNames
[closestSeries
];
1597 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1599 * This first finds the X data point closest to the supplied DOM X coordinate,
1600 * then finds the series which puts the Y coordinate on top of its filled area,
1601 * using linear interpolation between adjacent point pairs.
1603 * @param {number} domX graph-relative DOM X coordinate
1604 * @param {number} domY graph-relative DOM Y coordinate
1605 * Returns: {row, seriesName, point}
1608 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1609 var row
= this.findClosestRow(domX
);
1610 var closestPoint
, closestSeries
;
1611 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
1612 var boundary
= this.getLeftBoundary_(setIdx
);
1613 var rowIdx
= row
- boundary
;
1614 var points
= this.layout_
.points
[setIdx
];
1615 if (rowIdx
>= points
.length
) continue;
1616 var p1
= points
[rowIdx
];
1617 if (!Dygraph
.isValidPoint(p1
)) continue;
1618 var py
= p1
.canvasy
;
1619 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < points
.length
) {
1620 // interpolate series Y value using next point
1621 var p2
= points
[rowIdx
+ 1];
1622 if (Dygraph
.isValidPoint(p2
)) {
1623 var dx
= p2
.canvasx
- p1
.canvasx
;
1625 var r
= (domX
- p1
.canvasx
) / dx
;
1626 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1629 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1630 // interpolate series Y value using previous point
1631 var p0
= points
[rowIdx
- 1];
1632 if (Dygraph
.isValidPoint(p0
)) {
1633 var dx
= p1
.canvasx
- p0
.canvasx
;
1635 var r
= (p1
.canvasx
- domX
) / dx
;
1636 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1640 // Stop if the point (domX, py) is above this series' upper edge
1641 if (setIdx
=== 0 || py
< domY
) {
1643 closestSeries
= setIdx
;
1646 var name
= this.layout_
.setNames
[closestSeries
];
1655 * When the mouse moves in the canvas, display information about a nearby data
1656 * point and draw dots over those points in the data series. This function
1657 * takes care of cleanup of previously-drawn dots.
1658 * @param {Object} event The mousemove event from the browser.
1661 Dygraph
.prototype.mouseMove_
= function(event
) {
1662 // This prevents JS errors when mousing over the canvas before data loads.
1663 var points
= this.layout_
.points
;
1664 if (points
=== undefined
|| points
=== null) return;
1666 var canvasCoords
= this.eventToDomCoords(event
);
1667 var canvasx
= canvasCoords
[0];
1668 var canvasy
= canvasCoords
[1];
1670 var highlightSeriesOpts
= this.getOption("highlightSeriesOpts");
1671 var selectionChanged
= false;
1672 if (highlightSeriesOpts
&& !this.isSeriesLocked()) {
1674 if (this.getBooleanOption("stackedGraph")) {
1675 closest
= this.findStackedPoint(canvasx
, canvasy
);
1677 closest
= this.findClosestPoint(canvasx
, canvasy
);
1679 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1681 var idx
= this.findClosestRow(canvasx
);
1682 selectionChanged
= this.setSelection(idx
);
1685 var callback
= this.getFunctionOption("highlightCallback");
1686 if (callback
&& selectionChanged
) {
1687 callback
.call(this, event
,
1691 this.highlightSet_
);
1696 * Fetch left offset from the specified set index or if not passed, the
1697 * first defined boundaryIds record (see bug #236).
1700 Dygraph
.prototype.getLeftBoundary_
= function(setIdx
) {
1701 if (this.boundaryIds_
[setIdx
]) {
1702 return this.boundaryIds_
[setIdx
][0];
1704 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1705 if (this.boundaryIds_
[i
] !== undefined
) {
1706 return this.boundaryIds_
[i
][0];
1713 Dygraph
.prototype.animateSelection_
= function(direction
) {
1714 var totalSteps
= 10;
1716 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1717 if (this.animateId
=== undefined
) this.animateId
= 0;
1718 var start
= this.fadeLevel
;
1719 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1721 if (this.fadeLevel
) {
1722 this.updateSelection_(1.0);
1727 var thisId
= ++this.animateId
;
1729 var cleanupIfClearing
= function() {
1730 // if we haven't reached fadeLevel 0 in the max frame time,
1731 // ensure that the clear happens and just go to 0
1732 if (that
.fadeLevel
!== 0 && direction
< 0) {
1734 that
.clearSelection();
1737 utils
.repeatAndCleanup(
1739 // ignore simultaneous animations
1740 if (that
.animateId
!= thisId
) return;
1742 that
.fadeLevel
+= direction
;
1743 if (that
.fadeLevel
=== 0) {
1744 that
.clearSelection();
1746 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1749 steps
, millis
, cleanupIfClearing
);
1753 * Draw dots over the selectied points in the data series. This function
1754 * takes care of cleanup of previously-drawn dots.
1757 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1758 /*var defaultPrevented = */
1759 this.cascadeEvents_('select', {
1760 selectedRow
: this.lastRow_
,
1761 selectedX
: this.lastx_
,
1762 selectedPoints
: this.selPoints_
1764 // TODO(danvk): use defaultPrevented here?
1766 // Clear the previously drawn vertical, if there is one
1768 var ctx
= this.canvas_ctx_
;
1769 if (this.getOption('highlightSeriesOpts')) {
1770 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1771 var alpha
= 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha');
1773 // Activating background fade includes an animation effect for a gradual
1774 // fade. TODO(klausw): make this independently configurable if it causes
1775 // issues? Use a shared preference to control animations?
1776 var animateBackgroundFade
= true;
1777 if (animateBackgroundFade
) {
1778 if (opt_animFraction
=== undefined
) {
1779 // start a new animation
1780 this.animateSelection_(1);
1783 alpha
*= opt_animFraction
;
1785 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1786 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1789 // Redraw only the highlighted series in the interactive canvas (not the
1790 // static plot canvas, which is where series are usually drawn).
1791 this.plotter_
._renderLineChart(this.highlightSet_
, ctx
);
1792 } else if (this.previousVerticalX_
>= 0) {
1793 // Determine the maximum highlight circle size.
1794 var maxCircleSize
= 0;
1795 var labels
= this.attr_('labels');
1796 for (i
= 1; i
< labels
.length
; i
++) {
1797 var r
= this.getNumericOption('highlightCircleSize', labels
[i
]);
1798 if (r
> maxCircleSize
) maxCircleSize
= r
;
1800 var px
= this.previousVerticalX_
;
1801 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1802 2 * maxCircleSize
+ 2, this.height_
);
1805 if (this.selPoints_
.length
> 0) {
1806 // Draw colored circles over the center of each selected point
1807 var canvasx
= this.selPoints_
[0].canvasx
;
1809 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1810 var pt
= this.selPoints_
[i
];
1811 if (!utils
.isOK(pt
.canvasy
)) continue;
1813 var circleSize
= this.getNumericOption('highlightCircleSize', pt
.name
);
1814 var callback
= this.getFunctionOption("drawHighlightPointCallback", pt
.name
);
1815 var color
= this.plotter_
.colors
[pt
.name
];
1817 callback
= utils
.Circles
.DEFAULT
;
1819 ctx
.lineWidth
= this.getNumericOption('strokeWidth', pt
.name
);
1820 ctx
.strokeStyle
= color
;
1821 ctx
.fillStyle
= color
;
1822 callback
.call(this, this, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1823 color
, circleSize
, pt
.idx
);
1827 this.previousVerticalX_
= canvasx
;
1832 * Manually set the selected points and display information about them in the
1833 * legend. The selection can be cleared using clearSelection() and queried
1834 * using getSelection().
1835 * @param {number} row Row number that should be highlighted (i.e. appear with
1836 * hover dots on the chart).
1837 * @param {seriesName} optional series name to highlight that series with the
1838 * the highlightSeriesOpts setting.
1839 * @param { locked } optional If true, keep seriesName selected when mousing
1840 * over the graph, disabling closest-series highlighting. Call clearSelection()
1843 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
, opt_locked
) {
1844 // Extract the points we've selected
1845 this.selPoints_
= [];
1847 var changed
= false;
1848 if (row
!== false && row
>= 0) {
1849 if (row
!= this.lastRow_
) changed
= true;
1850 this.lastRow_
= row
;
1851 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
1852 var points
= this.layout_
.points
[setIdx
];
1853 // Check if the point at the appropriate index is the point we're looking
1854 // for. If it is, just use it, otherwise search the array for a point
1855 // in the proper place.
1856 var setRow
= row
- this.getLeftBoundary_(setIdx
);
1857 if (setRow
< points
.length
&& points
[setRow
].idx
== row
) {
1858 var point
= points
[setRow
];
1859 if (point
.yval
!== null) this.selPoints_
.push(point
);
1861 for (var pointIdx
= 0; pointIdx
< points
.length
; ++pointIdx
) {
1862 var point
= points
[pointIdx
];
1863 if (point
.idx
== row
) {
1864 if (point
.yval
!== null) {
1865 this.selPoints_
.push(point
);
1873 if (this.lastRow_
>= 0) changed
= true;
1877 if (this.selPoints_
.length
) {
1878 this.lastx_
= this.selPoints_
[0].xval
;
1883 if (opt_seriesName
!== undefined
) {
1884 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
1885 this.highlightSet_
= opt_seriesName
;
1888 if (opt_locked
!== undefined
) {
1889 this.lockedSet_
= opt_locked
;
1893 this.updateSelection_(undefined
);
1899 * The mouse has left the canvas. Clear out whatever artifacts remain
1900 * @param {Object} event the mouseout event from the browser.
1903 Dygraph
.prototype.mouseOut_
= function(event
) {
1904 if (this.getFunctionOption("unhighlightCallback")) {
1905 this.getFunctionOption("unhighlightCallback").call(this, event
);
1908 if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_
) {
1909 this.clearSelection();
1914 * Clears the current selection (i.e. points that were highlighted by moving
1915 * the mouse over the chart).
1917 Dygraph
.prototype.clearSelection
= function() {
1918 this.cascadeEvents_('deselect', {});
1920 this.lockedSet_
= false;
1921 // Get rid of the overlay data
1922 if (this.fadeLevel
) {
1923 this.animateSelection_(-1);
1926 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1928 this.selPoints_
= [];
1931 this.highlightSet_
= null;
1935 * Returns the number of the currently selected row. To get data for this row,
1936 * you can use the getValue method.
1937 * @return {number} row number, or -1 if nothing is selected
1939 Dygraph
.prototype.getSelection
= function() {
1940 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1944 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; setIdx
++) {
1945 var points
= this.layout_
.points
[setIdx
];
1946 for (var row
= 0; row
< points
.length
; row
++) {
1947 if (points
[row
].x
== this.selPoints_
[0].x
) {
1948 return points
[row
].idx
;
1956 * Returns the name of the currently-highlighted series.
1957 * Only available when the highlightSeriesOpts option is in use.
1959 Dygraph
.prototype.getHighlightSeries
= function() {
1960 return this.highlightSet_
;
1964 * Returns true if the currently-highlighted series was locked
1965 * via setSelection(..., seriesName, true).
1967 Dygraph
.prototype.isSeriesLocked
= function() {
1968 return this.lockedSet_
;
1972 * Fires when there's data available to be graphed.
1973 * @param {string} data Raw CSV data to be plotted
1976 Dygraph
.prototype.loadedEvent_
= function(data
) {
1977 this.rawData_
= this.parseCSV_(data
);
1978 this.cascadeDataDidUpdateEvent_();
1983 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1986 Dygraph
.prototype.addXTicks_
= function() {
1987 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1989 if (this.dateWindow_
) {
1990 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
1992 range
= this.xAxisExtremes();
1995 var xAxisOptionsView
= this.optionsViewForAxis_('x');
1996 var xTicks
= xAxisOptionsView('ticker')(
1999 this.plotter_
.area
.w
, // TODO(danvk): should be area.width
2002 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2003 // console.log(msg);
2004 this.layout_
.setXTicks(xTicks
);
2008 * Returns the correct handler class for the currently set options.
2011 Dygraph
.prototype.getHandlerClass_
= function() {
2013 if (this.attr_('dataHandler')) {
2014 handlerClass
= this.attr_('dataHandler');
2015 } else if (this.fractions_
) {
2016 if (this.getBooleanOption('errorBars')) {
2017 handlerClass
= DygraphDataHandlers
.FractionsBarsHandler
;
2019 handlerClass
= DygraphDataHandlers
.DefaultFractionHandler
;
2021 } else if (this.getBooleanOption('customBars')) {
2022 handlerClass
= DygraphDataHandlers
.CustomBarsHandler
;
2023 } else if (this.getBooleanOption('errorBars')) {
2024 handlerClass
= DygraphDataHandlers
.ErrorBarsHandler
;
2026 handlerClass
= DefaultHandler
;
2028 return handlerClass
;
2033 * This function is called once when the chart's data is changed or the options
2034 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2035 * idea is that values derived from the chart's data can be computed here,
2036 * rather than every time the chart is drawn. This includes things like the
2037 * number of axes, rolling averages, etc.
2039 Dygraph
.prototype.predraw_
= function() {
2040 var start
= new Date();
2042 // Create the correct dataHandler
2043 this.dataHandler_
= new (this.getHandlerClass_())();
2045 this.layout_
.computePlotArea();
2047 // TODO(danvk): move more computations out of drawGraph_ and into here.
2048 this.computeYAxes_();
2050 if (!this.is_initial_draw_
) {
2051 this.canvas_ctx_
.restore();
2052 this.hidden_ctx_
.restore();
2055 this.canvas_ctx_
.save();
2056 this.hidden_ctx_
.save();
2058 // Create a new plotter.
2059 this.plotter_
= new DygraphCanvasRenderer(this,
2064 // The roller sits in the bottom left corner of the chart. We don't know where
2065 // this will be until the options are available, so it's positioned here.
2066 this.createRollInterface_();
2068 this.cascadeEvents_('predraw');
2070 // Convert the raw data (a 2D array) into the internal format and compute
2071 // rolling averages.
2072 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2073 for (var i
= 1; i
< this.numColumns(); i
++) {
2074 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too
.
2075 var series
= this.dataHandler_
.extractSeries(this.rawData_
, i
, this.attributes_
);
2076 if (this.rollPeriod_
> 1) {
2077 series
= this.dataHandler_
.rollingAverage(series
, this.rollPeriod_
, this.attributes_
);
2080 this.rolledSeries_
.push(series
);
2083 // If the data or options have changed, then we'd better redraw.
2086 // This is used to determine whether to do various animations.
2087 var end
= new Date();
2088 this.drawingTimeMs_
= (end
- start
);
2094 * xval_* and yval_* are the original unscaled data values,
2095 * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
2096 * yval_stacked is the cumulative Y value used for stacking graphs,
2097 * and bottom/top/minus/plus are used for error bar graphs.
2104 * y_bottom: ?number,
2106 * y_stacked: ?number,
2108 * yval_minus: ?number,
2110 * yval_plus: ?number,
2114 Dygraph
.PointType
= undefined
;
2117 * Calculates point stacking for stackedGraph=true.
2119 * For stacking purposes, interpolate or extend neighboring data across
2120 * NaN values based on stackedGraphNaNFill settings. This is for display
2121 * only, the underlying data value as shown in the legend remains NaN.
2123 * @param {Array.<Dygraph.PointType>} points Point array for a single series.
2124 * Updates each Point's yval_stacked property.
2125 * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
2126 * values for the series seen so far. Index is the row number. Updated
2127 * based on the current series's values.
2128 * @param {Array.<number>} seriesExtremes Min and max values, updated
2129 * to reflect the stacked values.
2130 * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
2134 Dygraph
.stackPoints_
= function(
2135 points
, cumulativeYval
, seriesExtremes
, fillMethod
) {
2136 var lastXval
= null;
2137 var prevPoint
= null;
2138 var nextPoint
= null;
2139 var nextPointIdx
= -1;
2141 // Find the next stackable point starting from the given index.
2142 var updateNextPoint
= function(idx
) {
2143 // If we've previously found a non-NaN point and haven't gone past it yet,
2145 if (nextPointIdx
>= idx
) return;
2147 // We haven't found a non-NaN point yet or have moved past it,
2148 // look towards the right to find a non-NaN point.
2149 for (var j
= idx
; j
< points
.length
; ++j
) {
2150 // Clear out a previously-found point (if any) since it's no longer
2151 // valid, we shouldn't use it for interpolation anymore.
2153 if (!isNaN(points
[j
].yval
) && points
[j
].yval
!== null) {
2155 nextPoint
= points
[j
];
2161 for (var i
= 0; i
< points
.length
; ++i
) {
2162 var point
= points
[i
];
2163 var xval
= point
.xval
;
2164 if (cumulativeYval
[xval
] === undefined
) {
2165 cumulativeYval
[xval
] = 0;
2168 var actualYval
= point
.yval
;
2169 if (isNaN(actualYval
) || actualYval
=== null) {
2170 if(fillMethod
== 'none') {
2173 // Interpolate/extend
for stacking purposes
if possible
.
2175 if (prevPoint
&& nextPoint
&& fillMethod
!= 'none') {
2176 // Use linear interpolation between prevPoint and nextPoint.
2177 actualYval
= prevPoint
.yval
+ (nextPoint
.yval
- prevPoint
.yval
) *
2178 ((xval
- prevPoint
.xval
) / (nextPoint
.xval
- prevPoint
.xval
));
2179 } else if (prevPoint
&& fillMethod
== 'all') {
2180 actualYval
= prevPoint
.yval
;
2181 } else if (nextPoint
&& fillMethod
== 'all') {
2182 actualYval
= nextPoint
.yval
;
2191 var stackedYval
= cumulativeYval
[xval
];
2192 if (lastXval
!= xval
) {
2193 // If an x-value is repeated, we ignore the duplicates.
2194 stackedYval
+= actualYval
;
2195 cumulativeYval
[xval
] = stackedYval
;
2199 point
.yval_stacked
= stackedYval
;
2201 if (stackedYval
> seriesExtremes
[1]) {
2202 seriesExtremes
[1] = stackedYval
;
2204 if (stackedYval
< seriesExtremes
[0]) {
2205 seriesExtremes
[0] = stackedYval
;
2212 * Loop over all fields and create datasets, calculating extreme y-values for
2213 * each series and extreme x-indices as we go.
2215 * dateWindow is passed in as an explicit parameter so that we can compute
2216 * extreme values "speculatively", i.e. without actually setting state on the
2219 * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
2220 * rolledSeries[seriesIndex][row] = raw point, where
2221 * seriesIndex is the column number starting with 1, and
2222 * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
2223 * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
2225 * points: Array.<Array.<Dygraph.PointType>>,
2226 * seriesExtremes: Array.<Array.<number>>,
2227 * boundaryIds: Array.<number>}}
2230 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2231 var boundaryIds
= [];
2233 var cumulativeYval
= []; // For stacked series.
2234 var extremes
= {}; // series name -> [low, high]
2235 var seriesIdx
, sampleIdx
;
2236 var firstIdx
, lastIdx
;
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;
2243 for (seriesIdx
= num_series
; seriesIdx
>= 1; seriesIdx
--) {
2244 if (!this.visibility()[seriesIdx
- 1]) continue;
2246 // Prune down to the desired range, if necessary (for zooming)
2247 // Because there can be lines going to points outside of the visible area,
2248 // we actually prune to visible points, plus one on either side.
2250 series
= rolledSeries
[seriesIdx
];
2251 var low
= dateWindow
[0];
2252 var high
= dateWindow
[1];
2254 // TODO(danvk): do binary search instead of linear search.
2255 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2258 for (sampleIdx
= 0; sampleIdx
< series
.length
; sampleIdx
++) {
2259 if (series
[sampleIdx
][0] >= low
&& firstIdx
=== null) {
2260 firstIdx
= sampleIdx
;
2262 if (series
[sampleIdx
][0] <= high
) {
2263 lastIdx
= sampleIdx
;
2267 if (firstIdx
=== null) firstIdx
= 0;
2268 var correctedFirstIdx
= firstIdx
;
2269 var isInvalidValue
= true;
2270 while (isInvalidValue
&& correctedFirstIdx
> 0) {
2271 correctedFirstIdx
--;
2272 // check if the y value is null.
2273 isInvalidValue
= series
[correctedFirstIdx
][1] === null;
2276 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2277 var correctedLastIdx
= lastIdx
;
2278 isInvalidValue
= true;
2279 while (isInvalidValue
&& correctedLastIdx
< series
.length
- 1) {
2281 isInvalidValue
= series
[correctedLastIdx
][1] === null;
2284 if (correctedFirstIdx
!==firstIdx
) {
2285 firstIdx
= correctedFirstIdx
;
2287 if (correctedLastIdx
!== lastIdx
) {
2288 lastIdx
= correctedLastIdx
;
2291 boundaryIds
[seriesIdx
-1] = [firstIdx
, lastIdx
];
2293 // .slice's end is exclusive, we want to include lastIdx.
2294 series
= series
.slice(firstIdx
, lastIdx
+ 1);
2296 series
= rolledSeries
[seriesIdx
];
2297 boundaryIds
[seriesIdx
-1] = [0, series
.length
-1];
2300 var seriesName
= this.attr_("labels")[seriesIdx
];
2301 var seriesExtremes
= this.dataHandler_
.getExtremeYValues(series
,
2302 dateWindow
, this.getBooleanOption("stepPlot",seriesName
));
2304 var seriesPoints
= this.dataHandler_
.seriesToPoints(series
,
2305 seriesName
, boundaryIds
[seriesIdx
-1][0]);
2307 if (this.getBooleanOption("stackedGraph")) {
2308 axisIdx
= this.attributes_
.axisForSeries(seriesName
);
2309 if (cumulativeYval
[axisIdx
] === undefined
) {
2310 cumulativeYval
[axisIdx
] = [];
2312 Dygraph
.stackPoints_(seriesPoints
, cumulativeYval
[axisIdx
], seriesExtremes
,
2313 this.getBooleanOption("stackedGraphNaNFill"));
2316 extremes
[seriesName
] = seriesExtremes
;
2317 points
[seriesIdx
] = seriesPoints
;
2320 return { points
: points
, extremes
: extremes
, boundaryIds
: boundaryIds
};
2324 * Update the graph with new data. This method is called when the viewing area
2325 * has changed. If the underlying data or options have changed, predraw_ will
2326 * be called before drawGraph_ is called.
2330 Dygraph
.prototype.drawGraph_
= function() {
2331 var start
= new Date();
2333 // This is used to set the second parameter to drawCallback, below.
2334 var is_initial_draw
= this.is_initial_draw_
;
2335 this.is_initial_draw_
= false;
2337 this.layout_
.removeAllDatasets();
2339 this.attrs_
.pointSize
= 0.5 * this.getNumericOption('highlightCircleSize');
2341 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2342 var points
= packed
.points
;
2343 var extremes
= packed
.extremes
;
2344 this.boundaryIds_
= packed
.boundaryIds
;
2346 this.setIndexByName_
= {};
2347 var labels
= this.attr_("labels");
2348 if (labels
.length
> 0) {
2349 this.setIndexByName_
[labels
[0]] = 0;
2352 for (var i
= 1; i
< points
.length
; i
++) {
2353 this.setIndexByName_
[labels
[i
]] = i
;
2354 if (!this.visibility()[i
- 1]) continue;
2355 this.layout_
.addDataset(labels
[i
], points
[i
]);
2356 this.datasetIndex_
[i
] = dataIdx
++;
2359 this.computeYAxisRanges_(extremes
);
2360 this.layout_
.setYAxes(this.axes_
);
2364 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2365 var tmp_zoomed_x
= this.zoomed_x_
;
2366 // Tell PlotKit to use this new data and render itself
2367 this.zoomed_x_
= tmp_zoomed_x
;
2368 this.layout_
.evaluate();
2369 this.renderGraph_(is_initial_draw
);
2371 if (this.getStringOption("timingName")) {
2372 var end
= new Date();
2373 console
.log(this.getStringOption("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2378 * This does the work of drawing the chart. It assumes that the layout and axis
2379 * scales have already been set (e.g. by predraw_).
2383 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2384 this.cascadeEvents_('clearChart');
2385 this.plotter_
.clear();
2387 if (this.getFunctionOption('underlayCallback')) {
2388 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2389 // users who expect a deprecated form of this callback.
2390 this.getFunctionOption('underlayCallback').call(this,
2391 this.hidden_ctx_
, this.layout_
.getPlotArea(), this, this);
2395 canvas
: this.hidden_
,
2396 drawingContext
: this.hidden_ctx_
2398 this.cascadeEvents_('willDrawChart', e
);
2399 this.plotter_
.render();
2400 this.cascadeEvents_('didDrawChart', e
);
2401 this.lastRow_
= -1; // because plugins/legend.js clears the legend
2403 // TODO(danvk): is this a performance bottleneck when panning?
2404 // The interaction canvas should already be empty in that situation.
2405 this.canvas_
.getContext('2d').clearRect(0, 0, this.width_
, this.height_
);
2407 if (this.getFunctionOption("drawCallback") !== null) {
2408 this.getFunctionOption("drawCallback").call(this, this, is_initial_draw
);
2410 if (is_initial_draw
) {
2411 this.readyFired_
= true;
2412 while (this.readyFns_
.length
> 0) {
2413 var fn
= this.readyFns_
.pop();
2421 * Determine properties of the y-axes which are independent of the data
2422 * currently being displayed. This includes things like the number of axes and
2423 * the style of the axes. It does not include the range of each axis and its
2425 * This fills in this.axes_.
2426 * axes_ = [ { options } ]
2427 * indices are into the axes_ array.
2429 Dygraph
.prototype.computeYAxes_
= function() {
2430 // Preserve valueWindow settings if they exist, and if the user hasn't
2431 // specified a new valueRange.
2432 var valueWindows
, axis
, index
, opts
, v
;
2433 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2435 for (index
= 0; index
< this.axes_
.length
; index
++) {
2436 valueWindows
.push(this.axes_
[index
].valueWindow
);
2440 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2441 // data computation as well as options storage.
2442 // Go through once and add all the axes.
2445 for (axis
= 0; axis
< this.attributes_
.numAxes(); axis
++) {
2446 // Add a new axis, making a copy of its per-axis options.
2447 opts
= { g
: this };
2448 utils
.update(opts
, this.attributes_
.axisOptions(axis
));
2449 this.axes_
[axis
] = opts
;
2453 // Copy global valueRange option over to the first axis.
2454 // NOTE(konigsberg): Are these two statements necessary?
2455 // I tried removing it. The automated tests pass, and manually
2456 // messing with tests/zoom
.html showed no trouble
.
2457 v
= this.attr_('valueRange');
2458 if (v
) this.axes_
[0].valueRange
= v
;
2460 if (valueWindows
!== undefined
) {
2461 // Restore valueWindow settings.
2463 // When going from two axes back to one, we only restore
2465 var idxCount
= Math
.min(valueWindows
.length
, this.axes_
.length
);
2467 for (index
= 0; index
< idxCount
; index
++) {
2468 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2472 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2474 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2475 v
= opts("valueRange");
2476 if (v
) this.axes_
[axis
].valueRange
= v
;
2477 } else { // To keep old behavior
2478 var axes
= this.user_attrs_
.axes
;
2479 if (axes
&& axes
.y2
) {
2480 v
= axes
.y2
.valueRange
;
2481 if (v
) this.axes_
[axis
].valueRange
= v
;
2488 * Returns the number of y-axes on the chart.
2489 * @return {number} the number of axes.
2491 Dygraph
.prototype.numAxes
= function() {
2492 return this.attributes_
.numAxes();
2497 * Returns axis properties for the given series.
2498 * @param {string} setName The name of the series for which to get axis
2499 * properties, e.g. 'Y1'.
2500 * @return {Object} The axis properties.
2502 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2503 // TODO(danvk): handle errors.
2504 return this.axes_
[this.attributes_
.axisForSeries(series
)];
2509 * Determine the value range and tick marks for each axis.
2510 * @param {Object} extremes A mapping from seriesName -> [low, high]
2511 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2513 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2514 var isNullUndefinedOrNaN
= function(num
) {
2515 return isNaN(parseFloat(num
));
2517 var numAxes
= this.attributes_
.numAxes();
2518 var ypadCompat
, span
, series
, ypad
;
2522 // Compute extreme values, a span and tick marks for each axis.
2523 for (var i
= 0; i
< numAxes
; i
++) {
2524 var axis
= this.axes_
[i
];
2525 var logscale
= this.attributes_
.getForAxis("logscale", i
);
2526 var includeZero
= this.attributes_
.getForAxis("includeZero", i
);
2527 var independentTicks
= this.attributes_
.getForAxis("independentTicks", i
);
2528 series
= this.attributes_
.seriesForAxis(i
);
2530 // Add some padding. This supports two Y padding operation modes:
2532 // - backwards compatible (yRangePad not set):
2533 // 10% padding for automatic Y ranges, but not for user-supplied
2534 // ranges, and move a close-to-zero edge to zero except if
2535 // avoidMinZero is set, since drawing at the edge results in
2536 // invisible lines. Unfortunately lines drawn at the edge of a
2537 // user-supplied range will still be invisible. If logscale is
2538 // set, add a variable amount of padding at the top but
2539 // none at the bottom.
2541 // - new-style (yRangePad set by the user):
2542 // always add the specified Y padding.
2545 ypad
= 0.1; // add 10%
2546 if (this.getNumericOption('yRangePad') !== null) {
2548 // Convert pixel padding to ratio
2549 ypad
= this.getNumericOption('yRangePad') / this.plotter_
.area
.h
;
2552 if (series
.length
=== 0) {
2553 // If no series are defined or visible then use a reasonable default
2554 axis
.extremeRange
= [0, 1];
2556 // Calculate the extremes of extremes.
2557 var minY
= Infinity
; // extremes[series[0]][0];
2558 var maxY
= -Infinity
; // extremes[series[0]][1];
2559 var extremeMinY
, extremeMaxY
;
2561 for (var j
= 0; j
< series
.length
; j
++) {
2562 // this skips invisible series
2563 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2565 // Only use valid extremes to stop null data series' from corrupting the scale.
2566 extremeMinY
= extremes
[series
[j
]][0];
2567 if (extremeMinY
!== null) {
2568 minY
= Math
.min(extremeMinY
, minY
);
2570 extremeMaxY
= extremes
[series
[j
]][1];
2571 if (extremeMaxY
!== null) {
2572 maxY
= Math
.max(extremeMaxY
, maxY
);
2576 // Include zero if requested by the user.
2577 if (includeZero
&& !logscale
) {
2578 if (minY
> 0) minY
= 0;
2579 if (maxY
< 0) maxY
= 0;
2582 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2583 if (minY
== Infinity
) minY
= 0;
2584 if (maxY
== -Infinity
) maxY
= 1;
2587 // special case: if we have no sense of scale, center on the sole value.
2590 span
= Math
.abs(maxY
);
2592 // ... and if the sole value is zero, use range 0-1.
2598 var maxAxisY
, minAxisY
;
2601 maxAxisY
= maxY
+ ypad
* span
;
2604 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2605 maxAxisY
= maxY
* logpad
;
2606 minAxisY
= minY
/ logpad
;
2609 maxAxisY
= maxY
+ ypad
* span
;
2610 minAxisY
= minY
- ypad
* span
;
2612 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2613 // close to zero, but not if avoidMinZero is set.
2614 if (ypadCompat
&& !this.getBooleanOption("avoidMinZero")) {
2615 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2616 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2619 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2621 if (axis
.valueWindow
) {
2622 // This is only set if the user has zoomed on the y-axis. It is never set
2623 // by a user. It takes precedence over axis.valueRange because, if you set
2624 // valueRange, you'd still expect to be able to pan.
2625 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2626 } else if (axis
.valueRange
) {
2627 // This is a user-set value range for this axis.
2628 var y0
= isNullUndefinedOrNaN(axis
.valueRange
[0]) ? axis
.extremeRange
[0] : axis
.valueRange
[0];
2629 var y1
= isNullUndefinedOrNaN(axis
.valueRange
[1]) ? axis
.extremeRange
[1] : axis
.valueRange
[1];
2631 if (axis
.logscale
) {
2632 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2641 axis
.computedValueRange
= [y0
, y1
];
2643 axis
.computedValueRange
= axis
.extremeRange
;
2647 if (independentTicks
) {
2648 axis
.independentTicks
= independentTicks
;
2649 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2650 var ticker
= opts('ticker');
2651 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2652 axis
.computedValueRange
[1],
2653 this.plotter_
.area
.h
,
2656 // Define the first independent axis as primary axis.
2657 if (!p_axis
) p_axis
= axis
;
2660 if (p_axis
=== undefined
) {
2661 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
2663 // Add ticks. By default, all axes inherit the tick positions of the
2664 // primary axis. However, if an axis is specifically marked as having
2665 // independent ticks, then that is permissible as well.
2666 for (var i
= 0; i
< numAxes
; i
++) {
2667 var axis
= this.axes_
[i
];
2669 if (!axis
.independentTicks
) {
2670 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2671 var ticker
= opts('ticker');
2672 var p_ticks
= p_axis
.ticks
;
2673 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2674 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2675 var tick_values
= [];
2676 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2677 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2678 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2679 tick_values
.push(y_val
);
2682 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2683 axis
.computedValueRange
[1],
2684 this.plotter_
.area
.h
,
2693 * Detects the type of the str (date or numeric) and sets the various
2694 * formatting attributes in this.attrs_ based on this type.
2695 * @param {string} str An x value.
2698 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2700 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2701 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
2702 str
.indexOf('/') >= 0 ||
2703 isNaN(parseFloat(str
))) {
2705 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2706 // TODO(danvk): remove support for this format.
2710 this.setXAxisOptions_(isDate
);
2713 Dygraph
.prototype.setXAxisOptions_
= function(isDate
) {
2715 this.attrs_
.xValueParser
= utils
.dateParser
;
2716 this.attrs_
.axes
.x
.valueFormatter
= utils
.dateValueFormatter
;
2717 this.attrs_
.axes
.x
.ticker
= DygraphTickers
.dateTicker
;
2718 this.attrs_
.axes
.x
.axisLabelFormatter
= utils
.dateAxisLabelFormatter
;
2720 /** @private (shut up, jsdoc!) */
2721 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2722 // TODO(danvk): use Dygraph.numberValueFormatter here?
2723 /** @private (shut up, jsdoc!) */
2724 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2725 this.attrs_
.axes
.x
.ticker
= DygraphTickers
.numericTicks
;
2726 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2732 * Parses a string in a special csv format. We expect a csv file where each
2733 * line is a date point, and the first field in each line is the date string.
2734 * We also expect that all remaining fields represent series.
2735 * if the errorBars attribute is set, then interpret the fields as:
2736 * date, series1, stddev1, series2, stddev2, ...
2737 * @param {[Object]} data See above.
2739 * @return [Object] An array with one entry for each row. These entries
2740 * are an array of cells in that row. The first entry is the parsed x-value for
2741 * the row. The second, third, etc. are the y-values. These can take on one of
2742 * three forms, depending on the CSV and constructor parameters:
2744 * 2. [ value, stddev ]
2745 * 3. [ low value, center value, high value ]
2747 Dygraph
.prototype.parseCSV_
= function(data
) {
2749 var line_delimiter
= utils
.detectLineDelimiter(data
);
2750 var lines
= data
.split(line_delimiter
|| "\n");
2753 // Use the default delimiter or fall back to a tab if that makes sense.
2754 var delim
= this.getStringOption('delimiter');
2755 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2760 if (!('labels' in this.user_attrs_
)) {
2761 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
2763 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
2764 this.attributes_
.reparseSeries();
2769 var defaultParserSet
= false; // attempt to auto-detect x value type
2770 var expectedCols
= this.attr_("labels").length
;
2771 var outOfOrder
= false;
2772 for (var i
= start
; i
< lines
.length
; i
++) {
2773 var line
= lines
[i
];
2775 if (line
.length
=== 0) continue; // skip blank lines
2776 if (line
[0] == '#') continue; // skip comment lines
2777 var inFields
= line
.split(delim
);
2778 if (inFields
.length
< 2) continue;
2781 if (!defaultParserSet
) {
2782 this.detectTypeFromString_(inFields
[0]);
2783 xParser
= this.getFunctionOption("xValueParser");
2784 defaultParserSet
= true;
2786 fields
[0] = xParser(inFields
[0], this);
2788 // If fractions are expected, parse the numbers as "A/B
"
2789 if (this.fractions_) {
2790 for (j = 1; j < inFields.length; j++) {
2791 // TODO(danvk): figure out an appropriate way to flag parse errors.
2792 vals = inFields[j].split("/");
2793 if (vals.length != 2) {
2794 console.error('Expected fractional "num
/den
" values in CSV data ' +
2795 "but found a value
'" + inFields[j] + "' on line
" +
2796 (1 + i) + " ('" + line + "') which is not of
this form
.");
2799 fields[j] = [utils.parseFloat_(vals[0], i, line),
2800 utils.parseFloat_(vals[1], i, line)];
2803 } else if (this.getBooleanOption("errorBars
")) {
2804 // If there are error bars, values are (value, stddev) pairs
2805 if (inFields.length % 2 != 1) {
2806 console.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2807 'but line ' + (1 + i) + ' has an odd number of values (' +
2808 (inFields.length - 1) + "): '" + line + "'");
2810 for (j = 1; j < inFields.length; j += 2) {
2811 fields[(j + 1) / 2] = [utils.parseFloat_(inFields[j], i, line),
2812 utils.parseFloat_(inFields[j + 1], i, line)];
2814 } else if (this.getBooleanOption("customBars
")) {
2815 // Bars are a low;center;high tuple
2816 for (j = 1; j < inFields.length; j++) {
2817 var val = inFields[j];
2818 if (/^ *$/.test(val)) {
2819 fields[j] = [null, null, null];
2821 vals = val.split(";");
2822 if (vals.length == 3) {
2823 fields[j] = [ utils.parseFloat_(vals[0], i, line),
2824 utils.parseFloat_(vals[1], i, line),
2825 utils.parseFloat_(vals[2], i, line) ];
2827 console.warn('When using customBars, values must be either blank ' +
2828 'or "low
;center
;high
" tuples (got "' + val +
2829 '" on line ' + (1+i));
2834 // Values are just numbers
2835 for (j = 1; j < inFields.length; j++) {
2836 fields[j] = utils.parseFloat_(inFields[j], i, line);
2839 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2843 if (fields.length != expectedCols) {
2844 console.error("Number of columns
in line
" + i + " (" + fields.length +
2845 ") does not agree
with number of
labels (" + expectedCols +
2849 // If the user specified the 'labels' option and none of the cells of the
2850 // first row parsed correctly, then they probably double-specified the
2851 // labels. We go with the values set in the option, discard this row and
2852 // log a warning to the JS console.
2853 if (i === 0 && this.attr_('labels')) {
2854 var all_null = true;
2855 for (j = 0; all_null && j < fields.length; j++) {
2856 if (fields[j]) all_null = false;
2859 console.warn("The dygraphs
'labels' option is set
, but the first row
" +
2860 "of CSV
data ('" + line + "') appears to also contain
" +
2861 "labels
. Will drop the CSV labels and
use the option
" +
2870 console.warn("CSV is out of order
; order it correctly to speed loading
.");
2871 ret.sort(function(a,b) { return a[0] - b[0]; });
2878 * The user has provided their data as a pre-packaged JS array. If the x values
2879 * are numeric, this is the same as dygraphs' internal format. If the x values
2880 * are dates, we need to convert them from Date objects to ms since epoch.
2881 * @param {!Array} data
2882 * @return {Object} data with numeric x values.
2885 Dygraph.prototype.parseArray_ = function(data) {
2886 // Peek at the first x value to see if it's numeric.
2887 if (data.length === 0) {
2888 console.error("Can
't plot empty data set");
2891 if (data[0].length === 0) {
2892 console.error("Data set cannot contain an empty row");
2897 if (this.attr_("labels") === null) {
2898 console.warn("Using default labels. Set labels explicitly via 'labels
' " +
2899 "in the options parameter");
2900 this.attrs_.labels = [ "X" ];
2901 for (i = 1; i < data[0].length; i++) {
2902 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
2904 this.attributes_.reparseSeries();
2906 var num_labels = this.attr_("labels");
2907 if (num_labels.length != data[0].length) {
2908 console.error("Mismatch between number of labels (" + num_labels + ")" +
2909 " and number of columns in array (" + data[0].length + ")");
2914 if (utils.isDateLike(data[0][0])) {
2915 // Some intelligent defaults for a date x-axis.
2916 this.attrs_.axes.x.valueFormatter = utils.dateValueFormatter;
2917 this.attrs_.axes.x.ticker = DygraphTickers.dateTicker;
2918 this.attrs_.axes.x.axisLabelFormatter = utils.dateAxisLabelFormatter;
2920 // Assume they're all dates
.
2921 var parsedData
= utils
.clone(data
);
2922 for (i
= 0; i
< data
.length
; i
++) {
2923 if (parsedData
[i
].length
=== 0) {
2924 console
.error("Row " + (1 + i
) + " of data is empty");
2927 if (parsedData
[i
][0] === null ||
2928 typeof(parsedData
[i
][0].getTime
) != 'function' ||
2929 isNaN(parsedData
[i
][0].getTime())) {
2930 console
.error("x value in row " + (1 + i
) + " is not a Date");
2933 parsedData
[i
][0] = parsedData
[i
][0].getTime();
2937 // Some intelligent defaults for a numeric x-axis.
2938 /** @private (shut up, jsdoc!) */
2939 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2940 this.attrs_
.axes
.x
.ticker
= DygraphTickers
.numericTicks
;
2941 this.attrs_
.axes
.x
.axisLabelFormatter
= utils
.numberAxisLabelFormatter
;
2947 * Parses a DataTable object from gviz.
2948 * The data is expected to have a first column that is either a date or a
2949 * number. All subsequent columns must be numbers. If there is a clear mismatch
2950 * between this.xValueParser_ and the type of the first column, it will be
2951 * fixed. Fills out rawData_.
2952 * @param {!google.visualization.DataTable} data See above.
2955 Dygraph
.prototype.parseDataTable_
= function(data
) {
2956 var shortTextForAnnotationNum
= function(num
) {
2957 // converts [0-9]+ [A-Z][a-z]*
2958 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
2959 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
2960 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
2961 num
= Math
.floor(num
/ 26);
2963 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
2964 num
= Math
.floor((num
- 1) / 26);
2969 var cols
= data
.getNumberOfColumns();
2970 var rows
= data
.getNumberOfRows();
2972 var indepType
= data
.getColumnType(0);
2973 if (indepType
== 'date' || indepType
== 'datetime') {
2974 this.attrs_
.xValueParser
= utils
.dateParser
;
2975 this.attrs_
.axes
.x
.valueFormatter
= utils
.dateValueFormatter
;
2976 this.attrs_
.axes
.x
.ticker
= DygraphTickers
.dateTicker
;
2977 this.attrs_
.axes
.x
.axisLabelFormatter
= utils
.dateAxisLabelFormatter
;
2978 } else if (indepType
== 'number') {
2979 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2980 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2981 this.attrs_
.axes
.x
.ticker
= DygraphTickers
.numericTicks
;
2982 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2985 "only 'date', 'datetime' and 'number' types are supported " +
2986 "for column 1 of DataTable input (Got '" + indepType
+ "')");
2989 // Array of the column indices which contain data (and not annotations).
2991 var annotationCols
= {}; // data index -> [annotation cols]
2992 var hasAnnotations
= false;
2994 for (i
= 1; i
< cols
; i
++) {
2995 var type
= data
.getColumnType(i
);
2996 if (type
== 'number') {
2998 } else if (type
== 'string' && this.getBooleanOption('displayAnnotations')) {
2999 // This is OK -- it's an annotation column.
3000 var dataIdx
= colIdx
[colIdx
.length
- 1];
3001 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3002 annotationCols
[dataIdx
] = [i
];
3004 annotationCols
[dataIdx
].push(i
);
3006 hasAnnotations
= true;
3009 "Only 'number' is supported as a dependent type with Gviz." +
3010 " 'string' is only supported if displayAnnotations is true");
3014 // Read column labels
3015 // TODO(danvk): add support back for errorBars
3016 var labels
= [data
.getColumnLabel(0)];
3017 for (i
= 0; i
< colIdx
.length
; i
++) {
3018 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3019 if (this.getBooleanOption("errorBars")) i
+= 1;
3021 this.attrs_
.labels
= labels
;
3022 cols
= labels
.length
;
3025 var outOfOrder
= false;
3026 var annotations
= [];
3027 for (i
= 0; i
< rows
; i
++) {
3029 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3030 data
.getValue(i
, 0) === null) {
3031 console
.warn("Ignoring row " + i
+
3032 " of DataTable because of undefined or null first column.");
3036 if (indepType
== 'date' || indepType
== 'datetime') {
3037 row
.push(data
.getValue(i
, 0).getTime());
3039 row
.push(data
.getValue(i
, 0));
3041 if (!this.getBooleanOption("errorBars")) {
3042 for (j
= 0; j
< colIdx
.length
; j
++) {
3043 var col
= colIdx
[j
];
3044 row
.push(data
.getValue(i
, col
));
3045 if (hasAnnotations
&&
3046 annotationCols
.hasOwnProperty(col
) &&
3047 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3049 ann
.series
= data
.getColumnLabel(col
);
3051 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3053 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3054 if (k
) ann
.text
+= "\n";
3055 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3057 annotations
.push(ann
);
3061 // Strip out infinities, which give dygraphs problems later on.
3062 for (j
= 0; j
< row
.length
; j
++) {
3063 if (!isFinite(row
[j
])) row
[j
] = null;
3066 for (j
= 0; j
< cols
- 1; j
++) {
3067 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3070 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3077 console
.warn("DataTable is out of order; order it correctly to speed loading.");
3078 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3080 this.rawData_
= ret
;
3082 if (annotations
.length
> 0) {
3083 this.setAnnotations(annotations
, true);
3085 this.attributes_
.reparseSeries();
3089 * Signals to plugins that the chart data has updated.
3090 * This happens after the data has updated but before the chart has redrawn.
3092 Dygraph
.prototype.cascadeDataDidUpdateEvent_
= function() {
3093 // TODO(danvk): there are some issues checking xAxisRange() and using
3094 // toDomCoords from handlers of this event. The visible range should be set
3095 // when the chart is drawn, not derived from the data.
3096 this.cascadeEvents_('dataDidUpdate', {});
3100 * Get the CSV data. If it's in a function, call that function. If it's in a
3101 * file, do an XMLHttpRequest to get it.
3104 Dygraph
.prototype.start_
= function() {
3105 var data
= this.file_
;
3107 // Functions can return references of all other types.
3108 if (typeof data
== 'function') {
3112 if (utils
.isArrayLike(data
)) {
3113 this.rawData_
= this.parseArray_(data
);
3114 this.cascadeDataDidUpdateEvent_();
3116 } else if (typeof data
== 'object' &&
3117 typeof data
.getColumnRange
== 'function') {
3118 // must be a DataTable from gviz.
3119 this.parseDataTable_(data
);
3120 this.cascadeDataDidUpdateEvent_();
3122 } else if (typeof data
== 'string') {
3123 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3124 var line_delimiter
= utils
.detectLineDelimiter(data
);
3125 if (line_delimiter
) {
3126 this.loadedEvent_(data
);
3130 if (window
.XMLHttpRequest
) {
3131 // Firefox, Opera, IE7, and other browsers will use the native object
3132 req
= new XMLHttpRequest();
3134 // IE 5 and 6 will use the ActiveX control
3135 req
= new ActiveXObject("Microsoft.XMLHTTP");
3139 req
.onreadystatechange
= function () {
3140 if (req
.readyState
== 4) {
3141 if (req
.status
=== 200 || // Normal http
3142 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3143 caller
.loadedEvent_(req
.responseText
);
3148 req
.open("GET", data
, true);
3152 console
.error("Unknown data format: " + (typeof data
));
3157 * Changes various properties of the graph. These can include:
3159 * <li>file: changes the source data for the graph</li>
3160 * <li>errorBars: changes whether the data contains stddev</li>
3163 * There's a huge variety of options that can be passed to this method. For a
3164 * full list, see http://dygraphs.com/options.html.
3166 * @param {Object} input_attrs The new properties and values
3167 * @param {boolean} block_redraw Usually the chart is redrawn after every
3168 * call to updateOptions(). If you know better, you can pass true to
3169 * explicitly block the redraw. This can be useful for chaining
3170 * updateOptions() calls, avoiding the occasional infinite loop and
3171 * preventing redraws when it's not necessary (e.g. when updating a
3174 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3175 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3177 // copyUserAttrs_ drops the "file" parameter as a convenience to us.
3178 var file
= input_attrs
.file
;
3179 var attrs
= Dygraph
.copyUserAttrs_(input_attrs
);
3181 // TODO(danvk): this is a mess. Move these options into attr_.
3182 if ('rollPeriod' in attrs
) {
3183 this.rollPeriod_
= attrs
.rollPeriod
;
3185 if ('dateWindow' in attrs
) {
3186 this.dateWindow_
= attrs
.dateWindow
;
3187 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3188 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3191 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3192 this.zoomed_y_
= (attrs
.valueRange
!== null);
3195 // TODO(danvk): validate per-series options.
3200 // highlightCircleSize
3202 // Check if this set options will require new points.
3203 var requiresNewPoints
= utils
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3205 utils
.updateDeep(this.user_attrs_
, attrs
);
3207 this.attributes_
.reparseSeries();
3210 // This event indicates that the data is about to change, but hasn't yet.
3211 // TODO(danvk): support cancelation of the update via this event.
3212 this.cascadeEvents_('dataWillUpdate', {});
3215 if (!block_redraw
) this.start_();
3217 if (!block_redraw
) {
3218 if (requiresNewPoints
) {
3221 this.renderGraph_(false);
3228 * Make a copy of input attributes, removing file as a convenience.
3230 Dygraph
.copyUserAttrs_
= function(attrs
) {
3232 for (var k
in attrs
) {
3233 if (!attrs
.hasOwnProperty(k
)) continue;
3234 if (k
== 'file') continue;
3235 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3241 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3242 * containing div (which has presumably changed size since the dygraph was
3243 * instantiated. If the width/height are specified, the div will be resized.
3245 * This is far more efficient than destroying and re-instantiating a
3246 * Dygraph, since it doesn't have to reparse the underlying data.
3248 * @param {number} width Width (in pixels)
3249 * @param {number} height Height (in pixels)
3251 Dygraph
.prototype.resize
= function(width
, height
) {
3252 if (this.resize_lock
) {
3255 this.resize_lock
= true;
3257 if ((width
=== null) != (height
=== null)) {
3258 console
.warn("Dygraph.resize() should be called with zero parameters or " +
3259 "two non-NULL parameters. Pretending it was zero.");
3260 width
= height
= null;
3263 var old_width
= this.width_
;
3264 var old_height
= this.height_
;
3267 this.maindiv_
.style
.width
= width
+ "px";
3268 this.maindiv_
.style
.height
= height
+ "px";
3269 this.width_
= width
;
3270 this.height_
= height
;
3272 this.width_
= this.maindiv_
.clientWidth
;
3273 this.height_
= this.maindiv_
.clientHeight
;
3276 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3277 // Resizing a canvas erases it, even when the size doesn't change, so
3278 // any resize needs to be followed by a redraw.
3279 this.resizeElements_();
3283 this.resize_lock
= false;
3287 * Adjusts the number of points in the rolling average. Updates the graph to
3288 * reflect the new averaging period.
3289 * @param {number} length Number of points over which to average the data.
3291 Dygraph
.prototype.adjustRoll
= function(length
) {
3292 this.rollPeriod_
= length
;
3297 * Returns a boolean array of visibility statuses.
3299 Dygraph
.prototype.visibility
= function() {
3300 // Do lazy-initialization, so that this happens after we know the number of
3302 if (!this.getOption("visibility")) {
3303 this.attrs_
.visibility
= [];
3305 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3306 while (this.getOption("visibility").length
< this.numColumns() - 1) {
3307 this.attrs_
.visibility
.push(true);
3309 return this.getOption("visibility");
3313 * Changes the visibility of one or more series.
3315 * @param {number|number[]|object} num the series index or an array of series indices
3316 * or a boolean array of visibility states by index
3317 * or an object mapping series numbers, as keys, to
3318 * visibility state (boolean values)
3319 * @param {boolean} value the visibility state expressed as a boolean
3321 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3322 var x
= this.visibility();
3323 var numIsObject
= false;
3325 if (!Array
.isArray(num
)) {
3326 if (num
!== null && typeof num
=== 'object') {
3334 for (var i
in num
) {
3335 if (num
.hasOwnProperty(i
)) {
3336 if (i
< 0 || i
>= x
.length
) {
3337 console
.warn("Invalid series number in setVisibility: " + i
);
3344 for (var i
= 0; i
< num
.length
; i
++) {
3345 if (typeof num
[i
] === 'boolean') {
3346 if (i
>= x
.length
) {
3347 console
.warn("Invalid series number in setVisibility: " + i
);
3352 if (num
[i
] < 0 || num
[i
] >= x
.length
) {
3353 console
.warn("Invalid series number in setVisibility: " + num
[i
]);
3365 * How large of an area will the dygraph render itself in?
3366 * This is used for testing.
3367 * @return A {width: w, height: h} object.
3370 Dygraph
.prototype.size
= function() {
3371 return { width
: this.width_
, height
: this.height_
};
3375 * Update the list of annotations and redraw the chart.
3376 * See dygraphs.com/annotations.html for more info on how to use annotations.
3377 * @param ann {Array} An array of annotation objects.
3378 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3380 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3381 // Only add the annotation CSS rule once we know it will be used.
3382 Dygraph
.addAnnotationRule();
3383 this.annotations_
= ann
;
3384 if (!this.layout_
) {
3385 console
.warn("Tried to setAnnotations before dygraph was ready. " +
3386 "Try setting them in a ready() block. See " +
3387 "dygraphs.com/tests/annotation.html");
3391 this.layout_
.setAnnotations(this.annotations_
);
3392 if (!suppressDraw
) {
3398 * Return the list of annotations.
3400 Dygraph
.prototype.annotations
= function() {
3401 return this.annotations_
;
3405 * Get the list of label names for this graph. The first column is the
3406 * x-axis, so the data series names start at index 1.
3408 * Returns null when labels have not yet been defined.
3410 Dygraph
.prototype.getLabels
= function() {
3411 var labels
= this.attr_("labels");
3412 return labels
? labels
.slice() : null;
3416 * Get the index of a series (column) given its name. The first column is the
3417 * x-axis, so the data series start with index 1.
3419 Dygraph
.prototype.indexFromSetName
= function(name
) {
3420 return this.setIndexByName_
[name
];
3424 * Find the row number corresponding to the given x-value.
3425 * Returns null if there is no such x-value in the data.
3426 * If there are multiple rows with the same x-value, this will return the
3428 * @param {number} xVal The x-value to look for (e.g. millis since epoch).
3429 * @return {?number} The row number, which you can pass to getValue(), or null.
3431 Dygraph
.prototype.getRowForX
= function(xVal
) {
3433 high
= this.numRows() - 1;
3435 while (low
<= high
) {
3436 var idx
= (high
+ low
) >> 1;
3437 var x
= this.getValue(idx
, 0);
3440 } else if (x
> xVal
) {
3442 } else if (low
!= idx
) { // equal, but there may be an earlier match.
3453 * Trigger a callback when the dygraph has drawn itself and is ready to be
3454 * manipulated. This is primarily useful when dygraphs has to do an XHR for the
3455 * data (i.e. a URL is passed as the data source) and the chart is drawn
3456 * asynchronously. If the chart has already drawn, the callback will fire
3459 * This is a good place to call setAnnotation().
3461 * @param {function(!Dygraph)} callback The callback to trigger when the chart
3464 Dygraph
.prototype.ready
= function(callback
) {
3465 if (this.is_initial_draw_
) {
3466 this.readyFns_
.push(callback
);
3468 callback
.call(this, this);
3474 * Adds a default style for the annotation CSS classes to the document. This is
3475 * only executed when annotations are actually used. It is designed to only be
3476 * called once -- all calls after the first will return immediately.
3478 Dygraph
.addAnnotationRule
= function() {
3479 // TODO(danvk): move this function into plugins/annotations.js
?
3480 if (Dygraph
.addedAnnotationCSS
) return;
3482 var rule
= "border: 1px solid black; " +
3483 "background-color: white; " +
3484 "text-align: center;";
3486 var styleSheetElement
= document
.createElement("style");
3487 styleSheetElement
.type
= "text/css";
3488 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3490 // Find the first style sheet that we can access.
3491 // We may not add a rule to a style sheet from another domain for security
3492 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3493 // adds its own style sheets from google.com.
3494 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3495 if (document
.styleSheets
[i
].disabled
) continue;
3496 var mysheet
= document
.styleSheets
[i
];
3498 if (mysheet
.insertRule
) { // Firefox
3499 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3500 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3501 } else if (mysheet
.addRule
) { // IE
3502 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3504 Dygraph
.addedAnnotationCSS
= true;
3507 // Was likely a security exception.
3511 console
.warn("Unable to add default annotation CSS rule; display may be off.");
3515 * Add an event handler. This event handler is kept until the graph is
3516 * destroyed with a call to graph.destroy().
3518 * @param {!Node} elem The element to add the event to.
3519 * @param {string} type The type of the event, e.g. 'click' or 'mousemove'.
3520 * @param {function(Event):(boolean|undefined)} fn The function to call
3521 * on the event. The function takes one parameter: the event object.
3524 Dygraph
.prototype.addAndTrackEvent
= function(elem
, type
, fn
) {
3525 utils
.addEvent(elem
, type
, fn
);
3526 this.registeredEvents_
.push({elem
, type
, fn
});
3529 Dygraph
.prototype.removeTrackedEvents_
= function() {
3530 if (this.registeredEvents_
) {
3531 for (var idx
= 0; idx
< this.registeredEvents_
.length
; idx
++) {
3532 var reg
= this.registeredEvents_
[idx
];
3533 utils
.removeEvent(reg
.elem
, reg
.type
, reg
.fn
);
3537 this.registeredEvents_
= [];
3541 // Installed plugins, in order of precedence (most-general to most-specific).
3545 RangeSelectorPlugin
, // Has to be before ChartLabels so that its callbacks are called after ChartLabels' callbacks.
3551 export default Dygraph
;