3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
9 * string. Dygraph can handle multiple series with or without error bars. The
10 * date/value ranges will be automatically set. Dygraph uses the
11 * <canvas> tag, so it only works in FF1.5+.
12 * @author danvdk@gmail.com (Dan Vanderkam)
15 <div id="graphdiv" style="width:800px; height:500px;"></div>
16 <script type="text/javascript">
17 new Dygraph(document.getElementById("graphdiv"),
18 "datafile.csv", // CSV file with headers
22 The CSV file is of the form
24 Date,SeriesA,SeriesB,SeriesC
28 If the 'errorBars' option is set in the constructor, the input should be of
30 Date,SeriesA,SeriesB,...
31 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
32 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
34 If the 'fractions' option is set, the input should be of the form:
36 Date,SeriesA,SeriesB,...
37 YYYYMMDD,A1/B1,A2/B2,...
38 YYYYMMDD,A1/B1,A2/B2,...
40 And error bars will be calculated automatically using a binomial distribution.
42 For further documentation and examples, see http://dygraphs.com/
46 /*jshint globalstrict: true */
47 /*global DygraphRangeSelector:false, DygraphLayout:false, DygraphCanvasRenderer:false, G_vmlCanvasManager:false */
51 * Creates an interactive, zoomable chart.
54 * @param {div | String} div A div or the id of a div into which to construct
56 * @param {String | Function} file A file containing CSV data or a function
57 * that returns this data. The most basic expected format for each line is
58 * "YYYY/MM/DD,val1,val2,...". For more information, see
59 * http://dygraphs.com/data.html.
60 * @param {Object} attrs Various other attributes, e.g. errorBars determines
61 * whether the input data contains error ranges. For a complete list of
62 * options, see http://dygraphs.com/options.html.
64 var Dygraph
= function(div
, data
, opts
, opt_fourth_param
) {
65 if (opt_fourth_param
!== undefined
) {
66 // Old versions of dygraphs took in the series labels as a constructor
67 // parameter. This doesn't make sense anymore, but it's easy to continue
68 // to support this usage.
69 this.warn("Using deprecated four-argument dygraph constructor");
70 this.__old_init__(div
, data
, opts
, opt_fourth_param
);
72 this.__init__(div
, data
, opts
);
76 Dygraph
.NAME
= "Dygraph";
77 Dygraph
.VERSION
= "1.2";
78 Dygraph
.__repr__
= function() {
79 return "[" + this.NAME
+ " " + this.VERSION
+ "]";
83 * Returns information about the Dygraph class.
85 Dygraph
.toString
= function() {
86 return this.__repr__();
89 // Various default values
90 Dygraph
.DEFAULT_ROLL_PERIOD
= 1;
91 Dygraph
.DEFAULT_WIDTH
= 480;
92 Dygraph
.DEFAULT_HEIGHT
= 320;
94 Dygraph
.ANIMATION_STEPS
= 10;
95 Dygraph
.ANIMATION_DURATION
= 200;
97 // These are defined before DEFAULT_ATTRS so that it can refer to them.
100 * Return a string version of a number. This respects the digitsAfterDecimal
101 * and maxNumberWidth options.
102 * @param {Number} x The number to be formatted
103 * @param {Dygraph} opts An options view
104 * @param {String} name The name of the point's data series
105 * @param {Dygraph} g The dygraph object
107 Dygraph
.numberValueFormatter
= function(x
, opts
, pt
, g
) {
108 var sigFigs
= opts('sigFigs');
110 if (sigFigs
!== null) {
111 // User has opted for a fixed number of significant figures.
112 return Dygraph
.floatFormat(x
, sigFigs
);
115 var digits
= opts('digitsAfterDecimal');
116 var maxNumberWidth
= opts('maxNumberWidth');
118 // switch to scientific notation if we underflow or overflow fixed display.
120 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
121 Math
.abs(x
) < Math
.pow(10, -digits
))) {
122 return x
.toExponential(digits
);
124 return '' + Dygraph
.round_(x
, digits
);
129 * variant for use as an axisLabelFormatter.
132 Dygraph
.numberAxisLabelFormatter
= function(x
, granularity
, opts
, g
) {
133 return Dygraph
.numberValueFormatter(x
, opts
, g
);
137 * Convert a JS date (millis since epoch) to YYYY/MM/DD
138 * @param {Number} date The JavaScript date (ms since epoch)
139 * @return {String} A date of the form "YYYY/MM/DD"
142 Dygraph
.dateString_
= function(date
) {
143 var zeropad
= Dygraph
.zeropad
;
144 var d
= new Date(date
);
147 var year
= "" + d
.getFullYear();
148 // Get a 0 padded month string
149 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
150 // Get a 0 padded day string
151 var day
= zeropad(d
.getDate());
154 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
155 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
157 return year
+ "/" + month + "/" + day
+ ret
;
161 * Convert a JS date to a string appropriate to display on an axis that
162 * is displaying values at the stated granularity.
163 * @param {Date} date The date to format
164 * @param {Number} granularity One of the Dygraph granularity constants
165 * @return {String} The formatted date
168 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
169 if (granularity
>= Dygraph
.DECADAL
) {
170 return date
.strftime('%Y');
171 } else if (granularity
>= Dygraph
.MONTHLY
) {
172 return date
.strftime('%b %y');
174 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
175 if (frac
=== 0 || granularity
>= Dygraph
.DAILY
) {
176 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
178 return Dygraph
.hmsString_(date
.getTime());
184 // Default attribute values.
185 Dygraph
.DEFAULT_ATTRS
= {
186 highlightCircleSize
: 3,
187 highlightSeriesOpts
: null,
188 highlightSeriesBackgroundAlpha
: 0.5,
192 // TODO(danvk): move defaults from createStatusMessage_ here.
194 labelsSeparateLines
: false,
195 labelsShowZeroValues
: true,
198 showLabelsOnHighlight
: true,
200 digitsAfterDecimal
: 2,
205 strokeBorderWidth
: 0,
206 strokeBorderColor
: "white",
209 axisLabelFontSize
: 14,
215 xValueParser
: Dygraph
.dateParser
,
222 wilsonInterval
: true, // only relevant if fractions is true
226 connectSeparatedPoints
: false,
229 hideOverlayOnMouseOut
: true,
231 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
232 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
237 // Sizes of the various chart labels.
244 axisLineColor
: "black",
247 axisLabelColor
: "black",
248 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
252 gridLineColor
: "rgb(128,128,128)",
254 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
255 animatedZooms
: false, // (for now)
257 // Range selector options
258 showRangeSelector
: false,
259 rangeSelectorHeight
: 40,
260 rangeSelectorPlotStrokeColor
: "#808FAB",
261 rangeSelectorPlotFillColor
: "#A7B1C4",
267 axisLabelFormatter
: Dygraph
.dateAxisFormatter
,
268 valueFormatter
: Dygraph
.dateString_
,
269 ticker
: null // will be set in dygraph-tickers.js
273 valueFormatter
: Dygraph
.numberValueFormatter
,
274 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
275 ticker
: null // will be set in dygraph-tickers.js
279 valueFormatter
: Dygraph
.numberValueFormatter
,
280 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
281 ticker
: null // will be set in dygraph-tickers.js
286 // Directions for panning and zooming. Use bit operations when combined
287 // values are possible.
288 Dygraph
.HORIZONTAL
= 1;
289 Dygraph
.VERTICAL
= 2;
291 // Installed plugins, in order of precedence (most-general to most-specific).
292 // Plugins are installed after they are defined, in plugins/install.js
.
296 // Used for initializing annotation CSS rules only once.
297 Dygraph
.addedAnnotationCSS
= false;
299 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
300 // Labels is no longer a constructor parameter, since it's typically set
301 // directly from the data source. It also conains a name for the x-axis,
302 // which the previous constructor form did not.
303 if (labels
!== null) {
304 var new_labels
= ["Date"];
305 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
306 Dygraph
.update(attrs
, { 'labels': new_labels
});
308 this.__init__(div
, file
, attrs
);
312 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
313 * and context <canvas> inside of it. See the constructor for details.
315 * @param {Element} div the Element to render the graph into.
316 * @param {String | Function} file Source data
317 * @param {Object} attrs Miscellaneous other options
320 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
321 // Hack for IE: if we're using excanvas and the document hasn't finished
322 // loading yet (and hence may not have initialized whatever it needs to
323 // initialize), then keep calling this routine periodically until it has.
324 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
325 typeof(G_vmlCanvasManager
) != 'undefined' &&
326 document
.readyState
!= 'complete') {
328 setTimeout(function() { self
.__init__(div
, file
, attrs
); }, 100);
332 // Support two-argument constructor
333 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
335 attrs
= Dygraph
.mapLegacyOptions_(attrs
);
338 Dygraph
.error("Constructing dygraph with a non-existent div!");
342 this.isUsingExcanvas_
= typeof(G_vmlCanvasManager
) != 'undefined';
344 // Copy the important bits into the object
345 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
348 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
349 this.previousVerticalX_
= -1;
350 this.fractions_
= attrs
.fractions
|| false;
351 this.dateWindow_
= attrs
.dateWindow
|| null;
353 this.is_initial_draw_
= true;
354 this.annotations_
= [];
356 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
357 this.zoomed_x_
= false;
358 this.zoomed_y_
= false;
360 // Clear the div. This ensure that, if multiple dygraphs are passed the same
361 // div, then only one will be drawn.
364 // For historical reasons, the 'width' and 'height' options trump all CSS
365 // rules _except_ for an explicit 'width' or 'height' on the div.
366 // As an added convenience, if the div has zero height (like <div></div> does
367 // without any styles), then we use a default height/width
.
368 if (div
.style
.width
=== '' && attrs
.width
) {
369 div
.style
.width
= attrs
.width
+ "px";
371 if (div
.style
.height
=== '' && attrs
.height
) {
372 div
.style
.height
= attrs
.height
+ "px";
374 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
375 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
376 if (div
.style
.width
=== '') {
377 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
380 // these will be zero if the dygraph's div is hidden.
381 this.width_
= div
.clientWidth
;
382 this.height_
= div
.clientHeight
;
384 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
385 if (attrs
.stackedGraph
) {
386 attrs
.fillGraph
= true;
387 // TODO(nikhilk): Add any other stackedGraph checks here.
390 // Dygraphs has many options, some of which interact with one another.
391 // To keep track of everything, we maintain two sets of options:
393 // this.user_attrs_ only options explicitly set by the user.
394 // this.attrs_ defaults, options derived from user_attrs_, data.
396 // Options are then accessed this.attr_('attr'), which first looks at
397 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
398 // defaults without overriding behavior that the user specifically asks for.
399 this.user_attrs_
= {};
400 Dygraph
.update(this.user_attrs_
, attrs
);
402 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
404 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
406 this.boundaryIds_
= [];
407 this.setIndexByName_
= {};
408 this.datasetIndex_
= [];
410 // Create the containing DIV and other interactive elements
411 this.createInterface_();
415 for (var i
= 0; i
< Dygraph
.PLUGINS
.length
; i
++) {
416 var plugin
= Dygraph
.PLUGINS
[i
];
417 var pluginInstance
= new plugin();
419 plugin
: pluginInstance
,
425 var handlers
= pluginInstance
.activate(this);
426 for (var eventName
in handlers
) {
427 // TODO(danvk): validate eventName.
428 pluginDict
.events
[eventName
] = handlers
[eventName
];
431 this.plugins_
.push(pluginDict
);
434 // At this point, plugins can no longer register event handlers.
435 // Construct a map from event -> ordered list of [callback, plugin].
436 this.eventListeners_
= {};
437 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
438 var plugin_dict
= this.plugins_
[i
];
439 for (var eventName
in plugin_dict
.events
) {
440 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
441 var callback
= plugin_dict
.events
[eventName
];
443 var pair
= [plugin_dict
.plugin
, callback
];
444 if (!(eventName
in this.eventListeners_
)) {
445 this.eventListeners_
[eventName
] = [pair
];
447 this.eventListeners_
[eventName
].push(pair
);
456 * Triggers a cascade of events to the various plugins which are interested in them.
457 * Returns true if the "default behavior" should be performed, i.e. if none of
458 * the event listeners called event.preventDefault().
461 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
462 if (!name
in this.eventListeners_
) return true;
464 // QUESTION: can we use objects & prototypes to speed this up?
468 defaultPrevented
: false,
469 preventDefault
: function() {
470 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
471 e
.defaultPrevented
= true;
473 propagationStopped
: false,
474 stopPropagation
: function() {
475 e
.propagationStopped
= true;
478 Dygraph
.update(e
, extra_props
);
480 var callback_plugin_pairs
= this.eventListeners_
[name
];
481 if (callback_plugin_pairs
) {
482 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
483 var plugin
= callback_plugin_pairs
[i
][0];
484 var callback
= callback_plugin_pairs
[i
][1];
485 callback
.call(plugin
, e
);
486 if (e
.propagationStopped
) break;
489 return e
.defaultPrevented
;
493 * Returns the zoomed status of the chart for one or both axes.
495 * Axis is an optional parameter. Can be set to 'x' or 'y'.
497 * The zoomed status for an axis is set whenever a user zooms using the mouse
498 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
499 * option is also specified).
501 Dygraph
.prototype.isZoomed
= function(axis
) {
502 if (axis
== null) return this.zoomed_x_
|| this.zoomed_y_
;
503 if (axis
=== 'x') return this.zoomed_x_
;
504 if (axis
=== 'y') return this.zoomed_y_
;
505 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
509 * Returns information about the Dygraph object, including its containing ID.
511 Dygraph
.prototype.toString
= function() {
512 var maindiv
= this.maindiv_
;
513 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
514 return "[Dygraph " + id
+ "]";
519 * Returns the value of an option. This may be set by the user (either in the
520 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
522 * @param { String } name The name of the option, e.g. 'rollPeriod'.
523 * @param { String } [seriesName] The name of the series to which the option
524 * will be applied. If no per-series value of this option is available, then
525 * the global value is returned. This is optional.
526 * @return { ... } The value of the option.
528 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
529 // <REMOVE_FOR_COMBINED>
530 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
531 this.error('Must include options reference JS for testing');
532 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
533 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
534 'in the Dygraphs.OPTIONS_REFERENCE listing.');
535 // Only log this error once.
536 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
538 // </REMOVE_FOR_COMBINED
>
541 sources
.push(this.attrs_
);
542 if (this.user_attrs_
) {
543 sources
.push(this.user_attrs_
);
545 if (this.user_attrs_
.hasOwnProperty(seriesName
)) {
546 sources
.push(this.user_attrs_
[seriesName
]);
548 if (seriesName
=== this.highlightSet_
&&
549 this.user_attrs_
.hasOwnProperty('highlightSeriesOpts')) {
550 sources
.push(this.user_attrs_
['highlightSeriesOpts']);
556 for (var i
= sources
.length
- 1; i
>= 0; --i
) {
557 var source
= sources
[i
];
558 if (source
.hasOwnProperty(name
)) {
567 * Returns the current value for an option, as set in the constructor or via
568 * updateOptions. You may pass in an (optional) series name to get per-series
569 * values for the option.
571 * All values returned by this method should be considered immutable. If you
572 * modify them, there is no guarantee that the changes will be honored or that
573 * dygraphs will remain in a consistent state. If you want to modify an option,
574 * use updateOptions() instead.
576 * @param { String } name The name of the option (e.g. 'strokeWidth')
577 * @param { String } [opt_seriesName] Series name to get per-series values.
578 * @return { ... } The value of the option.
580 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
581 return this.attr_(name
, opt_seriesName
);
586 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
587 * @return { ... } A function mapping string -> option value
589 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
591 return function(opt
) {
592 var axis_opts
= self
.user_attrs_
.axes
;
593 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
594 return axis_opts
[axis
][opt
];
596 // user-specified attributes always trump defaults, even if they're less
598 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
599 return self
.user_attrs_
[opt
];
602 axis_opts
= self
.attrs_
.axes
;
603 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
604 return axis_opts
[axis
][opt
];
606 // check old-style axis options
607 // TODO(danvk): add a deprecation warning if either of these match.
608 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
609 return self
.axes_
[0][opt
];
610 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
611 return self
.axes_
[1][opt
];
613 return self
.attr_(opt
);
618 * Returns the current rolling period, as set by the user or an option.
619 * @return {Number} The number of points in the rolling window
621 Dygraph
.prototype.rollPeriod
= function() {
622 return this.rollPeriod_
;
626 * Returns the currently-visible x-range. This can be affected by zooming,
627 * panning or a call to updateOptions.
628 * Returns a two-element array: [left, right].
629 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
631 Dygraph
.prototype.xAxisRange
= function() {
632 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
636 * Returns the lower- and upper-bound x-axis values of the
639 Dygraph
.prototype.xAxisExtremes
= function() {
640 var left
= this.rawData_
[0][0];
641 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
642 return [left
, right
];
646 * Returns the currently-visible y-range for an axis. This can be affected by
647 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
648 * called with no arguments, returns the range of the first axis.
649 * Returns a two-element array: [bottom, top].
651 Dygraph
.prototype.yAxisRange
= function(idx
) {
652 if (typeof(idx
) == "undefined") idx
= 0;
653 if (idx
< 0 || idx
>= this.axes_
.length
) {
656 var axis
= this.axes_
[idx
];
657 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
661 * Returns the currently-visible y-ranges for each axis. This can be affected by
662 * zooming, panning, calls to updateOptions, etc.
663 * Returns an array of [bottom, top] pairs, one for each y-axis.
665 Dygraph
.prototype.yAxisRanges
= function() {
667 for (var i
= 0; i
< this.axes_
.length
; i
++) {
668 ret
.push(this.yAxisRange(i
));
673 // TODO(danvk): use these functions throughout dygraphs.
675 * Convert from data coordinates to canvas/div X/Y coordinates.
676 * If specified, do this conversion for the coordinate system of a particular
677 * axis. Uses the first axis by default.
678 * Returns a two-element array: [X, Y]
680 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
681 * instead of toDomCoords(null, y, axis).
683 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
684 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
688 * Convert from data x coordinates to canvas/div X coordinate.
689 * If specified, do this conversion for the coordinate system of a particular
691 * Returns a single value or null if x is null.
693 Dygraph
.prototype.toDomXCoord
= function(x
) {
698 var area
= this.plotter_
.area
;
699 var xRange
= this.xAxisRange();
700 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
704 * Convert from data x coordinates to canvas/div Y coordinate and optional
705 * axis. Uses the first axis by default.
707 * returns a single value or null if y is null.
709 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
710 var pct
= this.toPercentYCoord(y
, axis
);
715 var area
= this.plotter_
.area
;
716 return area
.y
+ pct
* area
.h
;
720 * Convert from canvas/div coords to data coordinates.
721 * If specified, do this conversion for the coordinate system of a particular
722 * axis. Uses the first axis by default.
723 * Returns a two-element array: [X, Y].
725 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
726 * instead of toDataCoords(null, y, axis).
728 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
729 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
733 * Convert from canvas/div x coordinate to data coordinate.
735 * If x is null, this returns null.
737 Dygraph
.prototype.toDataXCoord
= function(x
) {
742 var area
= this.plotter_
.area
;
743 var xRange
= this.xAxisRange();
744 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
748 * Convert from canvas/div y coord to value.
750 * If y is null, this returns null.
751 * if axis is null, this uses the first axis.
753 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
758 var area
= this.plotter_
.area
;
759 var yRange
= this.yAxisRange(axis
);
761 if (typeof(axis
) == "undefined") axis
= 0;
762 if (!this.axes_
[axis
].logscale
) {
763 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
765 // Computing the inverse of toDomCoord.
766 var pct
= (y
- area
.y
) / area
.h
;
768 // Computing the inverse of toPercentYCoord. The function was arrived at with
769 // the following steps:
771 // Original calcuation:
772 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
774 // Move denominator to both sides:
775 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
777 // subtract logr1, and take the negative value.
778 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
780 // Swap both sides of the equation, and we can compute the log of the
781 // return value. Which means we just need to use that as the exponent in
783 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
785 var logr1
= Dygraph
.log10(yRange
[1]);
786 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
787 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
793 * Converts a y for an axis to a percentage from the top to the
794 * bottom of the drawing area.
796 * If the coordinate represents a value visible on the canvas, then
797 * the value will be between 0 and 1, where 0 is the top of the canvas.
798 * However, this method will return values outside the range, as
799 * values can fall outside the canvas.
801 * If y is null, this returns null.
802 * if axis is null, this uses the first axis.
804 * @param { Number } y The data y-coordinate.
805 * @param { Number } [axis] The axis number on which the data coordinate lives.
806 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
808 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
812 if (typeof(axis
) == "undefined") axis
= 0;
814 var yRange
= this.yAxisRange(axis
);
817 if (!this.axes_
[axis
].logscale
) {
818 // yRange[1] - y is unit distance from the bottom.
819 // yRange[1] - yRange[0] is the scale of the range.
820 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
821 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
823 var logr1
= Dygraph
.log10(yRange
[1]);
824 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
830 * Converts an x value to a percentage from the left to the right of
833 * If the coordinate represents a value visible on the canvas, then
834 * the value will be between 0 and 1, where 0 is the left of the canvas.
835 * However, this method will return values outside the range, as
836 * values can fall outside the canvas.
838 * If x is null, this returns null.
839 * @param { Number } x The data x-coordinate.
840 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
842 Dygraph
.prototype.toPercentXCoord
= function(x
) {
847 var xRange
= this.xAxisRange();
848 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
852 * Returns the number of columns (including the independent variable).
853 * @return { Integer } The number of columns.
855 Dygraph
.prototype.numColumns
= function() {
856 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
860 * Returns the number of rows (excluding any header/label row).
861 * @return { Integer } The number of rows, less any header.
863 Dygraph
.prototype.numRows
= function() {
864 return this.rawData_
.length
;
868 * Returns the full range of the x-axis, as determined by the most extreme
869 * values in the data set. Not affected by zooming, visibility, etc.
870 * TODO(danvk): merge w/ xAxisExtremes
871 * @return { Array<Number> } A [low, high] pair
874 Dygraph
.prototype.fullXRange_
= function() {
875 if (this.numRows() > 0) {
876 return [this.rawData_
[0][0], this.rawData_
[this.numRows() - 1][0]];
883 * Returns the value in the given row and column. If the row and column exceed
884 * the bounds on the data, returns null. Also returns null if the value is
886 * @param { Number} row The row number of the data (0-based). Row 0 is the
887 * first row of data, not a header row.
888 * @param { Number} col The column number of the data (0-based)
889 * @return { Number } The value in the specified cell or null if the row/col
892 Dygraph
.prototype.getValue
= function(row
, col
) {
893 if (row
< 0 || row
> this.rawData_
.length
) return null;
894 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
896 return this.rawData_
[row
][col
];
900 * Generates interface elements for the Dygraph: a containing div, a div to
901 * display the current point, and a textbox to adjust the rolling average
902 * period. Also creates the Renderer/Layout elements.
905 Dygraph
.prototype.createInterface_
= function() {
906 // Create the all-enclosing graph div
907 var enclosing
= this.maindiv_
;
909 this.graphDiv
= document
.createElement("div");
910 this.graphDiv
.style
.width
= this.width_
+ "px";
911 this.graphDiv
.style
.height
= this.height_
+ "px";
912 enclosing
.appendChild(this.graphDiv
);
914 // Create the canvas for interactive parts of the chart.
915 this.canvas_
= Dygraph
.createCanvas();
916 this.canvas_
.style
.position
= "absolute";
917 this.canvas_
.width
= this.width_
;
918 this.canvas_
.height
= this.height_
;
919 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
920 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
922 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
924 // ... and for static parts of the chart.
925 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
926 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
928 if (this.attr_('showRangeSelector')) {
929 // The range selector must be created here so that its canvases and contexts get created here.
930 // For some reason, if the canvases and contexts don't get created here, things don't work in IE.
931 // The range selector also sets xAxisHeight in order to reserve space.
932 this.rangeSelector_
= new DygraphRangeSelector(this);
935 // The interactive parts of the graph are drawn on top of the chart.
936 this.graphDiv
.appendChild(this.hidden_
);
937 this.graphDiv
.appendChild(this.canvas_
);
938 this.mouseEventElement_
= this.createMouseEventElement_();
940 // Create the grapher
941 this.layout_
= new DygraphLayout(this);
943 if (this.rangeSelector_
) {
944 // This needs to happen after the graph canvases are added to the div and the layout object is created.
945 this.rangeSelector_
.addToGraph(this.graphDiv
, this.layout_
);
950 this.mouseMoveHandler
= function(e
) {
951 dygraph
.mouseMove_(e
);
953 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler
);
955 this.mouseOutHandler
= function(e
) {
956 dygraph
.mouseOut_(e
);
958 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', this.mouseOutHandler
);
960 this.createDragInterface_();
962 this.resizeHandler
= function(e
) {
966 // Update when the window is resized.
967 // TODO(danvk): drop frames depending on complexity of the chart.
968 Dygraph
.addEvent(window
, 'resize', this.resizeHandler
);
972 * Detach DOM elements in the dygraph and null out all data references.
973 * Calling this when you're done with a dygraph can dramatically reduce memory
974 * usage. See, e.g., the tests/perf.html example.
976 Dygraph
.prototype.destroy
= function() {
977 var removeRecursive
= function(node
) {
978 while (node
.hasChildNodes()) {
979 removeRecursive(node
.firstChild
);
980 node
.removeChild(node
.firstChild
);
984 // remove mouse event handlers
985 Dygraph
.removeEvent(this.mouseEventElement_
, 'mouseout', this.mouseOutHandler
);
986 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler
);
987 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseUpHandler_
);
988 removeRecursive(this.maindiv_
);
990 var nullOut
= function(obj
) {
992 if (typeof(obj
[n
]) === 'object') {
997 // remove event handlers
998 Dygraph
.removeEvent(window
,'resize',this.resizeHandler
);
999 this.resizeHandler
= null;
1000 // These may not all be necessary, but it can't hurt...
1001 nullOut(this.layout_
);
1002 nullOut(this.plotter_
);
1007 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1008 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1009 * or the zoom rectangles) is done on this.canvas_.
1010 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1011 * @return {Object} The newly-created canvas
1014 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1015 var h
= Dygraph
.createCanvas();
1016 h
.style
.position
= "absolute";
1017 // TODO(danvk): h should be offset from canvas. canvas needs to include
1018 // some extra area to make it easier to zoom in on the far left and far
1019 // right. h needs to be precisely the plot area, so that clipping occurs.
1020 h
.style
.top
= canvas
.style
.top
;
1021 h
.style
.left
= canvas
.style
.left
;
1022 h
.width
= this.width_
;
1023 h
.height
= this.height_
;
1024 h
.style
.width
= this.width_
+ "px"; // for IE
1025 h
.style
.height
= this.height_
+ "px"; // for IE
1030 * Creates an overlay element used to handle mouse events.
1031 * @return {Object} The mouse event element.
1034 Dygraph
.prototype.createMouseEventElement_
= function() {
1035 if (this.isUsingExcanvas_
) {
1036 var elem
= document
.createElement("div");
1037 elem
.style
.position
= 'absolute';
1038 elem
.style
.backgroundColor
= 'white';
1039 elem
.style
.filter
= 'alpha(opacity=0)';
1040 elem
.style
.width
= this.width_
+ "px";
1041 elem
.style
.height
= this.height_
+ "px";
1042 this.graphDiv
.appendChild(elem
);
1045 return this.canvas_
;
1050 * Generate a set of distinct colors for the data series. This is done with a
1051 * color wheel. Saturation/Value are customizable, and the hue is
1052 * equally-spaced around the color wheel. If a custom set of colors is
1053 * specified, that is used instead.
1056 Dygraph
.prototype.setColors_
= function() {
1057 var num
= this.attr_("labels").length
- 1;
1059 var colors
= this.attr_('colors');
1062 var sat
= this.attr_('colorSaturation') || 1.0;
1063 var val
= this.attr_('colorValue') || 0.5;
1064 var half
= Math
.ceil(num
/ 2);
1065 for (i
= 1; i
<= num
; i
++) {
1066 if (!this.visibility()[i
-1]) continue;
1067 // alternate colors for high contrast.
1068 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
1069 var hue
= (1.0 * idx
/ (1 + num
));
1070 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
1073 for (i
= 0; i
< num
; i
++) {
1074 if (!this.visibility()[i
]) continue;
1075 var colorStr
= colors
[i
% colors
.length
];
1076 this.colors_
.push(colorStr
);
1080 this.plotter_
.setColors(this.colors_
);
1084 * Return the list of colors. This is either the list of colors passed in the
1085 * attributes or the autogenerated list of rgb(r,g,b) strings.
1086 * This does not return colors for invisible series.
1087 * @return {Array<string>} The list of colors.
1089 Dygraph
.prototype.getColors
= function() {
1090 return this.colors_
;
1094 * Returns a few attributes of a series, i.e. its color, its visibility, which
1095 * axis it's assigned to, and its column in the original data.
1096 * Returns null if the series does not exist.
1097 * Otherwise, returns an object with column, visibility, color and axis properties.
1098 * The "axis" property will be set to 1 for y1 and 2 for y2.
1099 * The "column" property can be fed back into getValue(row, column) to get
1100 * values for this series.
1102 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1104 var labels
= this.getLabels();
1105 for (var i
= 1; i
< labels
.length
; i
++) {
1106 if (labels
[i
] == series_name
) {
1111 if (idx
== -1) return null;
1116 visible
: this.visibility()[idx
- 1],
1117 color
: this.plotter_
.colors
[series_name
],
1118 axis
: 1 + this.seriesToAxisMap_
[series_name
]
1123 * Create the text box to adjust the averaging period
1126 Dygraph
.prototype.createRollInterface_
= function() {
1127 // Create a roller if one doesn't exist already.
1128 if (!this.roller_
) {
1129 this.roller_
= document
.createElement("input");
1130 this.roller_
.type
= "text";
1131 this.roller_
.style
.display
= "none";
1132 this.graphDiv
.appendChild(this.roller_
);
1135 var display
= this.attr_('showRoller') ? 'block' : 'none';
1137 var area
= this.plotter_
.area
;
1138 var textAttr
= { "position": "absolute",
1140 "top": (area
.y
+ area
.h
- 25) + "px",
1141 "left": (area
.x
+ 1) + "px",
1144 this.roller_
.size
= "2";
1145 this.roller_
.value
= this.rollPeriod_
;
1146 for (var name
in textAttr
) {
1147 if (textAttr
.hasOwnProperty(name
)) {
1148 this.roller_
.style
[name
] = textAttr
[name
];
1153 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1158 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1159 * canvas (i.e. DOM Coords).
1161 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1162 return Dygraph
.pageX(e
) - context
.px
;
1167 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1168 * canvas (i.e. DOM Coords).
1170 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1171 return Dygraph
.pageY(e
) - context
.py
;
1175 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1179 Dygraph
.prototype.createDragInterface_
= function() {
1181 // Tracks whether the mouse is down right now
1183 isPanning
: false, // is this drag part of a pan?
1184 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1185 dragStartX
: null, // pixel coordinates
1186 dragStartY
: null, // pixel coordinates
1187 dragEndX
: null, // pixel coordinates
1188 dragEndY
: null, // pixel coordinates
1189 dragDirection
: null,
1190 prevEndX
: null, // pixel coordinates
1191 prevEndY
: null, // pixel coordinates
1192 prevDragDirection
: null,
1193 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1195 // The value on the left side of the graph when a pan operation starts.
1196 initialLeftmostDate
: null,
1198 // The number of units each pixel spans. (This won't be valid for log
1200 xUnitsPerPixel
: null,
1202 // TODO(danvk): update this comment
1203 // The range in second/value units that the viewport encompasses during a
1204 // panning operation.
1207 // Top-left corner of the canvas, in DOM coords
1208 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1212 // Values for use with panEdgeFraction, which limit how far outside the
1213 // graph's data boundaries it can be panned.
1214 boundedDates
: null, // [minDate, maxDate]
1215 boundedValues
: null, // [[minValue, maxValue] ...]
1217 initializeMouseDown
: function(event
, g
, context
) {
1218 // prevents mouse drags from selecting page text.
1219 if (event
.preventDefault
) {
1220 event
.preventDefault(); // Firefox, Chrome, etc.
1222 event
.returnValue
= false; // IE
1223 event
.cancelBubble
= true;
1226 context
.px
= Dygraph
.findPosX(g
.canvas_
);
1227 context
.py
= Dygraph
.findPosY(g
.canvas_
);
1228 context
.dragStartX
= g
.dragGetX_(event
, context
);
1229 context
.dragStartY
= g
.dragGetY_(event
, context
);
1230 context
.cancelNextDblclick
= false;
1234 var interactionModel
= this.attr_("interactionModel");
1236 // Self is the graph.
1239 // Function that binds the graph and context to the handler.
1240 var bindHandler
= function(handler
) {
1241 return function(event
) {
1242 handler(event
, self
, context
);
1246 for (var eventName
in interactionModel
) {
1247 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1248 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
1249 bindHandler(interactionModel
[eventName
]));
1252 // If the user releases the mouse button during a drag, but not over the
1253 // canvas, then it doesn't count as a zooming action.
1254 this.mouseUpHandler_
= function(event
) {
1255 if (context
.isZooming
|| context
.isPanning
) {
1256 context
.isZooming
= false;
1257 context
.dragStartX
= null;
1258 context
.dragStartY
= null;
1261 if (context
.isPanning
) {
1262 context
.isPanning
= false;
1263 context
.draggingDate
= null;
1264 context
.dateRange
= null;
1265 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1266 delete self
.axes_
[i
].draggingValue
;
1267 delete self
.axes_
[i
].dragValueRange
;
1272 Dygraph
.addEvent(document
, 'mouseup', this.mouseUpHandler_
);
1276 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1277 * up any previous zoom rectangles that were drawn. This could be optimized to
1278 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1281 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1282 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1283 * @param {Number} startX The X position where the drag started, in canvas
1285 * @param {Number} endX The current X position of the drag, in canvas coords.
1286 * @param {Number} startY The Y position where the drag started, in canvas
1288 * @param {Number} endY The current Y position of the drag, in canvas coords.
1289 * @param {Number} prevDirection the value of direction on the previous call to
1290 * this function. Used to avoid excess redrawing
1291 * @param {Number} prevEndX The value of endX on the previous call to this
1292 * function. Used to avoid excess redrawing
1293 * @param {Number} prevEndY The value of endY on the previous call to this
1294 * function. Used to avoid excess redrawing
1297 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1298 endY
, prevDirection
, prevEndX
,
1300 var ctx
= this.canvas_ctx_
;
1302 // Clean up from the previous rect if necessary
1303 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1304 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1305 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1306 } else if (prevDirection
== Dygraph
.VERTICAL
){
1307 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1308 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1311 // Draw a light-grey rectangle to show the new viewing area
1312 if (direction
== Dygraph
.HORIZONTAL
) {
1313 if (endX
&& startX
) {
1314 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1315 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1316 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1318 } else if (direction
== Dygraph
.VERTICAL
) {
1319 if (endY
&& startY
) {
1320 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1321 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1322 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1326 if (this.isUsingExcanvas_
) {
1327 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1332 * Clear the zoom rectangle (and perform no zoom).
1335 Dygraph
.prototype.clearZoomRect_
= function() {
1336 this.currentZoomRectArgs_
= null;
1337 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1341 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1342 * the canvas. The exact zoom window may be slightly larger if there are no data
1343 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1344 * which accepts dates that match the raw data. This function redraws the graph.
1346 * @param {Number} lowX The leftmost pixel value that should be visible.
1347 * @param {Number} highX The rightmost pixel value that should be visible.
1350 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1351 this.currentZoomRectArgs_
= null;
1352 // Find the earliest and latest dates contained in this canvasx range.
1353 // Convert the call to date ranges of the raw data.
1354 var minDate
= this.toDataXCoord(lowX
);
1355 var maxDate
= this.toDataXCoord(highX
);
1356 this.doZoomXDates_(minDate
, maxDate
);
1360 * Transition function to use in animations. Returns values between 0.0
1361 * (totally old values) and 1.0 (totally new values) for each frame.
1364 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1366 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1370 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1371 * method with doZoomX which accepts pixel coordinates. This function redraws
1374 * @param {Number} minDate The minimum date that should be visible.
1375 * @param {Number} maxDate The maximum date that should be visible.
1378 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1379 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1380 // can produce strange effects. Rather than the y-axis transitioning slowly
1381 // between values, it can jerk around.)
1382 var old_window
= this.xAxisRange();
1383 var new_window
= [minDate
, maxDate
];
1384 this.zoomed_x_
= true;
1386 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1387 if (that
.attr_("zoomCallback")) {
1388 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1394 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1395 * the canvas. This function redraws the graph.
1397 * @param {Number} lowY The topmost pixel value that should be visible.
1398 * @param {Number} highY The lowest pixel value that should be visible.
1401 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1402 this.currentZoomRectArgs_
= null;
1403 // Find the highest and lowest values in pixel range for each axis.
1404 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1405 // This is because pixels increase as you go down on the screen, whereas data
1406 // coordinates increase as you go up the screen.
1407 var oldValueRanges
= this.yAxisRanges();
1408 var newValueRanges
= [];
1409 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1410 var hi
= this.toDataYCoord(lowY
, i
);
1411 var low
= this.toDataYCoord(highY
, i
);
1412 newValueRanges
.push([low
, hi
]);
1415 this.zoomed_y_
= true;
1417 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1418 if (that
.attr_("zoomCallback")) {
1419 var xRange
= that
.xAxisRange();
1420 that
.attr_("zoomCallback")(xRange
[0], xRange
[1], that
.yAxisRanges());
1426 * Reset the zoom to the original view coordinates. This is the same as
1427 * double-clicking on the graph.
1431 Dygraph
.prototype.doUnzoom_
= function() {
1432 var dirty
= false, dirtyX
= false, dirtyY
= false;
1433 if (this.dateWindow_
!== null) {
1438 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1439 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1445 // Clear any selection, since it's likely to be drawn in the wrong place.
1446 this.clearSelection();
1449 this.zoomed_x_
= false;
1450 this.zoomed_y_
= false;
1452 var minDate
= this.rawData_
[0][0];
1453 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1455 // With only one frame, don't bother calculating extreme ranges.
1456 // TODO(danvk): merge this block w/ the code below
.
1457 if (!this.attr_("animatedZooms")) {
1458 this.dateWindow_
= null;
1459 for (i
= 0; i
< this.axes_
.length
; i
++) {
1460 if (this.axes_
[i
].valueWindow
!== null) {
1461 delete this.axes_
[i
].valueWindow
;
1465 if (this.attr_("zoomCallback")) {
1466 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1471 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1473 oldWindow
= this.xAxisRange();
1474 newWindow
= [minDate
, maxDate
];
1478 oldValueRanges
= this.yAxisRanges();
1479 // TODO(danvk): this is pretty inefficient
1480 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1481 var extremes
= packed
[1];
1483 // this has the side-effect of modifying this.axes_.
1484 // this doesn't make much sense in this context, but it's convenient (we
1485 // need this.axes_[*].extremeValues) and not harmful since we'll be
1486 // calling drawGraph_ shortly, which clobbers these values.
1487 this.computeYAxisRanges_(extremes
);
1489 newValueRanges
= [];
1490 for (i
= 0; i
< this.axes_
.length
; i
++) {
1491 var axis
= this.axes_
[i
];
1492 newValueRanges
.push(axis
.valueRange
!= null ? axis
.valueRange
: axis
.extremeRange
);
1497 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1499 that
.dateWindow_
= null;
1500 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1501 if (that
.axes_
[i
].valueWindow
!== null) {
1502 delete that
.axes_
[i
].valueWindow
;
1505 if (that
.attr_("zoomCallback")) {
1506 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1513 * Combined animation logic for all zoom functions.
1514 * either the x parameters or y parameters may be null.
1517 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1518 var steps
= this.attr_("animatedZooms") ? Dygraph
.ANIMATION_STEPS
: 1;
1521 var valueRanges
= [];
1524 if (oldXRange
!== null && newXRange
!== null) {
1525 for (step
= 1; step
<= steps
; step
++) {
1526 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1527 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1528 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1532 if (oldYRanges
!== null && newYRanges
!== null) {
1533 for (step
= 1; step
<= steps
; step
++) {
1534 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1536 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1537 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1538 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1540 valueRanges
[step
-1] = thisRange
;
1545 Dygraph
.repeatAndCleanup(function(step
) {
1546 if (valueRanges
.length
) {
1547 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1548 var w
= valueRanges
[step
][i
];
1549 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1552 if (windows
.length
) {
1553 that
.dateWindow_
= windows
[step
];
1556 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1560 * Get the current graph's area object.
1562 * Returns: {x, y, w, h}
1564 Dygraph
.prototype.getArea
= function() {
1565 return this.plotter_
.area
;
1569 * Convert a mouse event to DOM coordinates relative to the graph origin.
1571 * Returns a two-element array: [X, Y].
1573 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1574 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1575 var canvasy
= Dygraph
.pageY(event
) - Dygraph
.findPosY(this.mouseEventElement_
);
1576 return [canvasx
, canvasy
];
1580 * Given a canvas X coordinate, find the closest row.
1581 * @param {Number} domX graph-relative DOM X coordinate
1582 * Returns: row number, integer
1585 Dygraph
.prototype.findClosestRow
= function(domX
) {
1586 var minDistX
= Infinity
;
1588 var points
= this.layout_
.points
;
1589 var l
= points
.length
;
1590 for (var i
= 0; i
< l
; i
++) {
1591 var point
= points
[i
];
1592 if (!Dygraph
.isValidPoint(point
, true)) continue;
1593 var dist
= Math
.abs(point
.canvasx
- domX
);
1594 if (dist
< minDistX
) {
1599 return this.idxToRow_(idx
);
1603 * Given canvas X,Y coordinates, find the closest point.
1605 * This finds the individual data point across all visible series
1606 * that's closest to the supplied DOM coordinates using the standard
1607 * Euclidean X,Y distance.
1609 * @param {Number} domX graph-relative DOM X coordinate
1610 * @param {Number} domY graph-relative DOM Y coordinate
1611 * Returns: {row, seriesName, point}
1614 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1615 var minDist
= Infinity
;
1617 var points
= this.layout_
.points
;
1618 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
;
1619 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1620 var first
= this.layout_
.setPointsOffsets
[setIdx
];
1621 var len
= this.layout_
.setPointsLengths
[setIdx
];
1622 for (var i
= 0; i
< len
; ++i
) {
1623 var point
= points
[first
+ i
];
1624 if (!Dygraph
.isValidPoint(point
)) continue;
1625 dx
= point
.canvasx
- domX
;
1626 dy
= point
.canvasy
- domY
;
1627 dist
= dx
* dx
+ dy
* dy
;
1628 if (dist
< minDist
) {
1630 closestPoint
= point
;
1631 closestSeries
= setIdx
;
1636 var name
= this.layout_
.setNames
[closestSeries
];
1638 row
: idx
+ this.getLeftBoundary_(),
1645 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1647 * This first finds the X data point closest to the supplied DOM X coordinate,
1648 * then finds the series which puts the Y coordinate on top of its filled area,
1649 * using linear interpolation between adjacent point pairs.
1651 * @param {Number} domX graph-relative DOM X coordinate
1652 * @param {Number} domY graph-relative DOM Y coordinate
1653 * Returns: {row, seriesName, point}
1656 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1657 var row
= this.findClosestRow(domX
);
1658 var boundary
= this.getLeftBoundary_();
1659 var rowIdx
= row
- boundary
;
1660 var points
= this.layout_
.points
;
1661 var closestPoint
, closestSeries
;
1662 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1663 var first
= this.layout_
.setPointsOffsets
[setIdx
];
1664 var len
= this.layout_
.setPointsLengths
[setIdx
];
1665 if (rowIdx
>= len
) continue;
1666 var p1
= points
[first
+ rowIdx
];
1667 if (!Dygraph
.isValidPoint(p1
)) continue;
1668 var py
= p1
.canvasy
;
1669 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < len
) {
1670 // interpolate series Y value using next point
1671 var p2
= points
[first
+ rowIdx
+ 1];
1672 if (Dygraph
.isValidPoint(p2
)) {
1673 var dx
= p2
.canvasx
- p1
.canvasx
;
1675 var r
= (domX
- p1
.canvasx
) / dx
;
1676 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1679 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1680 // interpolate series Y value using previous point
1681 var p0
= points
[first
+ rowIdx
- 1];
1682 if (Dygraph
.isValidPoint(p0
)) {
1683 var dx
= p1
.canvasx
- p0
.canvasx
;
1685 var r
= (p1
.canvasx
- domX
) / dx
;
1686 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1690 // Stop if the point (domX, py) is above this series' upper edge
1691 if (setIdx
== 0 || py
< domY
) {
1693 closestSeries
= setIdx
;
1696 var name
= this.layout_
.setNames
[closestSeries
];
1705 * When the mouse moves in the canvas, display information about a nearby data
1706 * point and draw dots over those points in the data series. This function
1707 * takes care of cleanup of previously-drawn dots.
1708 * @param {Object} event The mousemove event from the browser.
1711 Dygraph
.prototype.mouseMove_
= function(event
) {
1712 // This prevents JS errors when mousing over the canvas before data loads.
1713 var points
= this.layout_
.points
;
1714 if (points
=== undefined
) return;
1716 var canvasCoords
= this.eventToDomCoords(event
);
1717 var canvasx
= canvasCoords
[0];
1718 var canvasy
= canvasCoords
[1];
1720 var highlightSeriesOpts
= this.attr_("highlightSeriesOpts");
1721 var selectionChanged
= false;
1722 if (highlightSeriesOpts
) {
1724 if (this.attr_("stackedGraph")) {
1725 closest
= this.findStackedPoint(canvasx
, canvasy
);
1727 closest
= this.findClosestPoint(canvasx
, canvasy
);
1729 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1731 var idx
= this.findClosestRow(canvasx
);
1732 selectionChanged
= this.setSelection(idx
);
1735 var callback
= this.attr_("highlightCallback");
1736 if (callback
&& selectionChanged
) {
1737 callback(event
, this.lastx_
, this.selPoints_
, this.lastRow_
, this.highlightSet_
);
1742 * Fetch left offset from first defined boundaryIds record (see bug #236).
1745 Dygraph
.prototype.getLeftBoundary_
= function() {
1746 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1747 if (this.boundaryIds_
[i
] !== undefined
) {
1748 return this.boundaryIds_
[i
][0];
1755 * Transforms layout_.points index into data row number.
1756 * @param int layout_.points index
1757 * @return int row number, or -1 if none could be found.
1760 Dygraph
.prototype.idxToRow_
= function(idx
) {
1761 if (idx
< 0) return -1;
1763 var boundary
= this.getLeftBoundary_();
1764 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1765 var set
= this.layout_
.datasets
[setIdx
];
1766 if (idx
< set
.length
) {
1767 return boundary
+ idx
;
1774 Dygraph
.prototype.animateSelection_
= function(direction
) {
1775 var totalSteps
= 10;
1777 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1778 if (this.animateId
=== undefined
) this.animateId
= 0;
1779 var start
= this.fadeLevel
;
1780 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1782 if (this.fadeLevel
) {
1783 this.updateSelection_(1.0);
1788 var thisId
= ++this.animateId
;
1790 Dygraph
.repeatAndCleanup(
1792 // ignore simultaneous animations
1793 if (that
.animateId
!= thisId
) return;
1795 that
.fadeLevel
+= direction
;
1796 if (that
.fadeLevel
=== 0) {
1797 that
.clearSelection();
1799 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1802 steps
, millis
, function() {});
1806 * Draw dots over the selectied points in the data series. This function
1807 * takes care of cleanup of previously-drawn dots.
1810 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1811 var defaultPrevented
= this.cascadeEvents_('select', {
1812 selectedX
: this.lastx_
,
1813 selectedPoints
: this.selPoints_
1815 // TODO(danvk): use defaultPrevented here?
1817 // Clear the previously drawn vertical, if there is one
1819 var ctx
= this.canvas_ctx_
;
1820 if (this.attr_('highlightSeriesOpts')) {
1821 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1822 var alpha
= 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
1824 // Activating background fade includes an animation effect for a gradual
1825 // fade. TODO(klausw): make this independently configurable if it causes
1826 // issues? Use a shared preference to control animations?
1827 var animateBackgroundFade
= true;
1828 if (animateBackgroundFade
) {
1829 if (opt_animFraction
=== undefined
) {
1830 // start a new animation
1831 this.animateSelection_(1);
1834 alpha
*= opt_animFraction
;
1836 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1837 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1839 var setIdx
= this.datasetIndexFromSetName_(this.highlightSet_
);
1840 this.plotter_
._drawLine(ctx
, setIdx
);
1841 } else if (this.previousVerticalX_
>= 0) {
1842 // Determine the maximum highlight circle size.
1843 var maxCircleSize
= 0;
1844 var labels
= this.attr_('labels');
1845 for (i
= 1; i
< labels
.length
; i
++) {
1846 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1847 if (r
> maxCircleSize
) maxCircleSize
= r
;
1849 var px
= this.previousVerticalX_
;
1850 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1851 2 * maxCircleSize
+ 2, this.height_
);
1854 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
1855 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
1858 if (this.selPoints_
.length
> 0) {
1859 // Draw colored circles over the center of each selected point
1860 var canvasx
= this.selPoints_
[0].canvasx
;
1862 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1863 var pt
= this.selPoints_
[i
];
1864 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1866 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1867 var callback
= this.attr_("drawHighlightPointCallback", pt
.name
);
1868 var color
= this.plotter_
.colors
[pt
.name
];
1870 callback
= Dygraph
.Circles
.DEFAULT
;
1872 ctx
.lineWidth
= this.attr_('strokeWidth', pt
.name
);
1873 ctx
.strokeStyle
= color
;
1874 ctx
.fillStyle
= color
;
1875 callback(this.g
, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1880 this.previousVerticalX_
= canvasx
;
1885 * Manually set the selected points and display information about them in the
1886 * legend. The selection can be cleared using clearSelection() and queried
1887 * using getSelection().
1888 * @param { Integer } row number that should be highlighted (i.e. appear with
1889 * hover dots on the chart). Set to false to clear any selection.
1890 * @param { seriesName } optional series name to highlight that series with the
1891 * the highlightSeriesOpts setting.
1893 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
) {
1894 // Extract the points we've selected
1895 this.selPoints_
= [];
1898 if (row
!== false) {
1899 row
-= this.getLeftBoundary_();
1902 var changed
= false;
1903 if (row
!== false && row
>= 0) {
1904 if (row
!= this.lastRow_
) changed
= true;
1905 this.lastRow_
= row
;
1906 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1907 var set
= this.layout_
.datasets
[setIdx
];
1908 if (row
< set
.length
) {
1909 var point
= this.layout_
.points
[pos
+row
];
1911 if (this.attr_("stackedGraph")) {
1912 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
1915 if (!(point
.yval
=== null)) this.selPoints_
.push(point
);
1920 if (this.lastRow_
>= 0) changed
= true;
1924 if (this.selPoints_
.length
) {
1925 this.lastx_
= this.selPoints_
[0].xval
;
1930 if (opt_seriesName
!== undefined
) {
1931 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
1932 this.highlightSet_
= opt_seriesName
;
1936 this.updateSelection_(undefined
);
1942 * The mouse has left the canvas. Clear out whatever artifacts remain
1943 * @param {Object} event the mouseout event from the browser.
1946 Dygraph
.prototype.mouseOut_
= function(event
) {
1947 if (this.attr_("unhighlightCallback")) {
1948 this.attr_("unhighlightCallback")(event
);
1951 if (this.attr_("hideOverlayOnMouseOut")) {
1952 this.clearSelection();
1957 * Clears the current selection (i.e. points that were highlighted by moving
1958 * the mouse over the chart).
1960 Dygraph
.prototype.clearSelection
= function() {
1961 this.cascadeEvents_('deselect', {});
1963 // Get rid of the overlay data
1964 if (this.fadeLevel
) {
1965 this.animateSelection_(-1);
1968 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1970 this.selPoints_
= [];
1973 this.highlightSet_
= null;
1977 * Returns the number of the currently selected row. To get data for this row,
1978 * you can use the getValue method.
1979 * @return { Integer } row number, or -1 if nothing is selected
1981 Dygraph
.prototype.getSelection
= function() {
1982 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1986 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
1987 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
1988 return row
+ this.getLeftBoundary_();
1995 * Returns the name of the currently-highlighted series.
1996 * Only available when the highlightSeriesOpts option is in use.
1998 Dygraph
.prototype.getHighlightSeries
= function() {
1999 return this.highlightSet_
;
2003 * Fires when there's data available to be graphed.
2004 * @param {String} data Raw CSV data to be plotted
2007 Dygraph
.prototype.loadedEvent_
= function(data
) {
2008 this.rawData_
= this.parseCSV_(data
);
2013 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2016 Dygraph
.prototype.addXTicks_
= function() {
2017 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2019 if (this.dateWindow_
) {
2020 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2022 range
= this.fullXRange_();
2025 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2026 var xTicks
= xAxisOptionsView('ticker')(
2029 this.width_
, // TODO(danvk): should be area.width
2032 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2033 // console.log(msg);
2034 this.layout_
.setXTicks(xTicks
);
2039 * Computes the range of the data series (including confidence intervals).
2040 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2041 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2042 * @return [low, high]
2044 Dygraph
.prototype.extremeValues_
= function(series
) {
2045 var minY
= null, maxY
= null, j
, y
;
2047 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2049 // With custom bars, maxY is the max of the high values.
2050 for (j
= 0; j
< series
.length
; j
++) {
2051 y
= series
[j
][1][0];
2053 var low
= y
- series
[j
][1][1];
2054 var high
= y
+ series
[j
][1][2];
2055 if (low
> y
) low
= y
; // this can happen with custom bars,
2056 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2057 if (maxY
=== null || high
> maxY
) {
2060 if (minY
=== null || low
< minY
) {
2065 for (j
= 0; j
< series
.length
; j
++) {
2067 if (y
=== null || isNaN(y
)) continue;
2068 if (maxY
=== null || y
> maxY
) {
2071 if (minY
=== null || y
< minY
) {
2077 return [minY
, maxY
];
2082 * This function is called once when the chart's data is changed or the options
2083 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2084 * idea is that values derived from the chart's data can be computed here,
2085 * rather than every time the chart is drawn. This includes things like the
2086 * number of axes, rolling averages, etc.
2088 Dygraph
.prototype.predraw_
= function() {
2089 var start
= new Date();
2091 // TODO(danvk): move more computations out of drawGraph_ and into here.
2092 this.computeYAxes_();
2094 // Create a new plotter.
2095 if (this.plotter_
) this.plotter_
.clear();
2096 this.plotter_
= new DygraphCanvasRenderer(this,
2101 // The roller sits in the bottom left corner of the chart. We don't know where
2102 // this will be until the options are available, so it's positioned here.
2103 this.createRollInterface_();
2105 this.cascadeEvents_('predraw');
2107 if (this.rangeSelector_
) {
2108 this.rangeSelector_
.renderStaticLayer();
2111 // Convert the raw data (a 2D array) into the internal format and compute
2112 // rolling averages.
2113 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2114 for (var i
= 1; i
< this.numColumns(); i
++) {
2115 var logScale
= this.attr_('logscale', i
); // TODO(klausw): this looks wrong
2116 var series
= this.extractSeries_(this.rawData_
, i
, logScale
);
2117 series
= this.rollingAverage(series
, this.rollPeriod_
);
2118 this.rolledSeries_
.push(series
);
2121 // If the data or options have changed, then we'd better redraw.
2124 // This is used to determine whether to do various animations.
2125 var end
= new Date();
2126 this.drawingTimeMs_
= (end
- start
);
2130 * Loop over all fields and create datasets, calculating extreme y-values for
2131 * each series and extreme x-indices as we go.
2133 * dateWindow is passed in as an explicit parameter so that we can compute
2134 * extreme values "speculatively", i.e. without actually setting state on the
2137 * TODO(danvk): make this more of a true function
2138 * @return [ datasets, seriesExtremes, boundaryIds ]
2141 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2142 var boundaryIds
= [];
2143 var cumulative_y
= []; // For stacked series.
2145 var extremes
= {}; // series name -> [low, high]
2148 // Loop over the fields (series). Go from the last to the first,
2149 // because if they're stacked that's how we accumulate the values.
2150 var num_series
= rolledSeries
.length
- 1;
2151 for (i
= num_series
; i
>= 1; i
--) {
2152 if (!this.visibility()[i
- 1]) continue;
2154 // TODO(danvk): is this copy really necessary?
2156 for (j
= 0; j
< rolledSeries
[i
].length
; j
++) {
2157 series
.push(rolledSeries
[i
][j
]);
2160 // Prune down to the desired range, if necessary (for zooming)
2161 // Because there can be lines going to points outside of the visible area,
2162 // we actually prune to visible points, plus one on either side.
2163 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2165 var low
= dateWindow
[0];
2166 var high
= dateWindow
[1];
2168 // TODO(danvk): do binary search instead of linear search.
2169 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2170 var firstIdx
= null, lastIdx
= null;
2171 for (k
= 0; k
< series
.length
; k
++) {
2172 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2175 if (series
[k
][0] <= high
) {
2179 if (firstIdx
=== null) firstIdx
= 0;
2180 if (firstIdx
> 0) firstIdx
--;
2181 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2182 if (lastIdx
< series
.length
- 1) lastIdx
++;
2183 boundaryIds
[i
-1] = [firstIdx
, lastIdx
];
2184 for (k
= firstIdx
; k
<= lastIdx
; k
++) {
2185 pruned
.push(series
[k
]);
2189 boundaryIds
[i
-1] = [0, series
.length
-1];
2192 var seriesExtremes
= this.extremeValues_(series
);
2195 for (j
=0; j
<series
.length
; j
++) {
2196 series
[j
] = [series
[j
][0],
2201 } else if (this.attr_("stackedGraph")) {
2202 var l
= series
.length
;
2204 for (j
= 0; j
< l
; j
++) {
2205 // If one data set has a NaN, let all subsequent stacked
2206 // sets inherit the NaN -- only start at 0 for the first set.
2207 var x
= series
[j
][0];
2208 if (cumulative_y
[x
] === undefined
) {
2209 cumulative_y
[x
] = 0;
2212 actual_y
= series
[j
][1];
2213 if (actual_y
=== null) {
2214 series
[j
] = [x
, null];
2218 cumulative_y
[x
] += actual_y
;
2220 series
[j
] = [x
, cumulative_y
[x
]];
2222 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2223 seriesExtremes
[1] = cumulative_y
[x
];
2225 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2226 seriesExtremes
[0] = cumulative_y
[x
];
2231 var seriesName
= this.attr_("labels")[i
];
2232 extremes
[seriesName
] = seriesExtremes
;
2233 datasets
[i
] = series
;
2236 // For stacked graphs, a NaN value for any point in the sum should create a
2237 // clean gap in the graph. Back-propagate NaNs to all points at this X value.
2238 if (this.attr_("stackedGraph")) {
2239 for (k
= datasets
.length
- 1; k
>= 0; --k
) {
2240 // Use the first nonempty dataset to get X values.
2241 if (!datasets
[k
]) continue;
2242 for (j
= 0; j
< datasets
[k
].length
; j
++) {
2243 var x
= datasets
[k
][j
][0];
2244 if (isNaN(cumulative_y
[x
])) {
2245 // Set all Y values to NaN at that X value.
2246 for (i
= datasets
.length
- 1; i
>= 0; i
--) {
2247 if (!datasets
[i
]) continue;
2248 datasets
[i
][j
][1] = NaN
;
2256 return [ datasets
, extremes
, boundaryIds
];
2260 * Update the graph with new data. This method is called when the viewing area
2261 * has changed. If the underlying data or options have changed, predraw_ will
2262 * be called before drawGraph_ is called.
2266 Dygraph
.prototype.drawGraph_
= function() {
2267 var start
= new Date();
2269 // This is used to set the second parameter to drawCallback, below.
2270 var is_initial_draw
= this.is_initial_draw_
;
2271 this.is_initial_draw_
= false;
2273 this.layout_
.removeAllDatasets();
2275 this.attrs_
.pointSize
= 0.5 * this.attr_('highlightCircleSize');
2277 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2278 var datasets
= packed
[0];
2279 var extremes
= packed
[1];
2280 this.boundaryIds_
= packed
[2];
2282 this.setIndexByName_
= {};
2283 var labels
= this.attr_("labels");
2284 if (labels
.length
> 0) {
2285 this.setIndexByName_
[labels
[0]] = 0;
2288 for (var i
= 1; i
< datasets
.length
; i
++) {
2289 this.setIndexByName_
[labels
[i
]] = i
;
2290 if (!this.visibility()[i
- 1]) continue;
2291 this.layout_
.addDataset(labels
[i
], datasets
[i
]);
2292 this.datasetIndex_
[i
] = dataIdx
++;
2295 this.computeYAxisRanges_(extremes
);
2296 this.layout_
.setYAxes(this.axes_
);
2300 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2301 var tmp_zoomed_x
= this.zoomed_x_
;
2302 // Tell PlotKit to use this new data and render itself
2303 this.layout_
.setDateWindow(this.dateWindow_
);
2304 this.zoomed_x_
= tmp_zoomed_x
;
2305 this.layout_
.evaluateWithError();
2306 this.renderGraph_(is_initial_draw
);
2308 if (this.attr_("timingName")) {
2309 var end
= new Date();
2311 console
.log(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2317 * This does the work of drawing the chart. It assumes that the layout and axis
2318 * scales have already been set (e.g. by predraw_).
2322 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2323 this.plotter_
.clear();
2324 this.plotter_
.render();
2325 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2326 this.canvas_
.height
);
2328 // Generate a static legend before any particular point is selected.
2330 if (this.rangeSelector_
) {
2331 this.rangeSelector_
.renderInteractiveLayer();
2334 this.cascadeEvents_('drawChart');
2335 if (this.attr_("drawCallback") !== null) {
2336 this.attr_("drawCallback")(this, is_initial_draw
);
2342 * Determine properties of the y-axes which are independent of the data
2343 * currently being displayed. This includes things like the number of axes and
2344 * the style of the axes. It does not include the range of each axis and its
2346 * This fills in this.axes_ and this.seriesToAxisMap_.
2347 * axes_ = [ { options } ]
2348 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2349 * indices are into the axes_ array.
2351 Dygraph
.prototype.computeYAxes_
= function() {
2352 // Preserve valueWindow settings if they exist, and if the user hasn't
2353 // specified a new valueRange.
2354 var i
, valueWindows
, seriesName
, axis
, index
, opts
, v
;
2355 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2357 for (index
= 0; index
< this.axes_
.length
; index
++) {
2358 valueWindows
.push(this.axes_
[index
].valueWindow
);
2362 this.axes_
= [{ yAxisId
: 0, g
: this }]; // always have at least one y-axis.
2363 this.seriesToAxisMap_
= {};
2365 // Get a list of series names.
2366 var labels
= this.attr_("labels");
2368 for (i
= 1; i
< labels
.length
; i
++) series
[labels
[i
]] = (i
- 1);
2370 // all options which could be applied per-axis:
2378 'axisLabelFontSize',
2383 // Copy global axis options over to the first axis.
2384 for (i
= 0; i
< axisOptions
.length
; i
++) {
2385 var k
= axisOptions
[i
];
2387 if (v
) this.axes_
[0][k
] = v
;
2390 // Go through once and add all the axes.
2391 for (seriesName
in series
) {
2392 if (!series
.hasOwnProperty(seriesName
)) continue;
2393 axis
= this.attr_("axis", seriesName
);
2394 if (axis
=== null) {
2395 this.seriesToAxisMap_
[seriesName
] = 0;
2398 if (typeof(axis
) == 'object') {
2399 // Add a new axis, making a copy of its per-axis options.
2401 Dygraph
.update(opts
, this.axes_
[0]);
2402 Dygraph
.update(opts
, { valueRange
: null }); // shouldn't inherit this.
2403 var yAxisId
= this.axes_
.length
;
2404 opts
.yAxisId
= yAxisId
;
2406 Dygraph
.update(opts
, axis
);
2407 this.axes_
.push(opts
);
2408 this.seriesToAxisMap_
[seriesName
] = yAxisId
;
2412 // Go through one more time and assign series to an axis defined by another
2413 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2414 for (seriesName
in series
) {
2415 if (!series
.hasOwnProperty(seriesName
)) continue;
2416 axis
= this.attr_("axis", seriesName
);
2417 if (typeof(axis
) == 'string') {
2418 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
2419 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
2420 "series " + axis
+ ", which does not define its own axis.");
2423 var idx
= this.seriesToAxisMap_
[axis
];
2424 this.seriesToAxisMap_
[seriesName
] = idx
;
2428 if (valueWindows
!== undefined
) {
2429 // Restore valueWindow settings.
2430 for (index
= 0; index
< valueWindows
.length
; index
++) {
2431 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2436 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2438 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2439 v
= opts("valueRange");
2440 if (v
) this.axes_
[axis
].valueRange
= v
;
2441 } else { // To keep old behavior
2442 var axes
= this.user_attrs_
.axes
;
2443 if (axes
&& axes
.y2
) {
2444 v
= axes
.y2
.valueRange
;
2445 if (v
) this.axes_
[axis
].valueRange
= v
;
2453 * Returns the number of y-axes on the chart.
2454 * @return {Number} the number of axes.
2456 Dygraph
.prototype.numAxes
= function() {
2458 for (var series
in this.seriesToAxisMap_
) {
2459 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2460 var idx
= this.seriesToAxisMap_
[series
];
2461 if (idx
> last_axis
) last_axis
= idx
;
2463 return 1 + last_axis
;
2468 * Returns axis properties for the given series.
2469 * @param { String } setName The name of the series for which to get axis
2470 * properties, e.g. 'Y1'.
2471 * @return { Object } The axis properties.
2473 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2474 // TODO(danvk): handle errors.
2475 return this.axes_
[this.seriesToAxisMap_
[series
]];
2480 * Determine the value range and tick marks for each axis.
2481 * @param {Object} extremes A mapping from seriesName -> [low, high]
2482 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2484 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2485 // Build a map from axis number -> [list of series names]
2486 var seriesForAxis
= [], series
;
2487 for (series
in this.seriesToAxisMap_
) {
2488 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2489 var idx
= this.seriesToAxisMap_
[series
];
2490 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2491 seriesForAxis
[idx
].push(series
);
2494 // Compute extreme values, a span and tick marks for each axis.
2495 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2496 var axis
= this.axes_
[i
];
2498 if (!seriesForAxis
[i
]) {
2499 // If no series are defined or visible then use a reasonable default
2500 axis
.extremeRange
= [0, 1];
2502 // Calculate the extremes of extremes.
2503 series
= seriesForAxis
[i
];
2504 var minY
= Infinity
; // extremes[series[0]][0];
2505 var maxY
= -Infinity
; // extremes[series[0]][1];
2506 var extremeMinY
, extremeMaxY
;
2508 for (var j
= 0; j
< series
.length
; j
++) {
2509 // this skips invisible series
2510 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2512 // Only use valid extremes to stop null data series' from corrupting the scale.
2513 extremeMinY
= extremes
[series
[j
]][0];
2514 if (extremeMinY
!== null) {
2515 minY
= Math
.min(extremeMinY
, minY
);
2517 extremeMaxY
= extremes
[series
[j
]][1];
2518 if (extremeMaxY
!== null) {
2519 maxY
= Math
.max(extremeMaxY
, maxY
);
2522 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2524 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2525 if (minY
== Infinity
) minY
= 0;
2526 if (maxY
== -Infinity
) maxY
= 1;
2528 // Add some padding and round up to an integer to be human-friendly.
2529 var span
= maxY
- minY
;
2530 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2531 if (span
=== 0) { span
= maxY
; }
2533 var maxAxisY
, minAxisY
;
2534 if (axis
.logscale
) {
2535 maxAxisY
= maxY
+ 0.1 * span
;
2538 maxAxisY
= maxY
+ 0.1 * span
;
2539 minAxisY
= minY
- 0.1 * span
;
2541 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2542 if (!this.attr_("avoidMinZero")) {
2543 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2544 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2547 if (this.attr_("includeZero")) {
2548 if (maxY
< 0) maxAxisY
= 0;
2549 if (minY
> 0) minAxisY
= 0;
2552 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2554 if (axis
.valueWindow
) {
2555 // This is only set if the user has zoomed on the y-axis. It is never set
2556 // by a user. It takes precedence over axis.valueRange because, if you set
2557 // valueRange, you'd still expect to be able to pan.
2558 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2559 } else if (axis
.valueRange
) {
2560 // This is a user-set value range for this axis.
2561 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
2563 axis
.computedValueRange
= axis
.extremeRange
;
2566 // Add ticks. By default, all axes inherit the tick positions of the
2567 // primary axis. However, if an axis is specifically marked as having
2568 // independent ticks, then that is permissible as well.
2569 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2570 var ticker
= opts('ticker');
2571 if (i
=== 0 || axis
.independentTicks
) {
2572 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2573 axis
.computedValueRange
[1],
2574 this.height_
, // TODO(danvk): should be area.height
2578 var p_axis
= this.axes_
[0];
2579 var p_ticks
= p_axis
.ticks
;
2580 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2581 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2582 var tick_values
= [];
2583 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2584 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2585 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2586 tick_values
.push(y_val
);
2589 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2590 axis
.computedValueRange
[1],
2591 this.height_
, // TODO(danvk): should be area.height
2600 * Extracts one series from the raw data (a 2D array) into an array of (date,
2603 * This is where undesirable points (i.e. negative values on log scales and
2604 * missing values through which we wish to connect lines) are dropped.
2608 Dygraph
.prototype.extractSeries_
= function(rawData
, i
, logScale
) {
2610 for (var j
= 0; j
< rawData
.length
; j
++) {
2611 var x
= rawData
[j
][0];
2612 var point
= rawData
[j
][i
];
2614 // On the log scale, points less than zero do not exist.
2615 // This will create a gap in the chart.
2620 series
.push([x
, point
]);
2627 * Calculates the rolling average of a data set.
2628 * If originalData is [label, val], rolls the average of those.
2629 * If originalData is [label, [, it's interpreted as [value, stddev]
2630 * and the roll is returned in the same form, with appropriately reduced
2631 * stddev for each value.
2632 * Note that this is where fractional input (i.e. '5/10') is converted into
2634 * @param {Array} originalData The data in the appropriate format (see above)
2635 * @param {Number} rollPeriod The number of points over which to average the
2638 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2639 if (originalData
.length
< 2)
2640 return originalData
;
2641 rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2642 var rollingData
= [];
2643 var sigma
= this.attr_("sigma");
2645 var low
, high
, i
, j
, y
, sum
, num_ok
, stddev
;
2646 if (this.fractions_
) {
2648 var den
= 0; // numerator/denominator
2650 for (i
= 0; i
< originalData
.length
; i
++) {
2651 num
+= originalData
[i
][1][0];
2652 den
+= originalData
[i
][1][1];
2653 if (i
- rollPeriod
>= 0) {
2654 num
-= originalData
[i
- rollPeriod
][1][0];
2655 den
-= originalData
[i
- rollPeriod
][1][1];
2658 var date
= originalData
[i
][0];
2659 var value
= den
? num
/ den
: 0.0;
2660 if (this.attr_("errorBars")) {
2661 if (this.attr_("wilsonInterval")) {
2662 // For more details on this confidence interval, see:
2663 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2665 var p
= value
< 0 ? 0 : value
, n
= den
;
2666 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2667 var denom
= 1 + sigma
* sigma
/ den
;
2668 low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2669 high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2670 rollingData
[i
] = [date
,
2671 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2673 rollingData
[i
] = [date
, [0, 0, 0]];
2676 stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2677 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2680 rollingData
[i
] = [date
, mult
* value
];
2683 } else if (this.attr_("customBars")) {
2688 for (i
= 0; i
< originalData
.length
; i
++) {
2689 var data
= originalData
[i
][1];
2691 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2693 if (y
!== null && !isNaN(y
)) {
2699 if (i
- rollPeriod
>= 0) {
2700 var prev
= originalData
[i
- rollPeriod
];
2701 if (prev
[1][1] !== null && !isNaN(prev
[1][1])) {
2709 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2710 1.0 * (mid
- low
) / count
,
2711 1.0 * (high
- mid
) / count
]];
2713 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2717 // Calculate the rolling average for the first rollPeriod - 1 points where
2718 // there is not enough data to roll over the full number of points
2719 if (!this.attr_("errorBars")){
2720 if (rollPeriod
== 1) {
2721 return originalData
;
2724 for (i
= 0; i
< originalData
.length
; i
++) {
2727 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2728 y
= originalData
[j
][1];
2729 if (y
=== null || isNaN(y
)) continue;
2731 sum
+= originalData
[j
][1];
2734 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2736 rollingData
[i
] = [originalData
[i
][0], null];
2741 for (i
= 0; i
< originalData
.length
; i
++) {
2745 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2746 y
= originalData
[j
][1][0];
2747 if (y
=== null || isNaN(y
)) continue;
2749 sum
+= originalData
[j
][1][0];
2750 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2753 stddev
= Math
.sqrt(variance
) / num_ok
;
2754 rollingData
[i
] = [originalData
[i
][0],
2755 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2757 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2767 * Detects the type of the str (date or numeric) and sets the various
2768 * formatting attributes in this.attrs_ based on this type.
2769 * @param {String} str An x value.
2772 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2774 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2775 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
2776 str
.indexOf('/') >= 0 ||
2777 isNaN(parseFloat(str
))) {
2779 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2780 // TODO(danvk): remove support for this format.
2785 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2786 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
2787 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2788 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2790 /** @private (shut up, jsdoc!) */
2791 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2792 // TODO(danvk): use Dygraph.numberValueFormatter here?
2793 /** @private (shut up, jsdoc!) */
2794 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2795 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
2796 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2801 * Parses the value as a floating point number. This is like the parseFloat()
2802 * built-in, but with a few differences:
2803 * - the empty string is parsed as null, rather than NaN.
2804 * - if the string cannot be parsed at all, an error is logged.
2805 * If the string can't be parsed, this method returns null.
2806 * @param {String} x The string to be parsed
2807 * @param {Number} opt_line_no The line number from which the string comes.
2808 * @param {String} opt_line The text of the line from which the string comes.
2812 // Parse the x as a float or return null if it's not a number.
2813 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
2814 var val
= parseFloat(x
);
2815 if (!isNaN(val
)) return val
;
2817 // Try to figure out what happeend.
2818 // If the value is the empty string, parse it as null.
2819 if (/^ *$/.test(x
)) return null;
2821 // If it was actually "NaN", return it as NaN.
2822 if (/^ *nan *$/i.test(x
)) return NaN
;
2824 // Looks like a parsing error.
2825 var msg
= "Unable to parse '" + x
+ "' as a number";
2826 if (opt_line
!== null && opt_line_no
!== null) {
2827 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
2836 * Parses a string in a special csv format. We expect a csv file where each
2837 * line is a date point, and the first field in each line is the date string.
2838 * We also expect that all remaining fields represent series.
2839 * if the errorBars attribute is set, then interpret the fields as:
2840 * date, series1, stddev1, series2, stddev2, ...
2841 * @param {[Object]} data See above.
2843 * @return [Object] An array with one entry for each row. These entries
2844 * are an array of cells in that row. The first entry is the parsed x-value for
2845 * the row. The second, third, etc. are the y-values. These can take on one of
2846 * three forms, depending on the CSV and constructor parameters:
2848 * 2. [ value, stddev ]
2849 * 3. [ low value, center value, high value ]
2851 Dygraph
.prototype.parseCSV_
= function(data
) {
2853 var lines
= data
.split("\n");
2856 // Use the default delimiter or fall back to a tab if that makes sense.
2857 var delim
= this.attr_('delimiter');
2858 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2863 if (!('labels' in this.user_attrs_
)) {
2864 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
2866 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
2871 var defaultParserSet
= false; // attempt to auto-detect x value type
2872 var expectedCols
= this.attr_("labels").length
;
2873 var outOfOrder
= false;
2874 for (var i
= start
; i
< lines
.length
; i
++) {
2875 var line
= lines
[i
];
2877 if (line
.length
=== 0) continue; // skip blank lines
2878 if (line
[0] == '#') continue; // skip comment lines
2879 var inFields
= line
.split(delim
);
2880 if (inFields
.length
< 2) continue;
2883 if (!defaultParserSet
) {
2884 this.detectTypeFromString_(inFields
[0]);
2885 xParser
= this.attr_("xValueParser");
2886 defaultParserSet
= true;
2888 fields
[0] = xParser(inFields
[0], this);
2890 // If fractions are expected, parse the numbers as "A/B
"
2891 if (this.fractions_) {
2892 for (j = 1; j < inFields.length; j++) {
2893 // TODO(danvk): figure out an appropriate way to flag parse errors.
2894 vals = inFields[j].split("/");
2895 if (vals.length != 2) {
2896 this.error('Expected fractional "num
/den
" values in CSV data ' +
2897 "but found a value
'" + inFields[j] + "' on line
" +
2898 (1 + i) + " ('" + line + "') which is not of
this form
.");
2901 fields[j] = [this.parseFloat_(vals[0], i, line),
2902 this.parseFloat_(vals[1], i, line)];
2905 } else if (this.attr_("errorBars
")) {
2906 // If there are error bars, values are (value, stddev) pairs
2907 if (inFields.length % 2 != 1) {
2908 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2909 'but line ' + (1 + i) + ' has an odd number of values (' +
2910 (inFields.length - 1) + "): '" + line + "'");
2912 for (j = 1; j < inFields.length; j += 2) {
2913 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2914 this.parseFloat_(inFields[j + 1], i, line)];
2916 } else if (this.attr_("customBars
")) {
2917 // Bars are a low;center;high tuple
2918 for (j = 1; j < inFields.length; j++) {
2919 var val = inFields[j];
2920 if (/^ *$/.test(val)) {
2921 fields[j] = [null, null, null];
2923 vals = val.split(";");
2924 if (vals.length == 3) {
2925 fields[j] = [ this.parseFloat_(vals[0], i, line),
2926 this.parseFloat_(vals[1], i, line),
2927 this.parseFloat_(vals[2], i, line) ];
2929 this.warn('When using customBars, values must be either blank ' +
2930 'or "low
;center
;high
" tuples (got "' + val +
2931 '" on line ' + (1+i));
2936 // Values are just numbers
2937 for (j = 1; j < inFields.length; j++) {
2938 fields[j] = this.parseFloat_(inFields[j], i, line);
2941 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2945 if (fields.length != expectedCols) {
2946 this.error("Number of columns
in line
" + i + " (" + fields.length +
2947 ") does not agree
with number of
labels (" + expectedCols +
2951 // If the user specified the 'labels' option and none of the cells of the
2952 // first row parsed correctly, then they probably double-specified the
2953 // labels. We go with the values set in the option, discard this row and
2954 // log a warning to the JS console.
2955 if (i === 0 && this.attr_('labels')) {
2956 var all_null = true;
2957 for (j = 0; all_null && j < fields.length; j++) {
2958 if (fields[j]) all_null = false;
2961 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
2962 "CSV
data ('" + line + "') appears to also contain labels
. " +
2963 "Will drop the CSV labels and
use the option labels
.");
2971 this.warn("CSV is out of order
; order it correctly to speed loading
.");
2972 ret.sort(function(a,b) { return a[0] - b[0]; });
2980 * The user has provided their data as a pre-packaged JS array. If the x values
2981 * are numeric, this is the same as dygraphs' internal format. If the x values
2982 * are dates, we need to convert them from Date objects to ms since epoch.
2983 * @param {[Object]} data
2984 * @return {[Object]} data with numeric x values.
2986 Dygraph.prototype.parseArray_ = function(data) {
2987 // Peek at the first x value to see if it's numeric.
2988 if (data.length === 0) {
2989 this.error("Can
't plot empty data set");
2992 if (data[0].length === 0) {
2993 this.error("Data set cannot contain an empty row");
2998 if (this.attr_("labels") === null) {
2999 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3000 "in the options parameter");
3001 this.attrs_.labels = [ "X" ];
3002 for (i = 1; i < data[0].length; i++) {
3003 this.attrs_.labels.push("Y" + i);
3007 if (Dygraph.isDateLike(data[0][0])) {
3008 // Some intelligent defaults for a date x-axis.
3009 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3010 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3011 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3013 // Assume they're all dates
.
3014 var parsedData
= Dygraph
.clone(data
);
3015 for (i
= 0; i
< data
.length
; i
++) {
3016 if (parsedData
[i
].length
=== 0) {
3017 this.error("Row " + (1 + i
) + " of data is empty");
3020 if (parsedData
[i
][0] === null ||
3021 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3022 isNaN(parsedData
[i
][0].getTime())) {
3023 this.error("x value in row " + (1 + i
) + " is not a Date");
3026 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3030 // Some intelligent defaults for a numeric x-axis.
3031 /** @private (shut up, jsdoc!) */
3032 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3033 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3034 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3040 * Parses a DataTable object from gviz.
3041 * The data is expected to have a first column that is either a date or a
3042 * number. All subsequent columns must be numbers. If there is a clear mismatch
3043 * between this.xValueParser_ and the type of the first column, it will be
3044 * fixed. Fills out rawData_.
3045 * @param {[Object]} data See above.
3048 Dygraph
.prototype.parseDataTable_
= function(data
) {
3049 var shortTextForAnnotationNum
= function(num
) {
3050 // converts [0-9]+ [A-Z][a-z]*
3051 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3052 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3053 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3054 num
= Math
.floor(num
/ 26);
3056 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3057 num
= Math
.floor((num
- 1) / 26);
3062 var cols
= data
.getNumberOfColumns();
3063 var rows
= data
.getNumberOfRows();
3065 var indepType
= data
.getColumnType(0);
3066 if (indepType
== 'date' || indepType
== 'datetime') {
3067 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3068 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3069 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3070 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3071 } else if (indepType
== 'number') {
3072 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3073 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3074 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3075 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3077 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3078 "column 1 of DataTable input (Got '" + indepType
+ "')");
3082 // Array of the column indices which contain data (and not annotations).
3084 var annotationCols
= {}; // data index -> [annotation cols]
3085 var hasAnnotations
= false;
3087 for (i
= 1; i
< cols
; i
++) {
3088 var type
= data
.getColumnType(i
);
3089 if (type
== 'number') {
3091 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3092 // This is OK -- it's an annotation column.
3093 var dataIdx
= colIdx
[colIdx
.length
- 1];
3094 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3095 annotationCols
[dataIdx
] = [i
];
3097 annotationCols
[dataIdx
].push(i
);
3099 hasAnnotations
= true;
3101 this.error("Only 'number' is supported as a dependent type with Gviz." +
3102 " 'string' is only supported if displayAnnotations is true");
3106 // Read column labels
3107 // TODO(danvk): add support back for errorBars
3108 var labels
= [data
.getColumnLabel(0)];
3109 for (i
= 0; i
< colIdx
.length
; i
++) {
3110 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3111 if (this.attr_("errorBars")) i
+= 1;
3113 this.attrs_
.labels
= labels
;
3114 cols
= labels
.length
;
3117 var outOfOrder
= false;
3118 var annotations
= [];
3119 for (i
= 0; i
< rows
; i
++) {
3121 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3122 data
.getValue(i
, 0) === null) {
3123 this.warn("Ignoring row " + i
+
3124 " of DataTable because of undefined or null first column.");
3128 if (indepType
== 'date' || indepType
== 'datetime') {
3129 row
.push(data
.getValue(i
, 0).getTime());
3131 row
.push(data
.getValue(i
, 0));
3133 if (!this.attr_("errorBars")) {
3134 for (j
= 0; j
< colIdx
.length
; j
++) {
3135 var col
= colIdx
[j
];
3136 row
.push(data
.getValue(i
, col
));
3137 if (hasAnnotations
&&
3138 annotationCols
.hasOwnProperty(col
) &&
3139 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3141 ann
.series
= data
.getColumnLabel(col
);
3143 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3145 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3146 if (k
) ann
.text
+= "\n";
3147 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3149 annotations
.push(ann
);
3153 // Strip out infinities, which give dygraphs problems later on.
3154 for (j
= 0; j
< row
.length
; j
++) {
3155 if (!isFinite(row
[j
])) row
[j
] = null;
3158 for (j
= 0; j
< cols
- 1; j
++) {
3159 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3162 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3169 this.warn("DataTable is out of order; order it correctly to speed loading.");
3170 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3172 this.rawData_
= ret
;
3174 if (annotations
.length
> 0) {
3175 this.setAnnotations(annotations
, true);
3180 * Get the CSV data. If it's in a function, call that function. If it's in a
3181 * file, do an XMLHttpRequest to get it.
3184 Dygraph
.prototype.start_
= function() {
3185 var data
= this.file_
;
3187 // Functions can return references of all other types.
3188 if (typeof data
== 'function') {
3192 if (Dygraph
.isArrayLike(data
)) {
3193 this.rawData_
= this.parseArray_(data
);
3195 } else if (typeof data
== 'object' &&
3196 typeof data
.getColumnRange
== 'function') {
3197 // must be a DataTable from gviz.
3198 this.parseDataTable_(data
);
3200 } else if (typeof data
== 'string') {
3201 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3202 if (data
.indexOf('\n') >= 0) {
3203 this.loadedEvent_(data
);
3205 var req
= new XMLHttpRequest();
3207 req
.onreadystatechange
= function () {
3208 if (req
.readyState
== 4) {
3209 if (req
.status
=== 200 || // Normal http
3210 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3211 caller
.loadedEvent_(req
.responseText
);
3216 req
.open("GET", data
, true);
3220 this.error("Unknown data format: " + (typeof data
));
3225 * Changes various properties of the graph. These can include:
3227 * <li>file: changes the source data for the graph</li>
3228 * <li>errorBars: changes whether the data contains stddev</li>
3231 * There's a huge variety of options that can be passed to this method. For a
3232 * full list, see http://dygraphs.com/options.html.
3234 * @param {Object} attrs The new properties and values
3235 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3236 * call to updateOptions(). If you know better, you can pass true to explicitly
3237 * block the redraw. This can be useful for chaining updateOptions() calls,
3238 * avoiding the occasional infinite loop and preventing redraws when it's not
3239 * necessary (e.g. when updating a callback).
3241 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3242 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3244 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3245 var file
= input_attrs
.file
;
3246 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3248 // TODO(danvk): this is a mess. Move these options into attr_.
3249 if ('rollPeriod' in attrs
) {
3250 this.rollPeriod_
= attrs
.rollPeriod
;
3252 if ('dateWindow' in attrs
) {
3253 this.dateWindow_
= attrs
.dateWindow
;
3254 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3255 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3258 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3259 this.zoomed_y_
= (attrs
.valueRange
!== null);
3262 // TODO(danvk): validate per-series options.
3267 // highlightCircleSize
3269 // Check if this set options will require new points.
3270 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3272 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3276 if (!block_redraw
) this.start_();
3278 if (!block_redraw
) {
3279 if (requiresNewPoints
) {
3282 this.renderGraph_(false);
3289 * Returns a copy of the options with deprecated names converted into current
3290 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3291 * interested in that, they should save a copy before calling this.
3294 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3296 for (var k
in attrs
) {
3297 if (k
== 'file') continue;
3298 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3301 var set
= function(axis
, opt
, value
) {
3302 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3303 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3304 my_attrs
.axes
[axis
][opt
] = value
;
3306 var map
= function(opt
, axis
, new_opt
) {
3307 if (typeof(attrs
[opt
]) != 'undefined') {
3308 set(axis
, new_opt
, attrs
[opt
]);
3309 delete my_attrs
[opt
];
3313 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3314 map('xValueFormatter', 'x', 'valueFormatter');
3315 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3316 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3317 map('xTicker', 'x', 'ticker');
3318 map('yValueFormatter', 'y', 'valueFormatter');
3319 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3320 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3321 map('yTicker', 'y', 'ticker');
3326 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3327 * containing div (which has presumably changed size since the dygraph was
3328 * instantiated. If the width/height are specified, the div will be resized.
3330 * This is far more efficient than destroying and re-instantiating a
3331 * Dygraph, since it doesn't have to reparse the underlying data.
3333 * @param {Number} [width] Width (in pixels)
3334 * @param {Number} [height] Height (in pixels)
3336 Dygraph
.prototype.resize
= function(width
, height
) {
3337 if (this.resize_lock
) {
3340 this.resize_lock
= true;
3342 if ((width
=== null) != (height
=== null)) {
3343 this.warn("Dygraph.resize() should be called with zero parameters or " +
3344 "two non-NULL parameters. Pretending it was zero.");
3345 width
= height
= null;
3348 var old_width
= this.width_
;
3349 var old_height
= this.height_
;
3352 this.maindiv_
.style
.width
= width
+ "px";
3353 this.maindiv_
.style
.height
= height
+ "px";
3354 this.width_
= width
;
3355 this.height_
= height
;
3357 this.width_
= this.maindiv_
.clientWidth
;
3358 this.height_
= this.maindiv_
.clientHeight
;
3361 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3362 // TODO(danvk): there should be a clear() method.
3363 this.maindiv_
.innerHTML
= "";
3364 this.roller_
= null;
3365 this.attrs_
.labelsDiv
= null;
3366 this.createInterface_();
3367 if (this.annotations_
.length
) {
3368 // createInterface_ reset the layout, so we need to do this.
3369 this.layout_
.setAnnotations(this.annotations_
);
3374 this.resize_lock
= false;
3378 * Adjusts the number of points in the rolling average. Updates the graph to
3379 * reflect the new averaging period.
3380 * @param {Number} length Number of points over which to average the data.
3382 Dygraph
.prototype.adjustRoll
= function(length
) {
3383 this.rollPeriod_
= length
;
3388 * Returns a boolean array of visibility statuses.
3390 Dygraph
.prototype.visibility
= function() {
3391 // Do lazy-initialization, so that this happens after we know the number of
3393 if (!this.attr_("visibility")) {
3394 this.attrs_
.visibility
= [];
3396 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3397 while (this.attr_("visibility").length
< this.numColumns() - 1) {
3398 this.attrs_
.visibility
.push(true);
3400 return this.attr_("visibility");
3404 * Changes the visiblity of a series.
3406 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3407 var x
= this.visibility();
3408 if (num
< 0 || num
>= x
.length
) {
3409 this.warn("invalid series number in setVisibility: " + num
);
3417 * How large of an area will the dygraph render itself in?
3418 * This is used for testing.
3419 * @return A {width: w, height: h} object.
3422 Dygraph
.prototype.size
= function() {
3423 return { width
: this.width_
, height
: this.height_
};
3427 * Update the list of annotations and redraw the chart.
3428 * See dygraphs.com/annotations.html for more info on how to use annotations.
3429 * @param ann {Array} An array of annotation objects.
3430 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3432 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3433 // Only add the annotation CSS rule once we know it will be used.
3434 Dygraph
.addAnnotationRule();
3435 this.annotations_
= ann
;
3436 this.layout_
.setAnnotations(this.annotations_
);
3437 if (!suppressDraw
) {
3443 * Return the list of annotations.
3445 Dygraph
.prototype.annotations
= function() {
3446 return this.annotations_
;
3450 * Get the list of label names for this graph. The first column is the
3451 * x-axis, so the data series names start at index 1.
3453 Dygraph
.prototype.getLabels
= function() {
3454 return this.attr_("labels").slice();
3458 * Get the index of a series (column) given its name. The first column is the
3459 * x-axis, so the data series start with index 1.
3461 Dygraph
.prototype.indexFromSetName
= function(name
) {
3462 return this.setIndexByName_
[name
];
3466 * Get the internal dataset index given its name. These are numbered starting from 0,
3467 * and only count visible sets.
3470 Dygraph
.prototype.datasetIndexFromSetName_
= function(name
) {
3471 return this.datasetIndex_
[this.indexFromSetName(name
)];
3476 * Adds a default style for the annotation CSS classes to the document. This is
3477 * only executed when annotations are actually used. It is designed to only be
3478 * called once -- all calls after the first will return immediately.
3480 Dygraph
.addAnnotationRule
= function() {
3481 if (Dygraph
.addedAnnotationCSS
) return;
3483 var rule
= "border: 1px solid black; " +
3484 "background-color: white; " +
3485 "text-align: center;";
3487 var styleSheetElement
= document
.createElement("style");
3488 styleSheetElement
.type
= "text/css";
3489 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3491 // Find the first style sheet that we can access.
3492 // We may not add a rule to a style sheet from another domain for security
3493 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3494 // adds its own style sheets from google.com.
3495 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3496 if (document
.styleSheets
[i
].disabled
) continue;
3497 var mysheet
= document
.styleSheets
[i
];
3499 if (mysheet
.insertRule
) { // Firefox
3500 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3501 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3502 } else if (mysheet
.addRule
) { // IE
3503 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3505 Dygraph
.addedAnnotationCSS
= true;
3508 // Was likely a security exception.
3512 this.warn("Unable to add default annotation CSS rule; display may be off.");
3515 // Older pages may still use this name.
3516 var DateGraph
= Dygraph
;