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 registerer
= (function(pluginDict
) {
427 addEventListener
: function(eventName
, callback
) {
428 // TODO(danvk): validate eventName.
429 pluginDict
.events
[eventName
] = callback
;
433 pluginInstance
.activate(this, registerer
);
434 // TODO(danvk): prevent activate() from holding a reference to registerer.
436 this.plugins_
.push(pluginDict
);
439 // At this point, plugins can no longer register event handlers.
440 // Construct a map from event -> ordered list of [callback, plugin].
441 this.eventListeners_
= {};
442 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
443 var plugin_dict
= this.plugins_
[i
];
444 for (var eventName
in plugin_dict
.events
) {
445 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
446 var callback
= plugin_dict
.events
[eventName
];
448 var pair
= [plugin_dict
.plugin
, callback
];
449 if (!(eventName
in this.eventListeners_
)) {
450 this.eventListeners_
[eventName
] = [pair
];
452 this.eventListeners_
[eventName
].push(pair
);
461 * Triggers a cascade of events to the various plugins which are interested in them.
462 * Returns true if the "default behavior" should be performed, i.e. if none of
463 * the event listeners called event.preventDefault().
466 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
467 if (!name
in this.eventListeners_
) return true;
469 // QUESTION: can we use objects & prototypes to speed this up?
473 defaultPrevented
: false,
474 preventDefault
: function() {
475 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
476 e
.defaultPrevented
= true;
478 propagationStopped
: false,
479 stopPropagation
: function() {
480 e
.propagationStopped
= true;
483 Dygraph
.update(e
, extra_props
);
485 var callback_plugin_pairs
= this.eventListeners_
[name
];
486 if (callback_plugin_pairs
) {
487 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
488 var plugin
= callback_plugin_pairs
[i
][0];
489 var callback
= callback_plugin_pairs
[i
][1];
490 callback
.call(plugin
, e
);
491 if (e
.propagationStopped
) break;
494 return e
.defaultPrevented
;
498 * Returns the zoomed status of the chart for one or both axes.
500 * Axis is an optional parameter. Can be set to 'x' or 'y'.
502 * The zoomed status for an axis is set whenever a user zooms using the mouse
503 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
504 * option is also specified).
506 Dygraph
.prototype.isZoomed
= function(axis
) {
507 if (axis
== null) return this.zoomed_x_
|| this.zoomed_y_
;
508 if (axis
=== 'x') return this.zoomed_x_
;
509 if (axis
=== 'y') return this.zoomed_y_
;
510 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
514 * Returns information about the Dygraph object, including its containing ID.
516 Dygraph
.prototype.toString
= function() {
517 var maindiv
= this.maindiv_
;
518 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
519 return "[Dygraph " + id
+ "]";
524 * Returns the value of an option. This may be set by the user (either in the
525 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
527 * @param { String } name The name of the option, e.g. 'rollPeriod'.
528 * @param { String } [seriesName] The name of the series to which the option
529 * will be applied. If no per-series value of this option is available, then
530 * the global value is returned. This is optional.
531 * @return { ... } The value of the option.
533 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
534 // <REMOVE_FOR_COMBINED>
535 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
536 this.error('Must include options reference JS for testing');
537 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
538 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
539 'in the Dygraphs.OPTIONS_REFERENCE listing.');
540 // Only log this error once.
541 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
543 // </REMOVE_FOR_COMBINED
>
546 sources
.push(this.attrs_
);
547 if (this.user_attrs_
) {
548 sources
.push(this.user_attrs_
);
550 if (this.user_attrs_
.hasOwnProperty(seriesName
)) {
551 sources
.push(this.user_attrs_
[seriesName
]);
553 if (seriesName
=== this.highlightSet_
&&
554 this.user_attrs_
.hasOwnProperty('highlightSeriesOpts')) {
555 sources
.push(this.user_attrs_
['highlightSeriesOpts']);
561 for (var i
= sources
.length
- 1; i
>= 0; --i
) {
562 var source
= sources
[i
];
563 if (source
.hasOwnProperty(name
)) {
572 * Returns the current value for an option, as set in the constructor or via
573 * updateOptions. You may pass in an (optional) series name to get per-series
574 * values for the option.
576 * All values returned by this method should be considered immutable. If you
577 * modify them, there is no guarantee that the changes will be honored or that
578 * dygraphs will remain in a consistent state. If you want to modify an option,
579 * use updateOptions() instead.
581 * @param { String } name The name of the option (e.g. 'strokeWidth')
582 * @param { String } [opt_seriesName] Series name to get per-series values.
583 * @return { ... } The value of the option.
585 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
586 return this.attr_(name
, opt_seriesName
);
591 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
592 * @return { ... } A function mapping string -> option value
594 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
596 return function(opt
) {
597 var axis_opts
= self
.user_attrs_
.axes
;
598 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
599 return axis_opts
[axis
][opt
];
601 // user-specified attributes always trump defaults, even if they're less
603 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
604 return self
.user_attrs_
[opt
];
607 axis_opts
= self
.attrs_
.axes
;
608 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
][opt
]) {
609 return axis_opts
[axis
][opt
];
611 // check old-style axis options
612 // TODO(danvk): add a deprecation warning if either of these match.
613 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
614 return self
.axes_
[0][opt
];
615 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
616 return self
.axes_
[1][opt
];
618 return self
.attr_(opt
);
623 * Returns the current rolling period, as set by the user or an option.
624 * @return {Number} The number of points in the rolling window
626 Dygraph
.prototype.rollPeriod
= function() {
627 return this.rollPeriod_
;
631 * Returns the currently-visible x-range. This can be affected by zooming,
632 * panning or a call to updateOptions.
633 * Returns a two-element array: [left, right].
634 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
636 Dygraph
.prototype.xAxisRange
= function() {
637 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
641 * Returns the lower- and upper-bound x-axis values of the
644 Dygraph
.prototype.xAxisExtremes
= function() {
645 var left
= this.rawData_
[0][0];
646 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
647 return [left
, right
];
651 * Returns the currently-visible y-range for an axis. This can be affected by
652 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
653 * called with no arguments, returns the range of the first axis.
654 * Returns a two-element array: [bottom, top].
656 Dygraph
.prototype.yAxisRange
= function(idx
) {
657 if (typeof(idx
) == "undefined") idx
= 0;
658 if (idx
< 0 || idx
>= this.axes_
.length
) {
661 var axis
= this.axes_
[idx
];
662 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
666 * Returns the currently-visible y-ranges for each axis. This can be affected by
667 * zooming, panning, calls to updateOptions, etc.
668 * Returns an array of [bottom, top] pairs, one for each y-axis.
670 Dygraph
.prototype.yAxisRanges
= function() {
672 for (var i
= 0; i
< this.axes_
.length
; i
++) {
673 ret
.push(this.yAxisRange(i
));
678 // TODO(danvk): use these functions throughout dygraphs.
680 * Convert from data coordinates to canvas/div X/Y coordinates.
681 * If specified, do this conversion for the coordinate system of a particular
682 * axis. Uses the first axis by default.
683 * Returns a two-element array: [X, Y]
685 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
686 * instead of toDomCoords(null, y, axis).
688 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
689 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
693 * Convert from data x coordinates to canvas/div X coordinate.
694 * If specified, do this conversion for the coordinate system of a particular
696 * Returns a single value or null if x is null.
698 Dygraph
.prototype.toDomXCoord
= function(x
) {
703 var area
= this.plotter_
.area
;
704 var xRange
= this.xAxisRange();
705 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
709 * Convert from data x coordinates to canvas/div Y coordinate and optional
710 * axis. Uses the first axis by default.
712 * returns a single value or null if y is null.
714 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
715 var pct
= this.toPercentYCoord(y
, axis
);
720 var area
= this.plotter_
.area
;
721 return area
.y
+ pct
* area
.h
;
725 * Convert from canvas/div coords to data coordinates.
726 * If specified, do this conversion for the coordinate system of a particular
727 * axis. Uses the first axis by default.
728 * Returns a two-element array: [X, Y].
730 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
731 * instead of toDataCoords(null, y, axis).
733 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
734 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
738 * Convert from canvas/div x coordinate to data coordinate.
740 * If x is null, this returns null.
742 Dygraph
.prototype.toDataXCoord
= function(x
) {
747 var area
= this.plotter_
.area
;
748 var xRange
= this.xAxisRange();
749 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
753 * Convert from canvas/div y coord to value.
755 * If y is null, this returns null.
756 * if axis is null, this uses the first axis.
758 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
763 var area
= this.plotter_
.area
;
764 var yRange
= this.yAxisRange(axis
);
766 if (typeof(axis
) == "undefined") axis
= 0;
767 if (!this.axes_
[axis
].logscale
) {
768 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
770 // Computing the inverse of toDomCoord.
771 var pct
= (y
- area
.y
) / area
.h
;
773 // Computing the inverse of toPercentYCoord. The function was arrived at with
774 // the following steps:
776 // Original calcuation:
777 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
779 // Move denominator to both sides:
780 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
782 // subtract logr1, and take the negative value.
783 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
785 // Swap both sides of the equation, and we can compute the log of the
786 // return value. Which means we just need to use that as the exponent in
788 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
790 var logr1
= Dygraph
.log10(yRange
[1]);
791 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
792 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
798 * Converts a y for an axis to a percentage from the top to the
799 * bottom of the drawing area.
801 * If the coordinate represents a value visible on the canvas, then
802 * the value will be between 0 and 1, where 0 is the top of the canvas.
803 * However, this method will return values outside the range, as
804 * values can fall outside the canvas.
806 * If y is null, this returns null.
807 * if axis is null, this uses the first axis.
809 * @param { Number } y The data y-coordinate.
810 * @param { Number } [axis] The axis number on which the data coordinate lives.
811 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
813 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
817 if (typeof(axis
) == "undefined") axis
= 0;
819 var yRange
= this.yAxisRange(axis
);
822 if (!this.axes_
[axis
].logscale
) {
823 // yRange[1] - y is unit distance from the bottom.
824 // yRange[1] - yRange[0] is the scale of the range.
825 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
826 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
828 var logr1
= Dygraph
.log10(yRange
[1]);
829 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
835 * Converts an x value to a percentage from the left to the right of
838 * If the coordinate represents a value visible on the canvas, then
839 * the value will be between 0 and 1, where 0 is the left of the canvas.
840 * However, this method will return values outside the range, as
841 * values can fall outside the canvas.
843 * If x is null, this returns null.
844 * @param { Number } x The data x-coordinate.
845 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
847 Dygraph
.prototype.toPercentXCoord
= function(x
) {
852 var xRange
= this.xAxisRange();
853 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
857 * Returns the number of columns (including the independent variable).
858 * @return { Integer } The number of columns.
860 Dygraph
.prototype.numColumns
= function() {
861 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
865 * Returns the number of rows (excluding any header/label row).
866 * @return { Integer } The number of rows, less any header.
868 Dygraph
.prototype.numRows
= function() {
869 return this.rawData_
.length
;
873 * Returns the full range of the x-axis, as determined by the most extreme
874 * values in the data set. Not affected by zooming, visibility, etc.
875 * TODO(danvk): merge w/ xAxisExtremes
876 * @return { Array<Number> } A [low, high] pair
879 Dygraph
.prototype.fullXRange_
= function() {
880 if (this.numRows() > 0) {
881 return [this.rawData_
[0][0], this.rawData_
[this.numRows() - 1][0]];
888 * Returns the value in the given row and column. If the row and column exceed
889 * the bounds on the data, returns null. Also returns null if the value is
891 * @param { Number} row The row number of the data (0-based). Row 0 is the
892 * first row of data, not a header row.
893 * @param { Number} col The column number of the data (0-based)
894 * @return { Number } The value in the specified cell or null if the row/col
897 Dygraph
.prototype.getValue
= function(row
, col
) {
898 if (row
< 0 || row
> this.rawData_
.length
) return null;
899 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
901 return this.rawData_
[row
][col
];
905 * Generates interface elements for the Dygraph: a containing div, a div to
906 * display the current point, and a textbox to adjust the rolling average
907 * period. Also creates the Renderer/Layout elements.
910 Dygraph
.prototype.createInterface_
= function() {
911 // Create the all-enclosing graph div
912 var enclosing
= this.maindiv_
;
914 this.graphDiv
= document
.createElement("div");
915 this.graphDiv
.style
.width
= this.width_
+ "px";
916 this.graphDiv
.style
.height
= this.height_
+ "px";
917 enclosing
.appendChild(this.graphDiv
);
919 // Create the canvas for interactive parts of the chart.
920 this.canvas_
= Dygraph
.createCanvas();
921 this.canvas_
.style
.position
= "absolute";
922 this.canvas_
.width
= this.width_
;
923 this.canvas_
.height
= this.height_
;
924 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
925 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
927 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
929 // ... and for static parts of the chart.
930 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
931 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
933 if (this.attr_('showRangeSelector')) {
934 // The range selector must be created here so that its canvases and contexts get created here.
935 // For some reason, if the canvases and contexts don't get created here, things don't work in IE.
936 // The range selector also sets xAxisHeight in order to reserve space.
937 this.rangeSelector_
= new DygraphRangeSelector(this);
940 // The interactive parts of the graph are drawn on top of the chart.
941 this.graphDiv
.appendChild(this.hidden_
);
942 this.graphDiv
.appendChild(this.canvas_
);
943 this.mouseEventElement_
= this.createMouseEventElement_();
945 // Create the grapher
946 this.layout_
= new DygraphLayout(this);
948 if (this.rangeSelector_
) {
949 // This needs to happen after the graph canvases are added to the div and the layout object is created.
950 this.rangeSelector_
.addToGraph(this.graphDiv
, this.layout_
);
955 this.mouseMoveHandler
= function(e
) {
956 dygraph
.mouseMove_(e
);
958 Dygraph
.addEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler
);
960 this.mouseOutHandler
= function(e
) {
961 dygraph
.mouseOut_(e
);
963 Dygraph
.addEvent(this.mouseEventElement_
, 'mouseout', this.mouseOutHandler
);
965 this.createDragInterface_();
967 this.resizeHandler
= function(e
) {
971 // Update when the window is resized.
972 // TODO(danvk): drop frames depending on complexity of the chart.
973 Dygraph
.addEvent(window
, 'resize', this.resizeHandler
);
977 * Detach DOM elements in the dygraph and null out all data references.
978 * Calling this when you're done with a dygraph can dramatically reduce memory
979 * usage. See, e.g., the tests/perf.html example.
981 Dygraph
.prototype.destroy
= function() {
982 var removeRecursive
= function(node
) {
983 while (node
.hasChildNodes()) {
984 removeRecursive(node
.firstChild
);
985 node
.removeChild(node
.firstChild
);
989 // remove mouse event handlers
990 Dygraph
.removeEvent(this.mouseEventElement_
, 'mouseout', this.mouseOutHandler
);
991 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler
);
992 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseUpHandler_
);
993 removeRecursive(this.maindiv_
);
995 var nullOut
= function(obj
) {
997 if (typeof(obj
[n
]) === 'object') {
1002 // remove event handlers
1003 Dygraph
.removeEvent(window
,'resize',this.resizeHandler
);
1004 this.resizeHandler
= null;
1005 // These may not all be necessary, but it can't hurt...
1006 nullOut(this.layout_
);
1007 nullOut(this.plotter_
);
1012 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1013 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1014 * or the zoom rectangles) is done on this.canvas_.
1015 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1016 * @return {Object} The newly-created canvas
1019 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1020 var h
= Dygraph
.createCanvas();
1021 h
.style
.position
= "absolute";
1022 // TODO(danvk): h should be offset from canvas. canvas needs to include
1023 // some extra area to make it easier to zoom in on the far left and far
1024 // right. h needs to be precisely the plot area, so that clipping occurs.
1025 h
.style
.top
= canvas
.style
.top
;
1026 h
.style
.left
= canvas
.style
.left
;
1027 h
.width
= this.width_
;
1028 h
.height
= this.height_
;
1029 h
.style
.width
= this.width_
+ "px"; // for IE
1030 h
.style
.height
= this.height_
+ "px"; // for IE
1035 * Creates an overlay element used to handle mouse events.
1036 * @return {Object} The mouse event element.
1039 Dygraph
.prototype.createMouseEventElement_
= function() {
1040 if (this.isUsingExcanvas_
) {
1041 var elem
= document
.createElement("div");
1042 elem
.style
.position
= 'absolute';
1043 elem
.style
.backgroundColor
= 'white';
1044 elem
.style
.filter
= 'alpha(opacity=0)';
1045 elem
.style
.width
= this.width_
+ "px";
1046 elem
.style
.height
= this.height_
+ "px";
1047 this.graphDiv
.appendChild(elem
);
1050 return this.canvas_
;
1055 * Generate a set of distinct colors for the data series. This is done with a
1056 * color wheel. Saturation/Value are customizable, and the hue is
1057 * equally-spaced around the color wheel. If a custom set of colors is
1058 * specified, that is used instead.
1061 Dygraph
.prototype.setColors_
= function() {
1062 var num
= this.attr_("labels").length
- 1;
1064 var colors
= this.attr_('colors');
1067 var sat
= this.attr_('colorSaturation') || 1.0;
1068 var val
= this.attr_('colorValue') || 0.5;
1069 var half
= Math
.ceil(num
/ 2);
1070 for (i
= 1; i
<= num
; i
++) {
1071 if (!this.visibility()[i
-1]) continue;
1072 // alternate colors for high contrast.
1073 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
1074 var hue
= (1.0 * idx
/ (1 + num
));
1075 this.colors_
.push(Dygraph
.hsvToRGB(hue
, sat
, val
));
1078 for (i
= 0; i
< num
; i
++) {
1079 if (!this.visibility()[i
]) continue;
1080 var colorStr
= colors
[i
% colors
.length
];
1081 this.colors_
.push(colorStr
);
1085 this.plotter_
.setColors(this.colors_
);
1089 * Return the list of colors. This is either the list of colors passed in the
1090 * attributes or the autogenerated list of rgb(r,g,b) strings.
1091 * This does not return colors for invisible series.
1092 * @return {Array<string>} The list of colors.
1094 Dygraph
.prototype.getColors
= function() {
1095 return this.colors_
;
1099 * Returns a few attributes of a series, i.e. its color, its visibility, which
1100 * axis it's assigned to, and its column in the original data.
1101 * Returns null if the series does not exist.
1102 * Otherwise, returns an object with column, visibility, color and axis properties.
1103 * The "axis" property will be set to 1 for y1 and 2 for y2.
1104 * The "column" property can be fed back into getValue(row, column) to get
1105 * values for this series.
1107 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1109 var labels
= this.getLabels();
1110 for (var i
= 1; i
< labels
.length
; i
++) {
1111 if (labels
[i
] == series_name
) {
1116 if (idx
== -1) return null;
1121 visible
: this.visibility()[idx
- 1],
1122 color
: this.plotter_
.colors
[series_name
],
1123 axis
: 1 + this.seriesToAxisMap_
[series_name
]
1128 * Create the text box to adjust the averaging period
1131 Dygraph
.prototype.createRollInterface_
= function() {
1132 // Create a roller if one doesn't exist already.
1133 if (!this.roller_
) {
1134 this.roller_
= document
.createElement("input");
1135 this.roller_
.type
= "text";
1136 this.roller_
.style
.display
= "none";
1137 this.graphDiv
.appendChild(this.roller_
);
1140 var display
= this.attr_('showRoller') ? 'block' : 'none';
1142 var area
= this.plotter_
.area
;
1143 var textAttr
= { "position": "absolute",
1145 "top": (area
.y
+ area
.h
- 25) + "px",
1146 "left": (area
.x
+ 1) + "px",
1149 this.roller_
.size
= "2";
1150 this.roller_
.value
= this.rollPeriod_
;
1151 for (var name
in textAttr
) {
1152 if (textAttr
.hasOwnProperty(name
)) {
1153 this.roller_
.style
[name
] = textAttr
[name
];
1158 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1163 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1164 * canvas (i.e. DOM Coords).
1166 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1167 return Dygraph
.pageX(e
) - context
.px
;
1172 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1173 * canvas (i.e. DOM Coords).
1175 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1176 return Dygraph
.pageY(e
) - context
.py
;
1180 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1184 Dygraph
.prototype.createDragInterface_
= function() {
1186 // Tracks whether the mouse is down right now
1188 isPanning
: false, // is this drag part of a pan?
1189 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1190 dragStartX
: null, // pixel coordinates
1191 dragStartY
: null, // pixel coordinates
1192 dragEndX
: null, // pixel coordinates
1193 dragEndY
: null, // pixel coordinates
1194 dragDirection
: null,
1195 prevEndX
: null, // pixel coordinates
1196 prevEndY
: null, // pixel coordinates
1197 prevDragDirection
: null,
1198 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1200 // The value on the left side of the graph when a pan operation starts.
1201 initialLeftmostDate
: null,
1203 // The number of units each pixel spans. (This won't be valid for log
1205 xUnitsPerPixel
: null,
1207 // TODO(danvk): update this comment
1208 // The range in second/value units that the viewport encompasses during a
1209 // panning operation.
1212 // Top-left corner of the canvas, in DOM coords
1213 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1217 // Values for use with panEdgeFraction, which limit how far outside the
1218 // graph's data boundaries it can be panned.
1219 boundedDates
: null, // [minDate, maxDate]
1220 boundedValues
: null, // [[minValue, maxValue] ...]
1222 initializeMouseDown
: function(event
, g
, context
) {
1223 // prevents mouse drags from selecting page text.
1224 if (event
.preventDefault
) {
1225 event
.preventDefault(); // Firefox, Chrome, etc.
1227 event
.returnValue
= false; // IE
1228 event
.cancelBubble
= true;
1231 context
.px
= Dygraph
.findPosX(g
.canvas_
);
1232 context
.py
= Dygraph
.findPosY(g
.canvas_
);
1233 context
.dragStartX
= g
.dragGetX_(event
, context
);
1234 context
.dragStartY
= g
.dragGetY_(event
, context
);
1235 context
.cancelNextDblclick
= false;
1239 var interactionModel
= this.attr_("interactionModel");
1241 // Self is the graph.
1244 // Function that binds the graph and context to the handler.
1245 var bindHandler
= function(handler
) {
1246 return function(event
) {
1247 handler(event
, self
, context
);
1251 for (var eventName
in interactionModel
) {
1252 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1253 Dygraph
.addEvent(this.mouseEventElement_
, eventName
,
1254 bindHandler(interactionModel
[eventName
]));
1257 // If the user releases the mouse button during a drag, but not over the
1258 // canvas, then it doesn't count as a zooming action.
1259 this.mouseUpHandler_
= function(event
) {
1260 if (context
.isZooming
|| context
.isPanning
) {
1261 context
.isZooming
= false;
1262 context
.dragStartX
= null;
1263 context
.dragStartY
= null;
1266 if (context
.isPanning
) {
1267 context
.isPanning
= false;
1268 context
.draggingDate
= null;
1269 context
.dateRange
= null;
1270 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1271 delete self
.axes_
[i
].draggingValue
;
1272 delete self
.axes_
[i
].dragValueRange
;
1277 Dygraph
.addEvent(document
, 'mouseup', this.mouseUpHandler_
);
1281 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1282 * up any previous zoom rectangles that were drawn. This could be optimized to
1283 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1286 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1287 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1288 * @param {Number} startX The X position where the drag started, in canvas
1290 * @param {Number} endX The current X position of the drag, in canvas coords.
1291 * @param {Number} startY The Y position where the drag started, in canvas
1293 * @param {Number} endY The current Y position of the drag, in canvas coords.
1294 * @param {Number} prevDirection the value of direction on the previous call to
1295 * this function. Used to avoid excess redrawing
1296 * @param {Number} prevEndX The value of endX on the previous call to this
1297 * function. Used to avoid excess redrawing
1298 * @param {Number} prevEndY The value of endY on the previous call to this
1299 * function. Used to avoid excess redrawing
1302 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1303 endY
, prevDirection
, prevEndX
,
1305 var ctx
= this.canvas_ctx_
;
1307 // Clean up from the previous rect if necessary
1308 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1309 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1310 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1311 } else if (prevDirection
== Dygraph
.VERTICAL
){
1312 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1313 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1316 // Draw a light-grey rectangle to show the new viewing area
1317 if (direction
== Dygraph
.HORIZONTAL
) {
1318 if (endX
&& startX
) {
1319 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1320 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1321 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1323 } else if (direction
== Dygraph
.VERTICAL
) {
1324 if (endY
&& startY
) {
1325 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1326 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1327 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1331 if (this.isUsingExcanvas_
) {
1332 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1337 * Clear the zoom rectangle (and perform no zoom).
1340 Dygraph
.prototype.clearZoomRect_
= function() {
1341 this.currentZoomRectArgs_
= null;
1342 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1346 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1347 * the canvas. The exact zoom window may be slightly larger if there are no data
1348 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1349 * which accepts dates that match the raw data. This function redraws the graph.
1351 * @param {Number} lowX The leftmost pixel value that should be visible.
1352 * @param {Number} highX The rightmost pixel value that should be visible.
1355 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1356 this.currentZoomRectArgs_
= null;
1357 // Find the earliest and latest dates contained in this canvasx range.
1358 // Convert the call to date ranges of the raw data.
1359 var minDate
= this.toDataXCoord(lowX
);
1360 var maxDate
= this.toDataXCoord(highX
);
1361 this.doZoomXDates_(minDate
, maxDate
);
1365 * Transition function to use in animations. Returns values between 0.0
1366 * (totally old values) and 1.0 (totally new values) for each frame.
1369 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1371 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1375 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1376 * method with doZoomX which accepts pixel coordinates. This function redraws
1379 * @param {Number} minDate The minimum date that should be visible.
1380 * @param {Number} maxDate The maximum date that should be visible.
1383 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1384 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1385 // can produce strange effects. Rather than the y-axis transitioning slowly
1386 // between values, it can jerk around.)
1387 var old_window
= this.xAxisRange();
1388 var new_window
= [minDate
, maxDate
];
1389 this.zoomed_x_
= true;
1391 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1392 if (that
.attr_("zoomCallback")) {
1393 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1399 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1400 * the canvas. This function redraws the graph.
1402 * @param {Number} lowY The topmost pixel value that should be visible.
1403 * @param {Number} highY The lowest pixel value that should be visible.
1406 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1407 this.currentZoomRectArgs_
= null;
1408 // Find the highest and lowest values in pixel range for each axis.
1409 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1410 // This is because pixels increase as you go down on the screen, whereas data
1411 // coordinates increase as you go up the screen.
1412 var oldValueRanges
= this.yAxisRanges();
1413 var newValueRanges
= [];
1414 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1415 var hi
= this.toDataYCoord(lowY
, i
);
1416 var low
= this.toDataYCoord(highY
, i
);
1417 newValueRanges
.push([low
, hi
]);
1420 this.zoomed_y_
= true;
1422 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1423 if (that
.attr_("zoomCallback")) {
1424 var xRange
= that
.xAxisRange();
1425 that
.attr_("zoomCallback")(xRange
[0], xRange
[1], that
.yAxisRanges());
1431 * Reset the zoom to the original view coordinates. This is the same as
1432 * double-clicking on the graph.
1436 Dygraph
.prototype.doUnzoom_
= function() {
1437 var dirty
= false, dirtyX
= false, dirtyY
= false;
1438 if (this.dateWindow_
!== null) {
1443 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1444 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1450 // Clear any selection, since it's likely to be drawn in the wrong place.
1451 this.clearSelection();
1454 this.zoomed_x_
= false;
1455 this.zoomed_y_
= false;
1457 var minDate
= this.rawData_
[0][0];
1458 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1460 // With only one frame, don't bother calculating extreme ranges.
1461 // TODO(danvk): merge this block w/ the code below
.
1462 if (!this.attr_("animatedZooms")) {
1463 this.dateWindow_
= null;
1464 for (i
= 0; i
< this.axes_
.length
; i
++) {
1465 if (this.axes_
[i
].valueWindow
!== null) {
1466 delete this.axes_
[i
].valueWindow
;
1470 if (this.attr_("zoomCallback")) {
1471 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1476 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1478 oldWindow
= this.xAxisRange();
1479 newWindow
= [minDate
, maxDate
];
1483 oldValueRanges
= this.yAxisRanges();
1484 // TODO(danvk): this is pretty inefficient
1485 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1486 var extremes
= packed
[1];
1488 // this has the side-effect of modifying this.axes_.
1489 // this doesn't make much sense in this context, but it's convenient (we
1490 // need this.axes_[*].extremeValues) and not harmful since we'll be
1491 // calling drawGraph_ shortly, which clobbers these values.
1492 this.computeYAxisRanges_(extremes
);
1494 newValueRanges
= [];
1495 for (i
= 0; i
< this.axes_
.length
; i
++) {
1496 var axis
= this.axes_
[i
];
1497 newValueRanges
.push(axis
.valueRange
!= null ? axis
.valueRange
: axis
.extremeRange
);
1502 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1504 that
.dateWindow_
= null;
1505 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1506 if (that
.axes_
[i
].valueWindow
!== null) {
1507 delete that
.axes_
[i
].valueWindow
;
1510 if (that
.attr_("zoomCallback")) {
1511 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1518 * Combined animation logic for all zoom functions.
1519 * either the x parameters or y parameters may be null.
1522 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1523 var steps
= this.attr_("animatedZooms") ? Dygraph
.ANIMATION_STEPS
: 1;
1526 var valueRanges
= [];
1529 if (oldXRange
!== null && newXRange
!== null) {
1530 for (step
= 1; step
<= steps
; step
++) {
1531 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1532 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1533 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1537 if (oldYRanges
!== null && newYRanges
!== null) {
1538 for (step
= 1; step
<= steps
; step
++) {
1539 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1541 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1542 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1543 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1545 valueRanges
[step
-1] = thisRange
;
1550 Dygraph
.repeatAndCleanup(function(step
) {
1551 if (valueRanges
.length
) {
1552 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1553 var w
= valueRanges
[step
][i
];
1554 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1557 if (windows
.length
) {
1558 that
.dateWindow_
= windows
[step
];
1561 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1565 * Get the current graph's area object.
1567 * Returns: {x, y, w, h}
1569 Dygraph
.prototype.getArea
= function() {
1570 return this.plotter_
.area
;
1574 * Convert a mouse event to DOM coordinates relative to the graph origin.
1576 * Returns a two-element array: [X, Y].
1578 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1579 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1580 var canvasy
= Dygraph
.pageY(event
) - Dygraph
.findPosY(this.mouseEventElement_
);
1581 return [canvasx
, canvasy
];
1585 * Given a canvas X coordinate, find the closest row.
1586 * @param {Number} domX graph-relative DOM X coordinate
1587 * Returns: row number, integer
1590 Dygraph
.prototype.findClosestRow
= function(domX
) {
1591 var minDistX
= Infinity
;
1593 var points
= this.layout_
.points
;
1594 var l
= points
.length
;
1595 for (var i
= 0; i
< l
; i
++) {
1596 var point
= points
[i
];
1597 if (!Dygraph
.isValidPoint(point
, true)) continue;
1598 var dist
= Math
.abs(point
.canvasx
- domX
);
1599 if (dist
< minDistX
) {
1604 return this.idxToRow_(idx
);
1608 * Given canvas X,Y coordinates, find the closest point.
1610 * This finds the individual data point across all visible series
1611 * that's closest to the supplied DOM coordinates using the standard
1612 * Euclidean X,Y distance.
1614 * @param {Number} domX graph-relative DOM X coordinate
1615 * @param {Number} domY graph-relative DOM Y coordinate
1616 * Returns: {row, seriesName, point}
1619 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1620 var minDist
= Infinity
;
1622 var points
= this.layout_
.points
;
1623 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
;
1624 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1625 var first
= this.layout_
.setPointsOffsets
[setIdx
];
1626 var len
= this.layout_
.setPointsLengths
[setIdx
];
1627 for (var i
= 0; i
< len
; ++i
) {
1628 var point
= points
[first
+ i
];
1629 if (!Dygraph
.isValidPoint(point
)) continue;
1630 dx
= point
.canvasx
- domX
;
1631 dy
= point
.canvasy
- domY
;
1632 dist
= dx
* dx
+ dy
* dy
;
1633 if (dist
< minDist
) {
1635 closestPoint
= point
;
1636 closestSeries
= setIdx
;
1641 var name
= this.layout_
.setNames
[closestSeries
];
1643 row
: idx
+ this.getLeftBoundary_(),
1650 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1652 * This first finds the X data point closest to the supplied DOM X coordinate,
1653 * then finds the series which puts the Y coordinate on top of its filled area,
1654 * using linear interpolation between adjacent point pairs.
1656 * @param {Number} domX graph-relative DOM X coordinate
1657 * @param {Number} domY graph-relative DOM Y coordinate
1658 * Returns: {row, seriesName, point}
1661 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1662 var row
= this.findClosestRow(domX
);
1663 var boundary
= this.getLeftBoundary_();
1664 var rowIdx
= row
- boundary
;
1665 var points
= this.layout_
.points
;
1666 var closestPoint
, closestSeries
;
1667 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1668 var first
= this.layout_
.setPointsOffsets
[setIdx
];
1669 var len
= this.layout_
.setPointsLengths
[setIdx
];
1670 if (rowIdx
>= len
) continue;
1671 var p1
= points
[first
+ rowIdx
];
1672 if (!Dygraph
.isValidPoint(p1
)) continue;
1673 var py
= p1
.canvasy
;
1674 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < len
) {
1675 // interpolate series Y value using next point
1676 var p2
= points
[first
+ rowIdx
+ 1];
1677 if (Dygraph
.isValidPoint(p2
)) {
1678 var dx
= p2
.canvasx
- p1
.canvasx
;
1680 var r
= (domX
- p1
.canvasx
) / dx
;
1681 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1684 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1685 // interpolate series Y value using previous point
1686 var p0
= points
[first
+ rowIdx
- 1];
1687 if (Dygraph
.isValidPoint(p0
)) {
1688 var dx
= p1
.canvasx
- p0
.canvasx
;
1690 var r
= (p1
.canvasx
- domX
) / dx
;
1691 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1695 // Stop if the point (domX, py) is above this series' upper edge
1696 if (setIdx
== 0 || py
< domY
) {
1698 closestSeries
= setIdx
;
1701 var name
= this.layout_
.setNames
[closestSeries
];
1710 * When the mouse moves in the canvas, display information about a nearby data
1711 * point and draw dots over those points in the data series. This function
1712 * takes care of cleanup of previously-drawn dots.
1713 * @param {Object} event The mousemove event from the browser.
1716 Dygraph
.prototype.mouseMove_
= function(event
) {
1717 // This prevents JS errors when mousing over the canvas before data loads.
1718 var points
= this.layout_
.points
;
1719 if (points
=== undefined
) return;
1721 var canvasCoords
= this.eventToDomCoords(event
);
1722 var canvasx
= canvasCoords
[0];
1723 var canvasy
= canvasCoords
[1];
1725 var highlightSeriesOpts
= this.attr_("highlightSeriesOpts");
1726 var selectionChanged
= false;
1727 if (highlightSeriesOpts
) {
1729 if (this.attr_("stackedGraph")) {
1730 closest
= this.findStackedPoint(canvasx
, canvasy
);
1732 closest
= this.findClosestPoint(canvasx
, canvasy
);
1734 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1736 var idx
= this.findClosestRow(canvasx
);
1737 selectionChanged
= this.setSelection(idx
);
1740 var callback
= this.attr_("highlightCallback");
1741 if (callback
&& selectionChanged
) {
1742 callback(event
, this.lastx_
, this.selPoints_
, this.lastRow_
, this.highlightSet_
);
1747 * Fetch left offset from first defined boundaryIds record (see bug #236).
1750 Dygraph
.prototype.getLeftBoundary_
= function() {
1751 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1752 if (this.boundaryIds_
[i
] !== undefined
) {
1753 return this.boundaryIds_
[i
][0];
1760 * Transforms layout_.points index into data row number.
1761 * @param int layout_.points index
1762 * @return int row number, or -1 if none could be found.
1765 Dygraph
.prototype.idxToRow_
= function(idx
) {
1766 if (idx
< 0) return -1;
1768 var boundary
= this.getLeftBoundary_();
1769 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1770 var set
= this.layout_
.datasets
[setIdx
];
1771 if (idx
< set
.length
) {
1772 return boundary
+ idx
;
1779 Dygraph
.prototype.animateSelection_
= function(direction
) {
1780 var totalSteps
= 10;
1782 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1783 if (this.animateId
=== undefined
) this.animateId
= 0;
1784 var start
= this.fadeLevel
;
1785 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1787 if (this.fadeLevel
) {
1788 this.updateSelection_(1.0);
1793 var thisId
= ++this.animateId
;
1795 Dygraph
.repeatAndCleanup(
1797 // ignore simultaneous animations
1798 if (that
.animateId
!= thisId
) return;
1800 that
.fadeLevel
+= direction
;
1801 if (that
.fadeLevel
=== 0) {
1802 that
.clearSelection();
1804 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1807 steps
, millis
, function() {});
1811 * Draw dots over the selectied points in the data series. This function
1812 * takes care of cleanup of previously-drawn dots.
1815 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1816 var defaultPrevented
= this.cascadeEvents_('select', {
1817 selectedX
: this.lastx_
,
1818 selectedPoints
: this.selPoints_
1820 // TODO(danvk): use defaultPrevented here?
1822 // Clear the previously drawn vertical, if there is one
1824 var ctx
= this.canvas_ctx_
;
1825 if (this.attr_('highlightSeriesOpts')) {
1826 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1827 var alpha
= 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
1829 // Activating background fade includes an animation effect for a gradual
1830 // fade. TODO(klausw): make this independently configurable if it causes
1831 // issues? Use a shared preference to control animations?
1832 var animateBackgroundFade
= true;
1833 if (animateBackgroundFade
) {
1834 if (opt_animFraction
=== undefined
) {
1835 // start a new animation
1836 this.animateSelection_(1);
1839 alpha
*= opt_animFraction
;
1841 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1842 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1844 var setIdx
= this.datasetIndexFromSetName_(this.highlightSet_
);
1845 this.plotter_
._drawLine(ctx
, setIdx
);
1846 } else if (this.previousVerticalX_
>= 0) {
1847 // Determine the maximum highlight circle size.
1848 var maxCircleSize
= 0;
1849 var labels
= this.attr_('labels');
1850 for (i
= 1; i
< labels
.length
; i
++) {
1851 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1852 if (r
> maxCircleSize
) maxCircleSize
= r
;
1854 var px
= this.previousVerticalX_
;
1855 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1856 2 * maxCircleSize
+ 2, this.height_
);
1859 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
1860 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
1863 if (this.selPoints_
.length
> 0) {
1864 // Draw colored circles over the center of each selected point
1865 var canvasx
= this.selPoints_
[0].canvasx
;
1867 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1868 var pt
= this.selPoints_
[i
];
1869 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1871 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1872 var callback
= this.attr_("drawHighlightPointCallback", pt
.name
);
1873 var color
= this.plotter_
.colors
[pt
.name
];
1875 callback
= Dygraph
.Circles
.DEFAULT
;
1877 ctx
.lineWidth
= this.attr_('strokeWidth', pt
.name
);
1878 ctx
.strokeStyle
= color
;
1879 ctx
.fillStyle
= color
;
1880 callback(this.g
, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1885 this.previousVerticalX_
= canvasx
;
1890 * Manually set the selected points and display information about them in the
1891 * legend. The selection can be cleared using clearSelection() and queried
1892 * using getSelection().
1893 * @param { Integer } row number that should be highlighted (i.e. appear with
1894 * hover dots on the chart). Set to false to clear any selection.
1895 * @param { seriesName } optional series name to highlight that series with the
1896 * the highlightSeriesOpts setting.
1898 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
) {
1899 // Extract the points we've selected
1900 this.selPoints_
= [];
1903 if (row
!== false) {
1904 row
-= this.getLeftBoundary_();
1907 var changed
= false;
1908 if (row
!== false && row
>= 0) {
1909 if (row
!= this.lastRow_
) changed
= true;
1910 this.lastRow_
= row
;
1911 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1912 var set
= this.layout_
.datasets
[setIdx
];
1913 if (row
< set
.length
) {
1914 var point
= this.layout_
.points
[pos
+row
];
1916 if (this.attr_("stackedGraph")) {
1917 point
= this.layout_
.unstackPointAtIndex(pos
+row
);
1920 if (!(point
.yval
=== null)) this.selPoints_
.push(point
);
1925 if (this.lastRow_
>= 0) changed
= true;
1929 if (this.selPoints_
.length
) {
1930 this.lastx_
= this.selPoints_
[0].xval
;
1935 if (opt_seriesName
!== undefined
) {
1936 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
1937 this.highlightSet_
= opt_seriesName
;
1941 this.updateSelection_(undefined
);
1947 * The mouse has left the canvas. Clear out whatever artifacts remain
1948 * @param {Object} event the mouseout event from the browser.
1951 Dygraph
.prototype.mouseOut_
= function(event
) {
1952 if (this.attr_("unhighlightCallback")) {
1953 this.attr_("unhighlightCallback")(event
);
1956 if (this.attr_("hideOverlayOnMouseOut")) {
1957 this.clearSelection();
1962 * Clears the current selection (i.e. points that were highlighted by moving
1963 * the mouse over the chart).
1965 Dygraph
.prototype.clearSelection
= function() {
1966 this.cascadeEvents_('deselect', {});
1968 // Get rid of the overlay data
1969 if (this.fadeLevel
) {
1970 this.animateSelection_(-1);
1973 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1975 this.selPoints_
= [];
1978 this.highlightSet_
= null;
1982 * Returns the number of the currently selected row. To get data for this row,
1983 * you can use the getValue method.
1984 * @return { Integer } row number, or -1 if nothing is selected
1986 Dygraph
.prototype.getSelection
= function() {
1987 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
1991 for (var row
=0; row
<this.layout_
.points
.length
; row
++ ) {
1992 if (this.layout_
.points
[row
].x
== this.selPoints_
[0].x
) {
1993 return row
+ this.getLeftBoundary_();
2000 * Returns the name of the currently-highlighted series.
2001 * Only available when the highlightSeriesOpts option is in use.
2003 Dygraph
.prototype.getHighlightSeries
= function() {
2004 return this.highlightSet_
;
2008 * Fires when there's data available to be graphed.
2009 * @param {String} data Raw CSV data to be plotted
2012 Dygraph
.prototype.loadedEvent_
= function(data
) {
2013 this.rawData_
= this.parseCSV_(data
);
2018 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2021 Dygraph
.prototype.addXTicks_
= function() {
2022 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2024 if (this.dateWindow_
) {
2025 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2027 range
= this.fullXRange_();
2030 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2031 var xTicks
= xAxisOptionsView('ticker')(
2034 this.width_
, // TODO(danvk): should be area.width
2037 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2038 // console.log(msg);
2039 this.layout_
.setXTicks(xTicks
);
2044 * Computes the range of the data series (including confidence intervals).
2045 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2046 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2047 * @return [low, high]
2049 Dygraph
.prototype.extremeValues_
= function(series
) {
2050 var minY
= null, maxY
= null, j
, y
;
2052 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2054 // With custom bars, maxY is the max of the high values.
2055 for (j
= 0; j
< series
.length
; j
++) {
2056 y
= series
[j
][1][0];
2058 var low
= y
- series
[j
][1][1];
2059 var high
= y
+ series
[j
][1][2];
2060 if (low
> y
) low
= y
; // this can happen with custom bars,
2061 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2062 if (maxY
=== null || high
> maxY
) {
2065 if (minY
=== null || low
< minY
) {
2070 for (j
= 0; j
< series
.length
; j
++) {
2072 if (y
=== null || isNaN(y
)) continue;
2073 if (maxY
=== null || y
> maxY
) {
2076 if (minY
=== null || y
< minY
) {
2082 return [minY
, maxY
];
2087 * This function is called once when the chart's data is changed or the options
2088 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2089 * idea is that values derived from the chart's data can be computed here,
2090 * rather than every time the chart is drawn. This includes things like the
2091 * number of axes, rolling averages, etc.
2093 Dygraph
.prototype.predraw_
= function() {
2094 var start
= new Date();
2096 // TODO(danvk): move more computations out of drawGraph_ and into here.
2097 this.computeYAxes_();
2099 // Create a new plotter.
2100 if (this.plotter_
) this.plotter_
.clear();
2101 this.plotter_
= new DygraphCanvasRenderer(this,
2106 // The roller sits in the bottom left corner of the chart. We don't know where
2107 // this will be until the options are available, so it's positioned here.
2108 this.createRollInterface_();
2110 this.cascadeEvents_('predraw');
2112 if (this.rangeSelector_
) {
2113 this.rangeSelector_
.renderStaticLayer();
2116 // Convert the raw data (a 2D array) into the internal format and compute
2117 // rolling averages.
2118 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2119 for (var i
= 1; i
< this.numColumns(); i
++) {
2120 var logScale
= this.attr_('logscale', i
); // TODO(klausw): this looks wrong
2121 var series
= this.extractSeries_(this.rawData_
, i
, logScale
);
2122 series
= this.rollingAverage(series
, this.rollPeriod_
);
2123 this.rolledSeries_
.push(series
);
2126 // If the data or options have changed, then we'd better redraw.
2129 // This is used to determine whether to do various animations.
2130 var end
= new Date();
2131 this.drawingTimeMs_
= (end
- start
);
2135 * Loop over all fields and create datasets, calculating extreme y-values for
2136 * each series and extreme x-indices as we go.
2138 * dateWindow is passed in as an explicit parameter so that we can compute
2139 * extreme values "speculatively", i.e. without actually setting state on the
2142 * TODO(danvk): make this more of a true function
2143 * @return [ datasets, seriesExtremes, boundaryIds ]
2146 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2147 var boundaryIds
= [];
2148 var cumulative_y
= []; // For stacked series.
2150 var extremes
= {}; // series name -> [low, high]
2153 // Loop over the fields (series). Go from the last to the first,
2154 // because if they're stacked that's how we accumulate the values.
2155 var num_series
= rolledSeries
.length
- 1;
2156 for (i
= num_series
; i
>= 1; i
--) {
2157 if (!this.visibility()[i
- 1]) continue;
2159 // TODO(danvk): is this copy really necessary?
2161 for (j
= 0; j
< rolledSeries
[i
].length
; j
++) {
2162 series
.push(rolledSeries
[i
][j
]);
2165 // Prune down to the desired range, if necessary (for zooming)
2166 // Because there can be lines going to points outside of the visible area,
2167 // we actually prune to visible points, plus one on either side.
2168 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2170 var low
= dateWindow
[0];
2171 var high
= dateWindow
[1];
2173 // TODO(danvk): do binary search instead of linear search.
2174 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2175 var firstIdx
= null, lastIdx
= null;
2176 for (k
= 0; k
< series
.length
; k
++) {
2177 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2180 if (series
[k
][0] <= high
) {
2184 if (firstIdx
=== null) firstIdx
= 0;
2185 if (firstIdx
> 0) firstIdx
--;
2186 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2187 if (lastIdx
< series
.length
- 1) lastIdx
++;
2188 boundaryIds
[i
-1] = [firstIdx
, lastIdx
];
2189 for (k
= firstIdx
; k
<= lastIdx
; k
++) {
2190 pruned
.push(series
[k
]);
2194 boundaryIds
[i
-1] = [0, series
.length
-1];
2197 var seriesExtremes
= this.extremeValues_(series
);
2200 for (j
=0; j
<series
.length
; j
++) {
2201 series
[j
] = [series
[j
][0],
2206 } else if (this.attr_("stackedGraph")) {
2207 var l
= series
.length
;
2209 for (j
= 0; j
< l
; j
++) {
2210 // If one data set has a NaN, let all subsequent stacked
2211 // sets inherit the NaN -- only start at 0 for the first set.
2212 var x
= series
[j
][0];
2213 if (cumulative_y
[x
] === undefined
) {
2214 cumulative_y
[x
] = 0;
2217 actual_y
= series
[j
][1];
2218 if (actual_y
=== null) {
2219 series
[j
] = [x
, null];
2223 cumulative_y
[x
] += actual_y
;
2225 series
[j
] = [x
, cumulative_y
[x
]];
2227 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2228 seriesExtremes
[1] = cumulative_y
[x
];
2230 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2231 seriesExtremes
[0] = cumulative_y
[x
];
2236 var seriesName
= this.attr_("labels")[i
];
2237 extremes
[seriesName
] = seriesExtremes
;
2238 datasets
[i
] = series
;
2241 // For stacked graphs, a NaN value for any point in the sum should create a
2242 // clean gap in the graph. Back-propagate NaNs to all points at this X value.
2243 if (this.attr_("stackedGraph")) {
2244 for (k
= datasets
.length
- 1; k
>= 0; --k
) {
2245 // Use the first nonempty dataset to get X values.
2246 if (!datasets
[k
]) continue;
2247 for (j
= 0; j
< datasets
[k
].length
; j
++) {
2248 var x
= datasets
[k
][j
][0];
2249 if (isNaN(cumulative_y
[x
])) {
2250 // Set all Y values to NaN at that X value.
2251 for (i
= datasets
.length
- 1; i
>= 0; i
--) {
2252 if (!datasets
[i
]) continue;
2253 datasets
[i
][j
][1] = NaN
;
2261 return [ datasets
, extremes
, boundaryIds
];
2265 * Update the graph with new data. This method is called when the viewing area
2266 * has changed. If the underlying data or options have changed, predraw_ will
2267 * be called before drawGraph_ is called.
2271 Dygraph
.prototype.drawGraph_
= function() {
2272 var start
= new Date();
2274 // This is used to set the second parameter to drawCallback, below.
2275 var is_initial_draw
= this.is_initial_draw_
;
2276 this.is_initial_draw_
= false;
2278 this.layout_
.removeAllDatasets();
2280 this.attrs_
.pointSize
= 0.5 * this.attr_('highlightCircleSize');
2282 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2283 var datasets
= packed
[0];
2284 var extremes
= packed
[1];
2285 this.boundaryIds_
= packed
[2];
2287 this.setIndexByName_
= {};
2288 var labels
= this.attr_("labels");
2289 if (labels
.length
> 0) {
2290 this.setIndexByName_
[labels
[0]] = 0;
2293 for (var i
= 1; i
< datasets
.length
; i
++) {
2294 this.setIndexByName_
[labels
[i
]] = i
;
2295 if (!this.visibility()[i
- 1]) continue;
2296 this.layout_
.addDataset(labels
[i
], datasets
[i
]);
2297 this.datasetIndex_
[i
] = dataIdx
++;
2300 this.computeYAxisRanges_(extremes
);
2301 this.layout_
.setYAxes(this.axes_
);
2305 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2306 var tmp_zoomed_x
= this.zoomed_x_
;
2307 // Tell PlotKit to use this new data and render itself
2308 this.layout_
.setDateWindow(this.dateWindow_
);
2309 this.zoomed_x_
= tmp_zoomed_x
;
2310 this.layout_
.evaluateWithError();
2311 this.renderGraph_(is_initial_draw
);
2313 if (this.attr_("timingName")) {
2314 var end
= new Date();
2316 console
.log(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2322 * This does the work of drawing the chart. It assumes that the layout and axis
2323 * scales have already been set (e.g. by predraw_).
2327 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2328 this.plotter_
.clear();
2329 this.plotter_
.render();
2330 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2331 this.canvas_
.height
);
2333 // Generate a static legend before any particular point is selected.
2335 if (this.rangeSelector_
) {
2336 this.rangeSelector_
.renderInteractiveLayer();
2339 this.cascadeEvents_('drawChart');
2340 if (this.attr_("drawCallback") !== null) {
2341 this.attr_("drawCallback")(this, is_initial_draw
);
2347 * Determine properties of the y-axes which are independent of the data
2348 * currently being displayed. This includes things like the number of axes and
2349 * the style of the axes. It does not include the range of each axis and its
2351 * This fills in this.axes_ and this.seriesToAxisMap_.
2352 * axes_ = [ { options } ]
2353 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2354 * indices are into the axes_ array.
2356 Dygraph
.prototype.computeYAxes_
= function() {
2357 // Preserve valueWindow settings if they exist, and if the user hasn't
2358 // specified a new valueRange.
2359 var i
, valueWindows
, seriesName
, axis
, index
, opts
, v
;
2360 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2362 for (index
= 0; index
< this.axes_
.length
; index
++) {
2363 valueWindows
.push(this.axes_
[index
].valueWindow
);
2367 this.axes_
= [{ yAxisId
: 0, g
: this }]; // always have at least one y-axis.
2368 this.seriesToAxisMap_
= {};
2370 // Get a list of series names.
2371 var labels
= this.attr_("labels");
2373 for (i
= 1; i
< labels
.length
; i
++) series
[labels
[i
]] = (i
- 1);
2375 // all options which could be applied per-axis:
2383 'axisLabelFontSize',
2388 // Copy global axis options over to the first axis.
2389 for (i
= 0; i
< axisOptions
.length
; i
++) {
2390 var k
= axisOptions
[i
];
2392 if (v
) this.axes_
[0][k
] = v
;
2395 // Go through once and add all the axes.
2396 for (seriesName
in series
) {
2397 if (!series
.hasOwnProperty(seriesName
)) continue;
2398 axis
= this.attr_("axis", seriesName
);
2399 if (axis
=== null) {
2400 this.seriesToAxisMap_
[seriesName
] = 0;
2403 if (typeof(axis
) == 'object') {
2404 // Add a new axis, making a copy of its per-axis options.
2406 Dygraph
.update(opts
, this.axes_
[0]);
2407 Dygraph
.update(opts
, { valueRange
: null }); // shouldn't inherit this.
2408 var yAxisId
= this.axes_
.length
;
2409 opts
.yAxisId
= yAxisId
;
2411 Dygraph
.update(opts
, axis
);
2412 this.axes_
.push(opts
);
2413 this.seriesToAxisMap_
[seriesName
] = yAxisId
;
2417 // Go through one more time and assign series to an axis defined by another
2418 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
2419 for (seriesName
in series
) {
2420 if (!series
.hasOwnProperty(seriesName
)) continue;
2421 axis
= this.attr_("axis", seriesName
);
2422 if (typeof(axis
) == 'string') {
2423 if (!this.seriesToAxisMap_
.hasOwnProperty(axis
)) {
2424 this.error("Series " + seriesName
+ " wants to share a y-axis with " +
2425 "series " + axis
+ ", which does not define its own axis.");
2428 var idx
= this.seriesToAxisMap_
[axis
];
2429 this.seriesToAxisMap_
[seriesName
] = idx
;
2433 if (valueWindows
!== undefined
) {
2434 // Restore valueWindow settings.
2435 for (index
= 0; index
< valueWindows
.length
; index
++) {
2436 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2441 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2443 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2444 v
= opts("valueRange");
2445 if (v
) this.axes_
[axis
].valueRange
= v
;
2446 } else { // To keep old behavior
2447 var axes
= this.user_attrs_
.axes
;
2448 if (axes
&& axes
.y2
) {
2449 v
= axes
.y2
.valueRange
;
2450 if (v
) this.axes_
[axis
].valueRange
= v
;
2458 * Returns the number of y-axes on the chart.
2459 * @return {Number} the number of axes.
2461 Dygraph
.prototype.numAxes
= function() {
2463 for (var series
in this.seriesToAxisMap_
) {
2464 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2465 var idx
= this.seriesToAxisMap_
[series
];
2466 if (idx
> last_axis
) last_axis
= idx
;
2468 return 1 + last_axis
;
2473 * Returns axis properties for the given series.
2474 * @param { String } setName The name of the series for which to get axis
2475 * properties, e.g. 'Y1'.
2476 * @return { Object } The axis properties.
2478 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2479 // TODO(danvk): handle errors.
2480 return this.axes_
[this.seriesToAxisMap_
[series
]];
2485 * Determine the value range and tick marks for each axis.
2486 * @param {Object} extremes A mapping from seriesName -> [low, high]
2487 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2489 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2490 // Build a map from axis number -> [list of series names]
2491 var seriesForAxis
= [], series
;
2492 for (series
in this.seriesToAxisMap_
) {
2493 if (!this.seriesToAxisMap_
.hasOwnProperty(series
)) continue;
2494 var idx
= this.seriesToAxisMap_
[series
];
2495 while (seriesForAxis
.length
<= idx
) seriesForAxis
.push([]);
2496 seriesForAxis
[idx
].push(series
);
2499 // Compute extreme values, a span and tick marks for each axis.
2500 for (var i
= 0; i
< this.axes_
.length
; i
++) {
2501 var axis
= this.axes_
[i
];
2503 if (!seriesForAxis
[i
]) {
2504 // If no series are defined or visible then use a reasonable default
2505 axis
.extremeRange
= [0, 1];
2507 // Calculate the extremes of extremes.
2508 series
= seriesForAxis
[i
];
2509 var minY
= Infinity
; // extremes[series[0]][0];
2510 var maxY
= -Infinity
; // extremes[series[0]][1];
2511 var extremeMinY
, extremeMaxY
;
2513 for (var j
= 0; j
< series
.length
; j
++) {
2514 // this skips invisible series
2515 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2517 // Only use valid extremes to stop null data series' from corrupting the scale.
2518 extremeMinY
= extremes
[series
[j
]][0];
2519 if (extremeMinY
!== null) {
2520 minY
= Math
.min(extremeMinY
, minY
);
2522 extremeMaxY
= extremes
[series
[j
]][1];
2523 if (extremeMaxY
!== null) {
2524 maxY
= Math
.max(extremeMaxY
, maxY
);
2527 if (axis
.includeZero
&& minY
> 0) minY
= 0;
2529 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2530 if (minY
== Infinity
) minY
= 0;
2531 if (maxY
== -Infinity
) maxY
= 1;
2533 // Add some padding and round up to an integer to be human-friendly.
2534 var span
= maxY
- minY
;
2535 // special case: if we have no sense of scale, use +/-10% of the sole value
.
2536 if (span
=== 0) { span
= maxY
; }
2538 var maxAxisY
, minAxisY
;
2539 if (axis
.logscale
) {
2540 maxAxisY
= maxY
+ 0.1 * span
;
2543 maxAxisY
= maxY
+ 0.1 * span
;
2544 minAxisY
= minY
- 0.1 * span
;
2546 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2547 if (!this.attr_("avoidMinZero")) {
2548 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2549 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2552 if (this.attr_("includeZero")) {
2553 if (maxY
< 0) maxAxisY
= 0;
2554 if (minY
> 0) minAxisY
= 0;
2557 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2559 if (axis
.valueWindow
) {
2560 // This is only set if the user has zoomed on the y-axis. It is never set
2561 // by a user. It takes precedence over axis.valueRange because, if you set
2562 // valueRange, you'd still expect to be able to pan.
2563 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2564 } else if (axis
.valueRange
) {
2565 // This is a user-set value range for this axis.
2566 axis
.computedValueRange
= [axis
.valueRange
[0], axis
.valueRange
[1]];
2568 axis
.computedValueRange
= axis
.extremeRange
;
2571 // Add ticks. By default, all axes inherit the tick positions of the
2572 // primary axis. However, if an axis is specifically marked as having
2573 // independent ticks, then that is permissible as well.
2574 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2575 var ticker
= opts('ticker');
2576 if (i
=== 0 || axis
.independentTicks
) {
2577 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2578 axis
.computedValueRange
[1],
2579 this.height_
, // TODO(danvk): should be area.height
2583 var p_axis
= this.axes_
[0];
2584 var p_ticks
= p_axis
.ticks
;
2585 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2586 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2587 var tick_values
= [];
2588 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2589 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2590 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2591 tick_values
.push(y_val
);
2594 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2595 axis
.computedValueRange
[1],
2596 this.height_
, // TODO(danvk): should be area.height
2605 * Extracts one series from the raw data (a 2D array) into an array of (date,
2608 * This is where undesirable points (i.e. negative values on log scales and
2609 * missing values through which we wish to connect lines) are dropped.
2613 Dygraph
.prototype.extractSeries_
= function(rawData
, i
, logScale
) {
2615 for (var j
= 0; j
< rawData
.length
; j
++) {
2616 var x
= rawData
[j
][0];
2617 var point
= rawData
[j
][i
];
2619 // On the log scale, points less than zero do not exist.
2620 // This will create a gap in the chart.
2625 series
.push([x
, point
]);
2632 * Calculates the rolling average of a data set.
2633 * If originalData is [label, val], rolls the average of those.
2634 * If originalData is [label, [, it's interpreted as [value, stddev]
2635 * and the roll is returned in the same form, with appropriately reduced
2636 * stddev for each value.
2637 * Note that this is where fractional input (i.e. '5/10') is converted into
2639 * @param {Array} originalData The data in the appropriate format (see above)
2640 * @param {Number} rollPeriod The number of points over which to average the
2643 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2644 if (originalData
.length
< 2)
2645 return originalData
;
2646 rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2647 var rollingData
= [];
2648 var sigma
= this.attr_("sigma");
2650 var low
, high
, i
, j
, y
, sum
, num_ok
, stddev
;
2651 if (this.fractions_
) {
2653 var den
= 0; // numerator/denominator
2655 for (i
= 0; i
< originalData
.length
; i
++) {
2656 num
+= originalData
[i
][1][0];
2657 den
+= originalData
[i
][1][1];
2658 if (i
- rollPeriod
>= 0) {
2659 num
-= originalData
[i
- rollPeriod
][1][0];
2660 den
-= originalData
[i
- rollPeriod
][1][1];
2663 var date
= originalData
[i
][0];
2664 var value
= den
? num
/ den
: 0.0;
2665 if (this.attr_("errorBars")) {
2666 if (this.attr_("wilsonInterval")) {
2667 // For more details on this confidence interval, see:
2668 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2670 var p
= value
< 0 ? 0 : value
, n
= den
;
2671 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2672 var denom
= 1 + sigma
* sigma
/ den
;
2673 low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2674 high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2675 rollingData
[i
] = [date
,
2676 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2678 rollingData
[i
] = [date
, [0, 0, 0]];
2681 stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2682 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2685 rollingData
[i
] = [date
, mult
* value
];
2688 } else if (this.attr_("customBars")) {
2693 for (i
= 0; i
< originalData
.length
; i
++) {
2694 var data
= originalData
[i
][1];
2696 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2698 if (y
!== null && !isNaN(y
)) {
2704 if (i
- rollPeriod
>= 0) {
2705 var prev
= originalData
[i
- rollPeriod
];
2706 if (prev
[1][1] !== null && !isNaN(prev
[1][1])) {
2714 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2715 1.0 * (mid
- low
) / count
,
2716 1.0 * (high
- mid
) / count
]];
2718 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2722 // Calculate the rolling average for the first rollPeriod - 1 points where
2723 // there is not enough data to roll over the full number of points
2724 if (!this.attr_("errorBars")){
2725 if (rollPeriod
== 1) {
2726 return originalData
;
2729 for (i
= 0; i
< originalData
.length
; i
++) {
2732 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2733 y
= originalData
[j
][1];
2734 if (y
=== null || isNaN(y
)) continue;
2736 sum
+= originalData
[j
][1];
2739 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2741 rollingData
[i
] = [originalData
[i
][0], null];
2746 for (i
= 0; i
< originalData
.length
; i
++) {
2750 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2751 y
= originalData
[j
][1][0];
2752 if (y
=== null || isNaN(y
)) continue;
2754 sum
+= originalData
[j
][1][0];
2755 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2758 stddev
= Math
.sqrt(variance
) / num_ok
;
2759 rollingData
[i
] = [originalData
[i
][0],
2760 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2762 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2772 * Detects the type of the str (date or numeric) and sets the various
2773 * formatting attributes in this.attrs_ based on this type.
2774 * @param {String} str An x value.
2777 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2779 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2780 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
2781 str
.indexOf('/') >= 0 ||
2782 isNaN(parseFloat(str
))) {
2784 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2785 // TODO(danvk): remove support for this format.
2790 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2791 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
2792 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2793 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2795 /** @private (shut up, jsdoc!) */
2796 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2797 // TODO(danvk): use Dygraph.numberValueFormatter here?
2798 /** @private (shut up, jsdoc!) */
2799 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2800 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
2801 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2806 * Parses the value as a floating point number. This is like the parseFloat()
2807 * built-in, but with a few differences:
2808 * - the empty string is parsed as null, rather than NaN.
2809 * - if the string cannot be parsed at all, an error is logged.
2810 * If the string can't be parsed, this method returns null.
2811 * @param {String} x The string to be parsed
2812 * @param {Number} opt_line_no The line number from which the string comes.
2813 * @param {String} opt_line The text of the line from which the string comes.
2817 // Parse the x as a float or return null if it's not a number.
2818 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
2819 var val
= parseFloat(x
);
2820 if (!isNaN(val
)) return val
;
2822 // Try to figure out what happeend.
2823 // If the value is the empty string, parse it as null.
2824 if (/^ *$/.test(x
)) return null;
2826 // If it was actually "NaN", return it as NaN.
2827 if (/^ *nan *$/i.test(x
)) return NaN
;
2829 // Looks like a parsing error.
2830 var msg
= "Unable to parse '" + x
+ "' as a number";
2831 if (opt_line
!== null && opt_line_no
!== null) {
2832 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
2841 * Parses a string in a special csv format. We expect a csv file where each
2842 * line is a date point, and the first field in each line is the date string.
2843 * We also expect that all remaining fields represent series.
2844 * if the errorBars attribute is set, then interpret the fields as:
2845 * date, series1, stddev1, series2, stddev2, ...
2846 * @param {[Object]} data See above.
2848 * @return [Object] An array with one entry for each row. These entries
2849 * are an array of cells in that row. The first entry is the parsed x-value for
2850 * the row. The second, third, etc. are the y-values. These can take on one of
2851 * three forms, depending on the CSV and constructor parameters:
2853 * 2. [ value, stddev ]
2854 * 3. [ low value, center value, high value ]
2856 Dygraph
.prototype.parseCSV_
= function(data
) {
2858 var lines
= data
.split("\n");
2861 // Use the default delimiter or fall back to a tab if that makes sense.
2862 var delim
= this.attr_('delimiter');
2863 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
2868 if (!('labels' in this.user_attrs_
)) {
2869 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
2871 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
2876 var defaultParserSet
= false; // attempt to auto-detect x value type
2877 var expectedCols
= this.attr_("labels").length
;
2878 var outOfOrder
= false;
2879 for (var i
= start
; i
< lines
.length
; i
++) {
2880 var line
= lines
[i
];
2882 if (line
.length
=== 0) continue; // skip blank lines
2883 if (line
[0] == '#') continue; // skip comment lines
2884 var inFields
= line
.split(delim
);
2885 if (inFields
.length
< 2) continue;
2888 if (!defaultParserSet
) {
2889 this.detectTypeFromString_(inFields
[0]);
2890 xParser
= this.attr_("xValueParser");
2891 defaultParserSet
= true;
2893 fields
[0] = xParser(inFields
[0], this);
2895 // If fractions are expected, parse the numbers as "A/B
"
2896 if (this.fractions_) {
2897 for (j = 1; j < inFields.length; j++) {
2898 // TODO(danvk): figure out an appropriate way to flag parse errors.
2899 vals = inFields[j].split("/");
2900 if (vals.length != 2) {
2901 this.error('Expected fractional "num
/den
" values in CSV data ' +
2902 "but found a value
'" + inFields[j] + "' on line
" +
2903 (1 + i) + " ('" + line + "') which is not of
this form
.");
2906 fields[j] = [this.parseFloat_(vals[0], i, line),
2907 this.parseFloat_(vals[1], i, line)];
2910 } else if (this.attr_("errorBars
")) {
2911 // If there are error bars, values are (value, stddev) pairs
2912 if (inFields.length % 2 != 1) {
2913 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2914 'but line ' + (1 + i) + ' has an odd number of values (' +
2915 (inFields.length - 1) + "): '" + line + "'");
2917 for (j = 1; j < inFields.length; j += 2) {
2918 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2919 this.parseFloat_(inFields[j + 1], i, line)];
2921 } else if (this.attr_("customBars
")) {
2922 // Bars are a low;center;high tuple
2923 for (j = 1; j < inFields.length; j++) {
2924 var val = inFields[j];
2925 if (/^ *$/.test(val)) {
2926 fields[j] = [null, null, null];
2928 vals = val.split(";");
2929 if (vals.length == 3) {
2930 fields[j] = [ this.parseFloat_(vals[0], i, line),
2931 this.parseFloat_(vals[1], i, line),
2932 this.parseFloat_(vals[2], i, line) ];
2934 this.warn('When using customBars, values must be either blank ' +
2935 'or "low
;center
;high
" tuples (got "' + val +
2936 '" on line ' + (1+i));
2941 // Values are just numbers
2942 for (j = 1; j < inFields.length; j++) {
2943 fields[j] = this.parseFloat_(inFields[j], i, line);
2946 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2950 if (fields.length != expectedCols) {
2951 this.error("Number of columns
in line
" + i + " (" + fields.length +
2952 ") does not agree
with number of
labels (" + expectedCols +
2956 // If the user specified the 'labels' option and none of the cells of the
2957 // first row parsed correctly, then they probably double-specified the
2958 // labels. We go with the values set in the option, discard this row and
2959 // log a warning to the JS console.
2960 if (i === 0 && this.attr_('labels')) {
2961 var all_null = true;
2962 for (j = 0; all_null && j < fields.length; j++) {
2963 if (fields[j]) all_null = false;
2966 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
2967 "CSV
data ('" + line + "') appears to also contain labels
. " +
2968 "Will drop the CSV labels and
use the option labels
.");
2976 this.warn("CSV is out of order
; order it correctly to speed loading
.");
2977 ret.sort(function(a,b) { return a[0] - b[0]; });
2985 * The user has provided their data as a pre-packaged JS array. If the x values
2986 * are numeric, this is the same as dygraphs' internal format. If the x values
2987 * are dates, we need to convert them from Date objects to ms since epoch.
2988 * @param {[Object]} data
2989 * @return {[Object]} data with numeric x values.
2991 Dygraph.prototype.parseArray_ = function(data) {
2992 // Peek at the first x value to see if it's numeric.
2993 if (data.length === 0) {
2994 this.error("Can
't plot empty data set");
2997 if (data[0].length === 0) {
2998 this.error("Data set cannot contain an empty row");
3003 if (this.attr_("labels") === null) {
3004 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3005 "in the options parameter");
3006 this.attrs_.labels = [ "X" ];
3007 for (i = 1; i < data[0].length; i++) {
3008 this.attrs_.labels.push("Y" + i);
3012 if (Dygraph.isDateLike(data[0][0])) {
3013 // Some intelligent defaults for a date x-axis.
3014 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3015 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3016 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3018 // Assume they're all dates
.
3019 var parsedData
= Dygraph
.clone(data
);
3020 for (i
= 0; i
< data
.length
; i
++) {
3021 if (parsedData
[i
].length
=== 0) {
3022 this.error("Row " + (1 + i
) + " of data is empty");
3025 if (parsedData
[i
][0] === null ||
3026 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3027 isNaN(parsedData
[i
][0].getTime())) {
3028 this.error("x value in row " + (1 + i
) + " is not a Date");
3031 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3035 // Some intelligent defaults for a numeric x-axis.
3036 /** @private (shut up, jsdoc!) */
3037 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3038 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3039 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3045 * Parses a DataTable object from gviz.
3046 * The data is expected to have a first column that is either a date or a
3047 * number. All subsequent columns must be numbers. If there is a clear mismatch
3048 * between this.xValueParser_ and the type of the first column, it will be
3049 * fixed. Fills out rawData_.
3050 * @param {[Object]} data See above.
3053 Dygraph
.prototype.parseDataTable_
= function(data
) {
3054 var shortTextForAnnotationNum
= function(num
) {
3055 // converts [0-9]+ [A-Z][a-z]*
3056 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3057 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3058 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3059 num
= Math
.floor(num
/ 26);
3061 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3062 num
= Math
.floor((num
- 1) / 26);
3067 var cols
= data
.getNumberOfColumns();
3068 var rows
= data
.getNumberOfRows();
3070 var indepType
= data
.getColumnType(0);
3071 if (indepType
== 'date' || indepType
== 'datetime') {
3072 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3073 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3074 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3075 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3076 } else if (indepType
== 'number') {
3077 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3078 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3079 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3080 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3082 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3083 "column 1 of DataTable input (Got '" + indepType
+ "')");
3087 // Array of the column indices which contain data (and not annotations).
3089 var annotationCols
= {}; // data index -> [annotation cols]
3090 var hasAnnotations
= false;
3092 for (i
= 1; i
< cols
; i
++) {
3093 var type
= data
.getColumnType(i
);
3094 if (type
== 'number') {
3096 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3097 // This is OK -- it's an annotation column.
3098 var dataIdx
= colIdx
[colIdx
.length
- 1];
3099 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3100 annotationCols
[dataIdx
] = [i
];
3102 annotationCols
[dataIdx
].push(i
);
3104 hasAnnotations
= true;
3106 this.error("Only 'number' is supported as a dependent type with Gviz." +
3107 " 'string' is only supported if displayAnnotations is true");
3111 // Read column labels
3112 // TODO(danvk): add support back for errorBars
3113 var labels
= [data
.getColumnLabel(0)];
3114 for (i
= 0; i
< colIdx
.length
; i
++) {
3115 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3116 if (this.attr_("errorBars")) i
+= 1;
3118 this.attrs_
.labels
= labels
;
3119 cols
= labels
.length
;
3122 var outOfOrder
= false;
3123 var annotations
= [];
3124 for (i
= 0; i
< rows
; i
++) {
3126 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3127 data
.getValue(i
, 0) === null) {
3128 this.warn("Ignoring row " + i
+
3129 " of DataTable because of undefined or null first column.");
3133 if (indepType
== 'date' || indepType
== 'datetime') {
3134 row
.push(data
.getValue(i
, 0).getTime());
3136 row
.push(data
.getValue(i
, 0));
3138 if (!this.attr_("errorBars")) {
3139 for (j
= 0; j
< colIdx
.length
; j
++) {
3140 var col
= colIdx
[j
];
3141 row
.push(data
.getValue(i
, col
));
3142 if (hasAnnotations
&&
3143 annotationCols
.hasOwnProperty(col
) &&
3144 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3146 ann
.series
= data
.getColumnLabel(col
);
3148 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3150 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3151 if (k
) ann
.text
+= "\n";
3152 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3154 annotations
.push(ann
);
3158 // Strip out infinities, which give dygraphs problems later on.
3159 for (j
= 0; j
< row
.length
; j
++) {
3160 if (!isFinite(row
[j
])) row
[j
] = null;
3163 for (j
= 0; j
< cols
- 1; j
++) {
3164 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3167 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3174 this.warn("DataTable is out of order; order it correctly to speed loading.");
3175 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3177 this.rawData_
= ret
;
3179 if (annotations
.length
> 0) {
3180 this.setAnnotations(annotations
, true);
3185 * Get the CSV data. If it's in a function, call that function. If it's in a
3186 * file, do an XMLHttpRequest to get it.
3189 Dygraph
.prototype.start_
= function() {
3190 var data
= this.file_
;
3192 // Functions can return references of all other types.
3193 if (typeof data
== 'function') {
3197 if (Dygraph
.isArrayLike(data
)) {
3198 this.rawData_
= this.parseArray_(data
);
3200 } else if (typeof data
== 'object' &&
3201 typeof data
.getColumnRange
== 'function') {
3202 // must be a DataTable from gviz.
3203 this.parseDataTable_(data
);
3205 } else if (typeof data
== 'string') {
3206 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3207 if (data
.indexOf('\n') >= 0) {
3208 this.loadedEvent_(data
);
3210 var req
= new XMLHttpRequest();
3212 req
.onreadystatechange
= function () {
3213 if (req
.readyState
== 4) {
3214 if (req
.status
=== 200 || // Normal http
3215 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3216 caller
.loadedEvent_(req
.responseText
);
3221 req
.open("GET", data
, true);
3225 this.error("Unknown data format: " + (typeof data
));
3230 * Changes various properties of the graph. These can include:
3232 * <li>file: changes the source data for the graph</li>
3233 * <li>errorBars: changes whether the data contains stddev</li>
3236 * There's a huge variety of options that can be passed to this method. For a
3237 * full list, see http://dygraphs.com/options.html.
3239 * @param {Object} attrs The new properties and values
3240 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3241 * call to updateOptions(). If you know better, you can pass true to explicitly
3242 * block the redraw. This can be useful for chaining updateOptions() calls,
3243 * avoiding the occasional infinite loop and preventing redraws when it's not
3244 * necessary (e.g. when updating a callback).
3246 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3247 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3249 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3250 var file
= input_attrs
.file
;
3251 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3253 // TODO(danvk): this is a mess. Move these options into attr_.
3254 if ('rollPeriod' in attrs
) {
3255 this.rollPeriod_
= attrs
.rollPeriod
;
3257 if ('dateWindow' in attrs
) {
3258 this.dateWindow_
= attrs
.dateWindow
;
3259 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3260 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3263 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3264 this.zoomed_y_
= (attrs
.valueRange
!== null);
3267 // TODO(danvk): validate per-series options.
3272 // highlightCircleSize
3274 // Check if this set options will require new points.
3275 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3277 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3281 if (!block_redraw
) this.start_();
3283 if (!block_redraw
) {
3284 if (requiresNewPoints
) {
3287 this.renderGraph_(false);
3294 * Returns a copy of the options with deprecated names converted into current
3295 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3296 * interested in that, they should save a copy before calling this.
3299 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3301 for (var k
in attrs
) {
3302 if (k
== 'file') continue;
3303 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3306 var set
= function(axis
, opt
, value
) {
3307 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3308 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3309 my_attrs
.axes
[axis
][opt
] = value
;
3311 var map
= function(opt
, axis
, new_opt
) {
3312 if (typeof(attrs
[opt
]) != 'undefined') {
3313 set(axis
, new_opt
, attrs
[opt
]);
3314 delete my_attrs
[opt
];
3318 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3319 map('xValueFormatter', 'x', 'valueFormatter');
3320 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3321 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3322 map('xTicker', 'x', 'ticker');
3323 map('yValueFormatter', 'y', 'valueFormatter');
3324 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3325 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3326 map('yTicker', 'y', 'ticker');
3331 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3332 * containing div (which has presumably changed size since the dygraph was
3333 * instantiated. If the width/height are specified, the div will be resized.
3335 * This is far more efficient than destroying and re-instantiating a
3336 * Dygraph, since it doesn't have to reparse the underlying data.
3338 * @param {Number} [width] Width (in pixels)
3339 * @param {Number} [height] Height (in pixels)
3341 Dygraph
.prototype.resize
= function(width
, height
) {
3342 if (this.resize_lock
) {
3345 this.resize_lock
= true;
3347 if ((width
=== null) != (height
=== null)) {
3348 this.warn("Dygraph.resize() should be called with zero parameters or " +
3349 "two non-NULL parameters. Pretending it was zero.");
3350 width
= height
= null;
3353 var old_width
= this.width_
;
3354 var old_height
= this.height_
;
3357 this.maindiv_
.style
.width
= width
+ "px";
3358 this.maindiv_
.style
.height
= height
+ "px";
3359 this.width_
= width
;
3360 this.height_
= height
;
3362 this.width_
= this.maindiv_
.clientWidth
;
3363 this.height_
= this.maindiv_
.clientHeight
;
3366 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3367 // TODO(danvk): there should be a clear() method.
3368 this.maindiv_
.innerHTML
= "";
3369 this.roller_
= null;
3370 this.attrs_
.labelsDiv
= null;
3371 this.createInterface_();
3372 if (this.annotations_
.length
) {
3373 // createInterface_ reset the layout, so we need to do this.
3374 this.layout_
.setAnnotations(this.annotations_
);
3379 this.resize_lock
= false;
3383 * Adjusts the number of points in the rolling average. Updates the graph to
3384 * reflect the new averaging period.
3385 * @param {Number} length Number of points over which to average the data.
3387 Dygraph
.prototype.adjustRoll
= function(length
) {
3388 this.rollPeriod_
= length
;
3393 * Returns a boolean array of visibility statuses.
3395 Dygraph
.prototype.visibility
= function() {
3396 // Do lazy-initialization, so that this happens after we know the number of
3398 if (!this.attr_("visibility")) {
3399 this.attrs_
.visibility
= [];
3401 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3402 while (this.attr_("visibility").length
< this.numColumns() - 1) {
3403 this.attrs_
.visibility
.push(true);
3405 return this.attr_("visibility");
3409 * Changes the visiblity of a series.
3411 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3412 var x
= this.visibility();
3413 if (num
< 0 || num
>= x
.length
) {
3414 this.warn("invalid series number in setVisibility: " + num
);
3422 * How large of an area will the dygraph render itself in?
3423 * This is used for testing.
3424 * @return A {width: w, height: h} object.
3427 Dygraph
.prototype.size
= function() {
3428 return { width
: this.width_
, height
: this.height_
};
3432 * Update the list of annotations and redraw the chart.
3433 * See dygraphs.com/annotations.html for more info on how to use annotations.
3434 * @param ann {Array} An array of annotation objects.
3435 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3437 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3438 // Only add the annotation CSS rule once we know it will be used.
3439 Dygraph
.addAnnotationRule();
3440 this.annotations_
= ann
;
3441 this.layout_
.setAnnotations(this.annotations_
);
3442 if (!suppressDraw
) {
3448 * Return the list of annotations.
3450 Dygraph
.prototype.annotations
= function() {
3451 return this.annotations_
;
3455 * Get the list of label names for this graph. The first column is the
3456 * x-axis, so the data series names start at index 1.
3458 Dygraph
.prototype.getLabels
= function() {
3459 return this.attr_("labels").slice();
3463 * Get the index of a series (column) given its name. The first column is the
3464 * x-axis, so the data series start with index 1.
3466 Dygraph
.prototype.indexFromSetName
= function(name
) {
3467 return this.setIndexByName_
[name
];
3471 * Get the internal dataset index given its name. These are numbered starting from 0,
3472 * and only count visible sets.
3475 Dygraph
.prototype.datasetIndexFromSetName_
= function(name
) {
3476 return this.datasetIndex_
[this.indexFromSetName(name
)];
3481 * Adds a default style for the annotation CSS classes to the document. This is
3482 * only executed when annotations are actually used. It is designed to only be
3483 * called once -- all calls after the first will return immediately.
3485 Dygraph
.addAnnotationRule
= function() {
3486 if (Dygraph
.addedAnnotationCSS
) return;
3488 var rule
= "border: 1px solid black; " +
3489 "background-color: white; " +
3490 "text-align: center;";
3492 var styleSheetElement
= document
.createElement("style");
3493 styleSheetElement
.type
= "text/css";
3494 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3496 // Find the first style sheet that we can access.
3497 // We may not add a rule to a style sheet from another domain for security
3498 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3499 // adds its own style sheets from google.com.
3500 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3501 if (document
.styleSheets
[i
].disabled
) continue;
3502 var mysheet
= document
.styleSheets
[i
];
3504 if (mysheet
.insertRule
) { // Firefox
3505 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3506 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3507 } else if (mysheet
.addRule
) { // IE
3508 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3510 Dygraph
.addedAnnotationCSS
= true;
3513 // Was likely a security exception.
3517 this.warn("Unable to add default annotation CSS rule; display may be off.");
3520 // Older pages may still use this name.
3521 var DateGraph
= Dygraph
;