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 DygraphLayout:false, DygraphCanvasRenderer:false, DygraphOptions: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 // For max 60 Hz. animation:
95 Dygraph
.ANIMATION_STEPS
= 12;
96 Dygraph
.ANIMATION_DURATION
= 200;
98 Dygraph
.KMB_LABELS
= [ 'K', 'M', 'B', 'T', 'Q' ];
99 Dygraph
.KMG2_BIG_LABELS
= [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
100 Dygraph
.KMG2_SMALL_LABELS
= [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
102 // These are defined before DEFAULT_ATTRS so that it can refer to them.
105 * Return a string version of a number. This respects the digitsAfterDecimal
106 * and maxNumberWidth options.
107 * @param {Number} x The number to be formatted
108 * @param {Dygraph} opts An options view
109 * @param {String} name The name of the point's data series
110 * @param {Dygraph} g The dygraph object
112 Dygraph
.numberValueFormatter
= function(x
, opts
, pt
, g
) {
113 var sigFigs
= opts('sigFigs');
115 if (sigFigs
!== null) {
116 // User has opted for a fixed number of significant figures.
117 return Dygraph
.floatFormat(x
, sigFigs
);
120 var digits
= opts('digitsAfterDecimal');
121 var maxNumberWidth
= opts('maxNumberWidth');
123 var kmb
= opts('labelsKMB');
124 var kmg2
= opts('labelsKMG2');
128 // switch to scientific notation if we underflow or overflow fixed display.
130 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
131 Math
.abs(x
) < Math
.pow(10, -digits
))) {
132 label
= x
.toExponential(digits
);
134 label
= '' + Dygraph
.round_(x
, digits
);
143 k_labels
= [ "K", "M", "B", "T", "Q" ];
146 if (kmb
) Dygraph
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
148 k_labels
= [ "k", "M", "G", "T", "P", "E", "Z", "Y" ];
149 m_labels
= [ "m", "u", "n", "p", "f", "a", "z", "y" ];
152 var absx
= Math
.abs(x
);
153 var n
= Dygraph
.pow(k
, k_labels
.length
);
154 for (var j
= k_labels
.length
- 1; j
>= 0; j
--, n
/= k
) {
156 label
= Dygraph
.round_(x
/ n
, digits
) + k_labels
[j
];
161 // TODO(danvk): clean up this logic. Why so different than kmb?
162 var x_parts
= String(x
.toExponential()).split('e-');
163 if (x_parts
.length
=== 2 && x_parts
[1] >= 3 && x_parts
[1] <= 24) {
164 if (x_parts
[1] % 3 > 0) {
165 label
= Dygraph
.round_(x_parts
[0] /
166 Dygraph
.pow(10, (x_parts
[1] % 3)),
169 label
= Number(x_parts
[0]).toFixed(2);
171 label
+= m_labels
[Math
.floor(x_parts
[1] / 3) - 1];
180 * variant for use as an axisLabelFormatter.
183 Dygraph
.numberAxisLabelFormatter
= function(x
, granularity
, opts
, g
) {
184 return Dygraph
.numberValueFormatter(x
, opts
, g
);
188 * Convert a JS date (millis since epoch) to YYYY/MM/DD
189 * @param {Number} date The JavaScript date (ms since epoch)
190 * @return {String} A date of the form "YYYY/MM/DD"
193 Dygraph
.dateString_
= function(date
) {
194 var zeropad
= Dygraph
.zeropad
;
195 var d
= new Date(date
);
198 var year
= "" + d
.getFullYear();
199 // Get a 0 padded month string
200 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
201 // Get a 0 padded day string
202 var day
= zeropad(d
.getDate());
205 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
206 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
208 return year
+ "/" + month + "/" + day
+ ret
;
212 * Convert a JS date to a string appropriate to display on an axis that
213 * is displaying values at the stated granularity.
214 * @param {Date} date The date to format
215 * @param {Number} granularity One of the Dygraph granularity constants
216 * @return {String} The formatted date
219 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
220 if (granularity
>= Dygraph
.DECADAL
) {
221 return date
.strftime('%Y');
222 } else if (granularity
>= Dygraph
.MONTHLY
) {
223 return date
.strftime('%b %y');
225 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
226 if (frac
=== 0 || granularity
>= Dygraph
.DAILY
) {
227 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
229 return Dygraph
.hmsString_(date
.getTime());
235 * Standard plotters. These may be used by clients.
236 * Available plotters are:
237 * - Dygraph.Plotters.linePlotter: draws central lines (most common)
238 * - Dygraph.Plotters.errorPlotter: draws error bars
239 * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph)
241 * By default, the plotter is [fillPlotter, errorPlotter, linePlotter].
242 * This causes all the lines to be drawn over all the fills/error bars.
244 Dygraph
.Plotters
= DygraphCanvasRenderer
._Plotters
;
247 // Default attribute values.
248 Dygraph
.DEFAULT_ATTRS
= {
249 highlightCircleSize
: 3,
250 highlightSeriesOpts
: null,
251 highlightSeriesBackgroundAlpha
: 0.5,
255 // TODO(danvk): move defaults from createStatusMessage_ here.
257 labelsSeparateLines
: false,
258 labelsShowZeroValues
: true,
261 showLabelsOnHighlight
: true,
263 digitsAfterDecimal
: 2,
268 strokeBorderWidth
: 0,
269 strokeBorderColor
: "white",
272 axisLabelFontSize
: 14,
278 xValueParser
: Dygraph
.dateParser
,
285 wilsonInterval
: true, // only relevant if fractions is true
289 connectSeparatedPoints
: false,
292 hideOverlayOnMouseOut
: true,
294 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
295 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
301 drawAxesAtZero
: false,
303 // Sizes of the various chart labels.
310 axisLineColor
: "black",
313 axisLabelColor
: "black",
314 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
318 gridLineColor
: "rgb(128,128,128)",
320 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
321 animatedZooms
: false, // (for now)
323 // Range selector options
324 showRangeSelector
: false,
325 rangeSelectorHeight
: 40,
326 rangeSelectorPlotStrokeColor
: "#808FAB",
327 rangeSelectorPlotFillColor
: "#A7B1C4",
329 // The ordering here ensures that central lines always appear above any
330 // fill bars/error bars
.
332 Dygraph
.Plotters
.fillPlotter
,
333 Dygraph
.Plotters
.errorPlotter
,
334 Dygraph
.Plotters
.linePlotter
343 axisLabelFormatter
: Dygraph
.dateAxisFormatter
,
344 valueFormatter
: Dygraph
.dateString_
,
345 ticker
: null // will be set in dygraph-tickers.js
349 valueFormatter
: Dygraph
.numberValueFormatter
,
350 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
351 ticker
: null // will be set in dygraph-tickers.js
355 valueFormatter
: Dygraph
.numberValueFormatter
,
356 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
357 ticker
: null // will be set in dygraph-tickers.js
362 // Directions for panning and zooming. Use bit operations when combined
363 // values are possible.
364 Dygraph
.HORIZONTAL
= 1;
365 Dygraph
.VERTICAL
= 2;
367 // Installed plugins, in order of precedence (most-general to most-specific).
368 // Plugins are installed after they are defined, in plugins/install.js
.
372 // Used for initializing annotation CSS rules only once.
373 Dygraph
.addedAnnotationCSS
= false;
375 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
376 // Labels is no longer a constructor parameter, since it's typically set
377 // directly from the data source. It also conains a name for the x-axis,
378 // which the previous constructor form did not.
379 if (labels
!== null) {
380 var new_labels
= ["Date"];
381 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
382 Dygraph
.update(attrs
, { 'labels': new_labels
});
384 this.__init__(div
, file
, attrs
);
388 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
389 * and context <canvas> inside of it. See the constructor for details.
391 * @param {Element} div the Element to render the graph into.
392 * @param {String | Function} file Source data
393 * @param {Object} attrs Miscellaneous other options
396 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
397 // Hack for IE: if we're using excanvas and the document hasn't finished
398 // loading yet (and hence may not have initialized whatever it needs to
399 // initialize), then keep calling this routine periodically until it has.
400 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
401 typeof(G_vmlCanvasManager
) != 'undefined' &&
402 document
.readyState
!= 'complete') {
404 setTimeout(function() { self
.__init__(div
, file
, attrs
); }, 100);
408 // Support two-argument constructor
409 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
411 attrs
= Dygraph
.mapLegacyOptions_(attrs
);
413 if (typeof(div
) == 'string') {
414 div
= document
.getElementById(div
);
418 Dygraph
.error("Constructing dygraph with a non-existent div!");
422 this.isUsingExcanvas_
= typeof(G_vmlCanvasManager
) != 'undefined';
424 // Copy the important bits into the object
425 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
428 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
429 this.previousVerticalX_
= -1;
430 this.fractions_
= attrs
.fractions
|| false;
431 this.dateWindow_
= attrs
.dateWindow
|| null;
433 this.is_initial_draw_
= true;
434 this.annotations_
= [];
436 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
437 this.zoomed_x_
= false;
438 this.zoomed_y_
= false;
440 // Clear the div. This ensure that, if multiple dygraphs are passed the same
441 // div, then only one will be drawn.
444 // For historical reasons, the 'width' and 'height' options trump all CSS
445 // rules _except_ for an explicit 'width' or 'height' on the div.
446 // As an added convenience, if the div has zero height (like <div></div> does
447 // without any styles), then we use a default height/width
.
448 if (div
.style
.width
=== '' && attrs
.width
) {
449 div
.style
.width
= attrs
.width
+ "px";
451 if (div
.style
.height
=== '' && attrs
.height
) {
452 div
.style
.height
= attrs
.height
+ "px";
454 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
455 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
456 if (div
.style
.width
=== '') {
457 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
460 // these will be zero if the dygraph's div is hidden.
461 this.width_
= div
.clientWidth
;
462 this.height_
= div
.clientHeight
;
464 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
465 if (attrs
.stackedGraph
) {
466 attrs
.fillGraph
= true;
467 // TODO(nikhilk): Add any other stackedGraph checks here.
470 // DEPRECATION WARNING: All option processing should be moved from
471 // attrs_ and user_attrs_ to options_, which holds all this information.
473 // Dygraphs has many options, some of which interact with one another.
474 // To keep track of everything, we maintain two sets of options:
476 // this.user_attrs_ only options explicitly set by the user.
477 // this.attrs_ defaults, options derived from user_attrs_, data.
479 // Options are then accessed this.attr_('attr'), which first looks at
480 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
481 // defaults without overriding behavior that the user specifically asks for.
482 this.user_attrs_
= {};
483 Dygraph
.update(this.user_attrs_
, attrs
);
485 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
487 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
489 this.boundaryIds_
= [];
490 this.setIndexByName_
= {};
491 this.datasetIndex_
= [];
493 this.registeredEvents_
= [];
494 this.eventListeners_
= {};
496 this.attributes_
= new DygraphOptions(this);
498 // Create the containing DIV and other interactive elements
499 this.createInterface_();
503 var plugins
= Dygraph
.PLUGINS
.concat(this.getOption('plugins'));
504 for (var i
= 0; i
< plugins
.length
; i
++) {
505 var Plugin
= plugins
[i
];
506 var pluginInstance
= new Plugin();
508 plugin
: pluginInstance
,
514 var handlers
= pluginInstance
.activate(this);
515 for (var eventName
in handlers
) {
516 // TODO(danvk): validate eventName.
517 pluginDict
.events
[eventName
] = handlers
[eventName
];
520 this.plugins_
.push(pluginDict
);
523 // At this point, plugins can no longer register event handlers.
524 // Construct a map from event -> ordered list of [callback, plugin].
525 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
526 var plugin_dict
= this.plugins_
[i
];
527 for (var eventName
in plugin_dict
.events
) {
528 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
529 var callback
= plugin_dict
.events
[eventName
];
531 var pair
= [plugin_dict
.plugin
, callback
];
532 if (!(eventName
in this.eventListeners_
)) {
533 this.eventListeners_
[eventName
] = [pair
];
535 this.eventListeners_
[eventName
].push(pair
);
540 this.createDragInterface_();
546 * Triggers a cascade of events to the various plugins which are interested in them.
547 * Returns true if the "default behavior" should be performed, i.e. if none of
548 * the event listeners called event.preventDefault().
551 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
552 if (!(name
in this.eventListeners_
)) return true;
554 // QUESTION: can we use objects & prototypes to speed this up?
558 defaultPrevented
: false,
559 preventDefault
: function() {
560 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
561 e
.defaultPrevented
= true;
563 propagationStopped
: false,
564 stopPropagation
: function() {
565 e
.propagationStopped
= true;
568 Dygraph
.update(e
, extra_props
);
570 var callback_plugin_pairs
= this.eventListeners_
[name
];
571 if (callback_plugin_pairs
) {
572 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
573 var plugin
= callback_plugin_pairs
[i
][0];
574 var callback
= callback_plugin_pairs
[i
][1];
575 callback
.call(plugin
, e
);
576 if (e
.propagationStopped
) break;
579 return e
.defaultPrevented
;
583 * Returns the zoomed status of the chart for one or both axes.
585 * Axis is an optional parameter. Can be set to 'x' or 'y'.
587 * The zoomed status for an axis is set whenever a user zooms using the mouse
588 * or when the dateWindow or valueRange are updated (unless the
589 * isZoomedIgnoreProgrammaticZoom option is also specified).
591 Dygraph
.prototype.isZoomed
= function(axis
) {
592 if (axis
=== null || axis
=== undefined
) {
593 return this.zoomed_x_
|| this.zoomed_y_
;
595 if (axis
=== 'x') return this.zoomed_x_
;
596 if (axis
=== 'y') return this.zoomed_y_
;
597 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
601 * Returns information about the Dygraph object, including its containing ID.
603 Dygraph
.prototype.toString
= function() {
604 var maindiv
= this.maindiv_
;
605 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
606 return "[Dygraph " + id
+ "]";
611 * Returns the value of an option. This may be set by the user (either in the
612 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
614 * @param { String } name The name of the option, e.g. 'rollPeriod'.
615 * @param { String } [seriesName] The name of the series to which the option
616 * will be applied. If no per-series value of this option is available, then
617 * the global value is returned. This is optional.
618 * @return { ... } The value of the option.
620 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
621 // <REMOVE_FOR_COMBINED>
622 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
623 this.error('Must include options reference JS for testing');
624 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
625 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
626 'in the Dygraphs.OPTIONS_REFERENCE listing.');
627 // Only log this error once.
628 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
630 // </REMOVE_FOR_COMBINED
>
631 return seriesName
? this.attributes_
.getForSeries(name
, seriesName
) : this.attributes_
.get(name
);
635 * Returns the current value for an option, as set in the constructor or via
636 * updateOptions. You may pass in an (optional) series name to get per-series
637 * values for the option.
639 * All values returned by this method should be considered immutable. If you
640 * modify them, there is no guarantee that the changes will be honored or that
641 * dygraphs will remain in a consistent state. If you want to modify an option,
642 * use updateOptions() instead.
644 * @param { String } name The name of the option (e.g. 'strokeWidth')
645 * @param { String } [opt_seriesName] Series name to get per-series values.
646 * @return { ... } The value of the option.
648 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
649 return this.attr_(name
, opt_seriesName
);
652 Dygraph
.prototype.getOptionForAxis
= function(name
, axis
) {
653 return this.attributes_
.getForAxis(name
, axis
);
658 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
659 * @return { ... } A function mapping string -> option value
661 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
663 return function(opt
) {
664 var axis_opts
= self
.user_attrs_
.axes
;
665 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
666 return axis_opts
[axis
][opt
];
668 // user-specified attributes always trump defaults, even if they're less
670 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
671 return self
.user_attrs_
[opt
];
674 axis_opts
= self
.attrs_
.axes
;
675 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
676 return axis_opts
[axis
][opt
];
678 // check old-style axis options
679 // TODO(danvk): add a deprecation warning if either of these match.
680 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
681 return self
.axes_
[0][opt
];
682 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
683 return self
.axes_
[1][opt
];
685 return self
.attr_(opt
);
690 * Returns the current rolling period, as set by the user or an option.
691 * @return {Number} The number of points in the rolling window
693 Dygraph
.prototype.rollPeriod
= function() {
694 return this.rollPeriod_
;
698 * Returns the currently-visible x-range. This can be affected by zooming,
699 * panning or a call to updateOptions.
700 * Returns a two-element array: [left, right].
701 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
703 Dygraph
.prototype.xAxisRange
= function() {
704 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
708 * Returns the lower- and upper-bound x-axis values of the
711 Dygraph
.prototype.xAxisExtremes
= function() {
712 var pad
= this.attr_('xRangePad') / this.plotter_
.area
.w
;
713 if (this.numRows() === 0) {
714 return [0 - pad
, 1 + pad
];
716 var left
= this.rawData_
[0][0];
717 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
719 // Must keep this in sync with dygraph-layout _evaluateLimits()
720 var range
= right
- left
;
722 right
+= range
* pad
;
724 return [left
, right
];
728 * Returns the currently-visible y-range for an axis. This can be affected by
729 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
730 * called with no arguments, returns the range of the first axis.
731 * Returns a two-element array: [bottom, top].
733 Dygraph
.prototype.yAxisRange
= function(idx
) {
734 if (typeof(idx
) == "undefined") idx
= 0;
735 if (idx
< 0 || idx
>= this.axes_
.length
) {
738 var axis
= this.axes_
[idx
];
739 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
743 * Returns the currently-visible y-ranges for each axis. This can be affected by
744 * zooming, panning, calls to updateOptions, etc.
745 * Returns an array of [bottom, top] pairs, one for each y-axis.
747 Dygraph
.prototype.yAxisRanges
= function() {
749 for (var i
= 0; i
< this.axes_
.length
; i
++) {
750 ret
.push(this.yAxisRange(i
));
755 // TODO(danvk): use these functions throughout dygraphs.
757 * Convert from data coordinates to canvas/div X/Y coordinates.
758 * If specified, do this conversion for the coordinate system of a particular
759 * axis. Uses the first axis by default.
760 * Returns a two-element array: [X, Y]
762 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
763 * instead of toDomCoords(null, y, axis).
765 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
766 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
770 * Convert from data x coordinates to canvas/div X coordinate.
771 * If specified, do this conversion for the coordinate system of a particular
773 * Returns a single value or null if x is null.
775 Dygraph
.prototype.toDomXCoord
= function(x
) {
780 var area
= this.plotter_
.area
;
781 var xRange
= this.xAxisRange();
782 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
786 * Convert from data x coordinates to canvas/div Y coordinate and optional
787 * axis. Uses the first axis by default.
789 * returns a single value or null if y is null.
791 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
792 var pct
= this.toPercentYCoord(y
, axis
);
797 var area
= this.plotter_
.area
;
798 return area
.y
+ pct
* area
.h
;
802 * Convert from canvas/div coords to data coordinates.
803 * If specified, do this conversion for the coordinate system of a particular
804 * axis. Uses the first axis by default.
805 * Returns a two-element array: [X, Y].
807 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
808 * instead of toDataCoords(null, y, axis).
810 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
811 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
815 * Convert from canvas/div x coordinate to data coordinate.
817 * If x is null, this returns null.
819 Dygraph
.prototype.toDataXCoord
= function(x
) {
824 var area
= this.plotter_
.area
;
825 var xRange
= this.xAxisRange();
826 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
830 * Convert from canvas/div y coord to value.
832 * If y is null, this returns null.
833 * if axis is null, this uses the first axis.
835 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
840 var area
= this.plotter_
.area
;
841 var yRange
= this.yAxisRange(axis
);
843 if (typeof(axis
) == "undefined") axis
= 0;
844 if (!this.axes_
[axis
].logscale
) {
845 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
847 // Computing the inverse of toDomCoord.
848 var pct
= (y
- area
.y
) / area
.h
;
850 // Computing the inverse of toPercentYCoord. The function was arrived at with
851 // the following steps:
853 // Original calcuation:
854 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
856 // Move denominator to both sides:
857 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
859 // subtract logr1, and take the negative value.
860 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
862 // Swap both sides of the equation, and we can compute the log of the
863 // return value. Which means we just need to use that as the exponent in
865 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
867 var logr1
= Dygraph
.log10(yRange
[1]);
868 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
869 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
875 * Converts a y for an axis to a percentage from the top to the
876 * bottom of the drawing area.
878 * If the coordinate represents a value visible on the canvas, then
879 * the value will be between 0 and 1, where 0 is the top of the canvas.
880 * However, this method will return values outside the range, as
881 * values can fall outside the canvas.
883 * If y is null, this returns null.
884 * if axis is null, this uses the first axis.
886 * @param { Number } y The data y-coordinate.
887 * @param { Number } [axis] The axis number on which the data coordinate lives.
888 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
890 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
894 if (typeof(axis
) == "undefined") axis
= 0;
896 var yRange
= this.yAxisRange(axis
);
899 var logscale
= this.attributes_
.getForAxis("logscale", axis
);
901 // yRange[1] - y is unit distance from the bottom.
902 // yRange[1] - yRange[0] is the scale of the range.
903 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
904 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
906 var logr1
= Dygraph
.log10(yRange
[1]);
907 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
913 * Converts an x value to a percentage from the left to the right of
916 * If the coordinate represents a value visible on the canvas, then
917 * the value will be between 0 and 1, where 0 is the left of the canvas.
918 * However, this method will return values outside the range, as
919 * values can fall outside the canvas.
921 * If x is null, this returns null.
922 * @param { Number } x The data x-coordinate.
923 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
925 Dygraph
.prototype.toPercentXCoord
= function(x
) {
930 var xRange
= this.xAxisRange();
931 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
935 * Returns the number of columns (including the independent variable).
936 * @return { Integer } The number of columns.
938 Dygraph
.prototype.numColumns
= function() {
939 if (!this.rawData_
) return 0;
940 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
944 * Returns the number of rows (excluding any header/label row).
945 * @return { Integer } The number of rows, less any header.
947 Dygraph
.prototype.numRows
= function() {
948 if (!this.rawData_
) return 0;
949 return this.rawData_
.length
;
953 * Returns the value in the given row and column. If the row and column exceed
954 * the bounds on the data, returns null. Also returns null if the value is
956 * @param { Number} row The row number of the data (0-based). Row 0 is the
957 * first row of data, not a header row.
958 * @param { Number} col The column number of the data (0-based)
959 * @return { Number } The value in the specified cell or null if the row/col
962 Dygraph
.prototype.getValue
= function(row
, col
) {
963 if (row
< 0 || row
> this.rawData_
.length
) return null;
964 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
966 return this.rawData_
[row
][col
];
970 * Generates interface elements for the Dygraph: a containing div, a div to
971 * display the current point, and a textbox to adjust the rolling average
972 * period. Also creates the Renderer/Layout elements.
975 Dygraph
.prototype.createInterface_
= function() {
976 // Create the all-enclosing graph div
977 var enclosing
= this.maindiv_
;
979 this.graphDiv
= document
.createElement("div");
980 this.graphDiv
.style
.width
= this.width_
+ "px";
981 this.graphDiv
.style
.height
= this.height_
+ "px";
982 // TODO(danvk): any other styles that are useful to set here?
983 this.graphDiv
.style
.textAlign
= 'left'; // This is a CSS "reset"
984 enclosing
.appendChild(this.graphDiv
);
986 // Create the canvas for interactive parts of the chart.
987 this.canvas_
= Dygraph
.createCanvas();
988 this.canvas_
.style
.position
= "absolute";
989 this.canvas_
.width
= this.width_
;
990 this.canvas_
.height
= this.height_
;
991 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
992 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
994 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
996 // ... and for static parts of the chart.
997 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
998 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
1000 // The interactive parts of the graph are drawn on top of the chart.
1001 this.graphDiv
.appendChild(this.hidden_
);
1002 this.graphDiv
.appendChild(this.canvas_
);
1003 this.mouseEventElement_
= this.createMouseEventElement_();
1005 // Create the grapher
1006 this.layout_
= new DygraphLayout(this);
1010 this.mouseMoveHandler_
= function(e
) {
1011 dygraph
.mouseMove_(e
);
1014 this.mouseOutHandler_
= function(e
) {
1015 // The mouse has left the chart if:
1016 // 1. e.target is inside the chart
1017 // 2. e.relatedTarget is outside the chart
1018 var target
= e
.target
|| e
.fromElement
;
1019 var relatedTarget
= e
.relatedTarget
|| e
.toElement
;
1020 if (Dygraph
.isElementContainedBy(target
, dygraph
.graphDiv
) &&
1021 !Dygraph
.isElementContainedBy(relatedTarget
, dygraph
.graphDiv
)) {
1022 dygraph
.mouseOut_(e
);
1026 this.addEvent(window
, 'mouseout', this.mouseOutHandler_
);
1027 this.addEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1029 // Don't recreate and register the resize handler on subsequent calls.
1030 // This happens when the graph is resized.
1031 if (!this.resizeHandler_
) {
1032 this.resizeHandler_
= function(e
) {
1036 // Update when the window is resized.
1037 // TODO(danvk): drop frames depending on complexity of the chart.
1038 this.addEvent(window
, 'resize', this.resizeHandler_
);
1043 * Detach DOM elements in the dygraph and null out all data references.
1044 * Calling this when you're done with a dygraph can dramatically reduce memory
1045 * usage. See, e.g., the tests/perf.html example.
1047 Dygraph
.prototype.destroy
= function() {
1048 var removeRecursive
= function(node
) {
1049 while (node
.hasChildNodes()) {
1050 removeRecursive(node
.firstChild
);
1051 node
.removeChild(node
.firstChild
);
1055 if (this.registeredEvents_
) {
1056 for (var idx
= 0; idx
< this.registeredEvents_
.length
; idx
++) {
1057 var reg
= this.registeredEvents_
[idx
];
1058 Dygraph
.removeEvent(reg
.elem
, reg
.type
, reg
.fn
);
1062 this.registeredEvents_
= [];
1064 // remove mouse event handlers (This may not be necessary anymore)
1065 Dygraph
.removeEvent(window
, 'mouseout', this.mouseOutHandler_
);
1066 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1067 Dygraph
.removeEvent(this.mouseEventElement_
, 'mouseup', this.mouseUpHandler_
);
1069 // remove window handlers
1070 Dygraph
.removeEvent(window
,'resize',this.resizeHandler_
);
1071 this.resizeHandler_
= null;
1073 removeRecursive(this.maindiv_
);
1075 var nullOut
= function(obj
) {
1076 for (var n
in obj
) {
1077 if (typeof(obj
[n
]) === 'object') {
1082 // These may not all be necessary, but it can't hurt...
1083 nullOut(this.layout_
);
1084 nullOut(this.plotter_
);
1089 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1090 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1091 * or the zoom rectangles) is done on this.canvas_.
1092 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1093 * @return {Object} The newly-created canvas
1096 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1097 var h
= Dygraph
.createCanvas();
1098 h
.style
.position
= "absolute";
1099 // TODO(danvk): h should be offset from canvas. canvas needs to include
1100 // some extra area to make it easier to zoom in on the far left and far
1101 // right. h needs to be precisely the plot area, so that clipping occurs.
1102 h
.style
.top
= canvas
.style
.top
;
1103 h
.style
.left
= canvas
.style
.left
;
1104 h
.width
= this.width_
;
1105 h
.height
= this.height_
;
1106 h
.style
.width
= this.width_
+ "px"; // for IE
1107 h
.style
.height
= this.height_
+ "px"; // for IE
1112 * Creates an overlay element used to handle mouse events.
1113 * @return {Object} The mouse event element.
1116 Dygraph
.prototype.createMouseEventElement_
= function() {
1117 if (this.isUsingExcanvas_
) {
1118 var elem
= document
.createElement("div");
1119 elem
.style
.position
= 'absolute';
1120 elem
.style
.backgroundColor
= 'white';
1121 elem
.style
.filter
= 'alpha(opacity=0)';
1122 elem
.style
.width
= this.width_
+ "px";
1123 elem
.style
.height
= this.height_
+ "px";
1124 this.graphDiv
.appendChild(elem
);
1127 return this.canvas_
;
1132 * Generate a set of distinct colors for the data series. This is done with a
1133 * color wheel. Saturation/Value are customizable, and the hue is
1134 * equally-spaced around the color wheel. If a custom set of colors is
1135 * specified, that is used instead.
1138 Dygraph
.prototype.setColors_
= function() {
1139 var labels
= this.getLabels();
1140 var num
= labels
.length
- 1;
1142 this.colorsMap_
= {};
1143 var colors
= this.attr_('colors');
1146 var sat
= this.attr_('colorSaturation') || 1.0;
1147 var val
= this.attr_('colorValue') || 0.5;
1148 var half
= Math
.ceil(num
/ 2);
1149 for (i
= 1; i
<= num
; i
++) {
1150 if (!this.visibility()[i
-1]) continue;
1151 // alternate colors for high contrast.
1152 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
1153 var hue
= (1.0 * idx
/ (1 + num
));
1154 var colorStr
= Dygraph
.hsvToRGB(hue
, sat
, val
);
1155 this.colors_
.push(colorStr
);
1156 this.colorsMap_
[labels
[i
]] = colorStr
;
1159 for (i
= 0; i
< num
; i
++) {
1160 if (!this.visibility()[i
]) continue;
1161 var colorStr
= colors
[i
% colors
.length
];
1162 this.colors_
.push(colorStr
);
1163 this.colorsMap_
[labels
[1 + i
]] = colorStr
;
1169 * Return the list of colors. This is either the list of colors passed in the
1170 * attributes or the autogenerated list of rgb(r,g,b) strings.
1171 * This does not return colors for invisible series.
1172 * @return {Array<string>} The list of colors.
1174 Dygraph
.prototype.getColors
= function() {
1175 return this.colors_
;
1179 * Returns a few attributes of a series, i.e. its color, its visibility, which
1180 * axis it's assigned to, and its column in the original data.
1181 * Returns null if the series does not exist.
1182 * Otherwise, returns an object with column, visibility, color and axis properties.
1183 * The "axis" property will be set to 1 for y1 and 2 for y2.
1184 * The "column" property can be fed back into getValue(row, column) to get
1185 * values for this series.
1187 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1189 var labels
= this.getLabels();
1190 for (var i
= 1; i
< labels
.length
; i
++) {
1191 if (labels
[i
] == series_name
) {
1196 if (idx
== -1) return null;
1201 visible
: this.visibility()[idx
- 1],
1202 color
: this.colorsMap_
[series_name
],
1203 axis
: 1 + this.attributes_
.axisForSeries(series_name
)
1208 * Create the text box to adjust the averaging period
1211 Dygraph
.prototype.createRollInterface_
= function() {
1212 // Create a roller if one doesn't exist already.
1213 if (!this.roller_
) {
1214 this.roller_
= document
.createElement("input");
1215 this.roller_
.type
= "text";
1216 this.roller_
.style
.display
= "none";
1217 this.graphDiv
.appendChild(this.roller_
);
1220 var display
= this.attr_('showRoller') ? 'block' : 'none';
1222 var area
= this.plotter_
.area
;
1223 var textAttr
= { "position": "absolute",
1225 "top": (area
.y
+ area
.h
- 25) + "px",
1226 "left": (area
.x
+ 1) + "px",
1229 this.roller_
.size
= "2";
1230 this.roller_
.value
= this.rollPeriod_
;
1231 for (var name
in textAttr
) {
1232 if (textAttr
.hasOwnProperty(name
)) {
1233 this.roller_
.style
[name
] = textAttr
[name
];
1238 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1243 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1244 * canvas (i.e. DOM Coords).
1246 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1247 return Dygraph
.pageX(e
) - context
.px
;
1252 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1253 * canvas (i.e. DOM Coords).
1255 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1256 return Dygraph
.pageY(e
) - context
.py
;
1260 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1264 Dygraph
.prototype.createDragInterface_
= function() {
1266 // Tracks whether the mouse is down right now
1268 isPanning
: false, // is this drag part of a pan?
1269 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1270 dragStartX
: null, // pixel coordinates
1271 dragStartY
: null, // pixel coordinates
1272 dragEndX
: null, // pixel coordinates
1273 dragEndY
: null, // pixel coordinates
1274 dragDirection
: null,
1275 prevEndX
: null, // pixel coordinates
1276 prevEndY
: null, // pixel coordinates
1277 prevDragDirection
: null,
1278 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1280 // The value on the left side of the graph when a pan operation starts.
1281 initialLeftmostDate
: null,
1283 // The number of units each pixel spans. (This won't be valid for log
1285 xUnitsPerPixel
: null,
1287 // TODO(danvk): update this comment
1288 // The range in second/value units that the viewport encompasses during a
1289 // panning operation.
1292 // Top-left corner of the canvas, in DOM coords
1293 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1297 // Values for use with panEdgeFraction, which limit how far outside the
1298 // graph's data boundaries it can be panned.
1299 boundedDates
: null, // [minDate, maxDate]
1300 boundedValues
: null, // [[minValue, maxValue] ...]
1302 // We cover iframes during mouse interactions. See comments in
1303 // dygraph-utils.js for more info on why this is a good idea.
1304 tarp
: new Dygraph
.IFrameTarp(),
1306 // contextB is the same thing as this context object but renamed.
1307 initializeMouseDown
: function(event
, g
, contextB
) {
1308 // prevents mouse drags from selecting page text.
1309 if (event
.preventDefault
) {
1310 event
.preventDefault(); // Firefox, Chrome, etc.
1312 event
.returnValue
= false; // IE
1313 event
.cancelBubble
= true;
1316 contextB
.px
= Dygraph
.findPosX(g
.canvas_
);
1317 contextB
.py
= Dygraph
.findPosY(g
.canvas_
);
1318 contextB
.dragStartX
= g
.dragGetX_(event
, contextB
);
1319 contextB
.dragStartY
= g
.dragGetY_(event
, contextB
);
1320 contextB
.cancelNextDblclick
= false;
1321 contextB
.tarp
.cover();
1325 var interactionModel
= this.attr_("interactionModel");
1327 // Self is the graph.
1330 // Function that binds the graph and context to the handler.
1331 var bindHandler
= function(handler
) {
1332 return function(event
) {
1333 handler(event
, self
, context
);
1337 for (var eventName
in interactionModel
) {
1338 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1339 this.addEvent(this.mouseEventElement_
, eventName
,
1340 bindHandler(interactionModel
[eventName
]));
1343 // unregister the handler on subsequent calls.
1344 // This happens when the graph is resized.
1345 if (this.mouseUpHandler_
) {
1346 Dygraph
.removeEvent(document
, 'mouseup', this.mouseUpHandler_
);
1349 // If the user releases the mouse button during a drag, but not over the
1350 // canvas, then it doesn't count as a zooming action.
1351 this.mouseUpHandler_
= function(event
) {
1352 if (context
.isZooming
|| context
.isPanning
) {
1353 context
.isZooming
= false;
1354 context
.dragStartX
= null;
1355 context
.dragStartY
= null;
1358 if (context
.isPanning
) {
1359 context
.isPanning
= false;
1360 context
.draggingDate
= null;
1361 context
.dateRange
= null;
1362 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1363 delete self
.axes_
[i
].draggingValue
;
1364 delete self
.axes_
[i
].dragValueRange
;
1368 context
.tarp
.uncover();
1371 this.addEvent(document
, 'mouseup', this.mouseUpHandler_
);
1375 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1376 * up any previous zoom rectangles that were drawn. This could be optimized to
1377 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1380 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1381 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1382 * @param {Number} startX The X position where the drag started, in canvas
1384 * @param {Number} endX The current X position of the drag, in canvas coords.
1385 * @param {Number} startY The Y position where the drag started, in canvas
1387 * @param {Number} endY The current Y position of the drag, in canvas coords.
1388 * @param {Number} prevDirection the value of direction on the previous call to
1389 * this function. Used to avoid excess redrawing
1390 * @param {Number} prevEndX The value of endX on the previous call to this
1391 * function. Used to avoid excess redrawing
1392 * @param {Number} prevEndY The value of endY on the previous call to this
1393 * function. Used to avoid excess redrawing
1396 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1397 endY
, prevDirection
, prevEndX
,
1399 var ctx
= this.canvas_ctx_
;
1401 // Clean up from the previous rect if necessary
1402 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1403 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1404 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1405 } else if (prevDirection
== Dygraph
.VERTICAL
){
1406 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1407 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1410 // Draw a light-grey rectangle to show the new viewing area
1411 if (direction
== Dygraph
.HORIZONTAL
) {
1412 if (endX
&& startX
) {
1413 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1414 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1415 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1417 } else if (direction
== Dygraph
.VERTICAL
) {
1418 if (endY
&& startY
) {
1419 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1420 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1421 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1425 if (this.isUsingExcanvas_
) {
1426 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1431 * Clear the zoom rectangle (and perform no zoom).
1434 Dygraph
.prototype.clearZoomRect_
= function() {
1435 this.currentZoomRectArgs_
= null;
1436 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1440 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1441 * the canvas. The exact zoom window may be slightly larger if there are no data
1442 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1443 * which accepts dates that match the raw data. This function redraws the graph.
1445 * @param {Number} lowX The leftmost pixel value that should be visible.
1446 * @param {Number} highX The rightmost pixel value that should be visible.
1449 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1450 this.currentZoomRectArgs_
= null;
1451 // Find the earliest and latest dates contained in this canvasx range.
1452 // Convert the call to date ranges of the raw data.
1453 var minDate
= this.toDataXCoord(lowX
);
1454 var maxDate
= this.toDataXCoord(highX
);
1455 this.doZoomXDates_(minDate
, maxDate
);
1459 * Transition function to use in animations. Returns values between 0.0
1460 * (totally old values) and 1.0 (totally new values) for each frame.
1463 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1465 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1469 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1470 * method with doZoomX which accepts pixel coordinates. This function redraws
1473 * @param {Number} minDate The minimum date that should be visible.
1474 * @param {Number} maxDate The maximum date that should be visible.
1477 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1478 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1479 // can produce strange effects. Rather than the y-axis transitioning slowly
1480 // between values, it can jerk around.)
1481 var old_window
= this.xAxisRange();
1482 var new_window
= [minDate
, maxDate
];
1483 this.zoomed_x_
= true;
1485 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1486 if (that
.attr_("zoomCallback")) {
1487 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1493 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1494 * the canvas. This function redraws the graph.
1496 * @param {Number} lowY The topmost pixel value that should be visible.
1497 * @param {Number} highY The lowest pixel value that should be visible.
1500 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1501 this.currentZoomRectArgs_
= null;
1502 // Find the highest and lowest values in pixel range for each axis.
1503 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1504 // This is because pixels increase as you go down on the screen, whereas data
1505 // coordinates increase as you go up the screen.
1506 var oldValueRanges
= this.yAxisRanges();
1507 var newValueRanges
= [];
1508 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1509 var hi
= this.toDataYCoord(lowY
, i
);
1510 var low
= this.toDataYCoord(highY
, i
);
1511 newValueRanges
.push([low
, hi
]);
1514 this.zoomed_y_
= true;
1516 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1517 if (that
.attr_("zoomCallback")) {
1518 var xRange
= that
.xAxisRange();
1519 that
.attr_("zoomCallback")(xRange
[0], xRange
[1], that
.yAxisRanges());
1525 * Reset the zoom to the original view coordinates. This is the same as
1526 * double-clicking on the graph.
1528 Dygraph
.prototype.resetZoom
= function() {
1529 var dirty
= false, dirtyX
= false, dirtyY
= false;
1530 if (this.dateWindow_
!== null) {
1535 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1536 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1542 // Clear any selection, since it's likely to be drawn in the wrong place.
1543 this.clearSelection();
1546 this.zoomed_x_
= false;
1547 this.zoomed_y_
= false;
1549 var minDate
= this.rawData_
[0][0];
1550 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1552 // With only one frame, don't bother calculating extreme ranges.
1553 // TODO(danvk): merge this block w/ the code below
.
1554 if (!this.attr_("animatedZooms")) {
1555 this.dateWindow_
= null;
1556 for (i
= 0; i
< this.axes_
.length
; i
++) {
1557 if (this.axes_
[i
].valueWindow
!== null) {
1558 delete this.axes_
[i
].valueWindow
;
1562 if (this.attr_("zoomCallback")) {
1563 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1568 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1570 oldWindow
= this.xAxisRange();
1571 newWindow
= [minDate
, maxDate
];
1575 oldValueRanges
= this.yAxisRanges();
1576 // TODO(danvk): this is pretty inefficient
1577 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1578 var extremes
= packed
[1];
1580 // this has the side-effect of modifying this.axes_.
1581 // this doesn't make much sense in this context, but it's convenient (we
1582 // need this.axes_[*].extremeValues) and not harmful since we'll be
1583 // calling drawGraph_ shortly, which clobbers these values.
1584 this.computeYAxisRanges_(extremes
);
1586 newValueRanges
= [];
1587 for (i
= 0; i
< this.axes_
.length
; i
++) {
1588 var axis
= this.axes_
[i
];
1589 newValueRanges
.push((axis
.valueRange
!== null &&
1590 axis
.valueRange
!== undefined
) ?
1591 axis
.valueRange
: axis
.extremeRange
);
1596 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1598 that
.dateWindow_
= null;
1599 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1600 if (that
.axes_
[i
].valueWindow
!== null) {
1601 delete that
.axes_
[i
].valueWindow
;
1604 if (that
.attr_("zoomCallback")) {
1605 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1612 * Combined animation logic for all zoom functions.
1613 * either the x parameters or y parameters may be null.
1616 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1617 var steps
= this.attr_("animatedZooms") ? Dygraph
.ANIMATION_STEPS
: 1;
1620 var valueRanges
= [];
1623 if (oldXRange
!== null && newXRange
!== null) {
1624 for (step
= 1; step
<= steps
; step
++) {
1625 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1626 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1627 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1631 if (oldYRanges
!== null && newYRanges
!== null) {
1632 for (step
= 1; step
<= steps
; step
++) {
1633 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1635 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1636 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1637 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1639 valueRanges
[step
-1] = thisRange
;
1644 Dygraph
.repeatAndCleanup(function(step
) {
1645 if (valueRanges
.length
) {
1646 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1647 var w
= valueRanges
[step
][i
];
1648 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1651 if (windows
.length
) {
1652 that
.dateWindow_
= windows
[step
];
1655 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1659 * Get the current graph's area object.
1661 * Returns: {x, y, w, h}
1663 Dygraph
.prototype.getArea
= function() {
1664 return this.plotter_
.area
;
1668 * Convert a mouse event to DOM coordinates relative to the graph origin.
1670 * Returns a two-element array: [X, Y].
1672 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1673 if (event
.offsetX
&& event
.offsetY
) {
1674 return [ event
.offsetX
, event
.offsetY
];
1676 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1677 var canvasy
= Dygraph
.pageY(event
) - Dygraph
.findPosY(this.mouseEventElement_
);
1678 return [canvasx
, canvasy
];
1683 * Given a canvas X coordinate, find the closest row.
1684 * @param {Number} domX graph-relative DOM X coordinate
1685 * Returns: row number, integer
1688 Dygraph
.prototype.findClosestRow
= function(domX
) {
1689 var minDistX
= Infinity
;
1690 var pointIdx
= -1, setIdx
= -1;
1691 var sets
= this.layout_
.points
;
1692 for (var i
= 0; i
< sets
.length
; i
++) {
1693 var points
= sets
[i
];
1694 var len
= points
.length
;
1695 for (var j
= 0; j
< len
; j
++) {
1696 var point
= points
[j
];
1697 if (!Dygraph
.isValidPoint(point
, true)) continue;
1698 var dist
= Math
.abs(point
.canvasx
- domX
);
1699 if (dist
< minDistX
) {
1707 // TODO(danvk): remove this function; it's trivial and has only one use.
1708 return this.idxToRow_(setIdx
, pointIdx
);
1712 * Given canvas X,Y coordinates, find the closest point.
1714 * This finds the individual data point across all visible series
1715 * that's closest to the supplied DOM coordinates using the standard
1716 * Euclidean X,Y distance.
1718 * @param {Number} domX graph-relative DOM X coordinate
1719 * @param {Number} domY graph-relative DOM Y coordinate
1720 * Returns: {row, seriesName, point}
1723 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1724 var minDist
= Infinity
;
1726 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
;
1727 for ( var setIdx
= this.layout_
.datasets
.length
- 1 ; setIdx
>= 0 ; --setIdx
) {
1728 var points
= this.layout_
.points
[setIdx
];
1729 for (var i
= 0; i
< points
.length
; ++i
) {
1730 var point
= points
[i
];
1731 if (!Dygraph
.isValidPoint(point
)) continue;
1732 dx
= point
.canvasx
- domX
;
1733 dy
= point
.canvasy
- domY
;
1734 dist
= dx
* dx
+ dy
* dy
;
1735 if (dist
< minDist
) {
1737 closestPoint
= point
;
1738 closestSeries
= setIdx
;
1743 var name
= this.layout_
.setNames
[closestSeries
];
1745 row
: idx
+ this.getLeftBoundary_(),
1752 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1754 * This first finds the X data point closest to the supplied DOM X coordinate,
1755 * then finds the series which puts the Y coordinate on top of its filled area,
1756 * using linear interpolation between adjacent point pairs.
1758 * @param {Number} domX graph-relative DOM X coordinate
1759 * @param {Number} domY graph-relative DOM Y coordinate
1760 * Returns: {row, seriesName, point}
1763 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1764 var row
= this.findClosestRow(domX
);
1765 var boundary
= this.getLeftBoundary_();
1766 var rowIdx
= row
- boundary
;
1767 var closestPoint
, closestSeries
;
1768 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1769 var points
= this.layout_
.points
[setIdx
];
1770 if (rowIdx
>= points
.length
) continue;
1771 var p1
= points
[rowIdx
];
1772 if (!Dygraph
.isValidPoint(p1
)) continue;
1773 var py
= p1
.canvasy
;
1774 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < points
.length
) {
1775 // interpolate series Y value using next point
1776 var p2
= points
[rowIdx
+ 1];
1777 if (Dygraph
.isValidPoint(p2
)) {
1778 var dx
= p2
.canvasx
- p1
.canvasx
;
1780 var r
= (domX
- p1
.canvasx
) / dx
;
1781 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1784 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1785 // interpolate series Y value using previous point
1786 var p0
= points
[rowIdx
- 1];
1787 if (Dygraph
.isValidPoint(p0
)) {
1788 var dx
= p1
.canvasx
- p0
.canvasx
;
1790 var r
= (p1
.canvasx
- domX
) / dx
;
1791 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1795 // Stop if the point (domX, py) is above this series' upper edge
1796 if (setIdx
=== 0 || py
< domY
) {
1798 closestSeries
= setIdx
;
1801 var name
= this.layout_
.setNames
[closestSeries
];
1810 * When the mouse moves in the canvas, display information about a nearby data
1811 * point and draw dots over those points in the data series. This function
1812 * takes care of cleanup of previously-drawn dots.
1813 * @param {Object} event The mousemove event from the browser.
1816 Dygraph
.prototype.mouseMove_
= function(event
) {
1817 // This prevents JS errors when mousing over the canvas before data loads.
1818 var points
= this.layout_
.points
;
1819 if (points
=== undefined
|| points
=== null) return;
1821 var canvasCoords
= this.eventToDomCoords(event
);
1822 var canvasx
= canvasCoords
[0];
1823 var canvasy
= canvasCoords
[1];
1825 var highlightSeriesOpts
= this.attr_("highlightSeriesOpts");
1826 var selectionChanged
= false;
1827 if (highlightSeriesOpts
&& !this.isSeriesLocked()) {
1829 if (this.attr_("stackedGraph")) {
1830 closest
= this.findStackedPoint(canvasx
, canvasy
);
1832 closest
= this.findClosestPoint(canvasx
, canvasy
);
1834 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1836 var idx
= this.findClosestRow(canvasx
);
1837 selectionChanged
= this.setSelection(idx
);
1840 var callback
= this.attr_("highlightCallback");
1841 if (callback
&& selectionChanged
) {
1845 this.lastRow_
+ this.getLeftBoundary_(),
1846 this.highlightSet_
);
1851 * Fetch left offset from first defined boundaryIds record (see bug #236).
1854 Dygraph
.prototype.getLeftBoundary_
= function() {
1855 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1856 if (this.boundaryIds_
[i
] !== undefined
) {
1857 return this.boundaryIds_
[i
][0];
1864 * Transforms layout_.points index into data row number.
1865 * @param int layout_.points index
1866 * @return int row number, or -1 if none could be found.
1869 Dygraph
.prototype.idxToRow_
= function(setIdx
, rowIdx
) {
1870 if (rowIdx
< 0) return -1;
1872 var boundary
= this.getLeftBoundary_();
1873 return boundary
+ rowIdx
;
1874 // for (var setIdx = 0; setIdx < this.layout_.datasets.length; ++setIdx) {
1875 // var set = this.layout_.datasets[setIdx];
1876 // if (idx < set.length) {
1877 // return boundary + idx;
1879 // idx -= set.length;
1884 Dygraph
.prototype.animateSelection_
= function(direction
) {
1885 var totalSteps
= 10;
1887 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1888 if (this.animateId
=== undefined
) this.animateId
= 0;
1889 var start
= this.fadeLevel
;
1890 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1892 if (this.fadeLevel
) {
1893 this.updateSelection_(1.0);
1898 var thisId
= ++this.animateId
;
1900 Dygraph
.repeatAndCleanup(
1902 // ignore simultaneous animations
1903 if (that
.animateId
!= thisId
) return;
1905 that
.fadeLevel
+= direction
;
1906 if (that
.fadeLevel
=== 0) {
1907 that
.clearSelection();
1909 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1912 steps
, millis
, function() {});
1916 * Draw dots over the selectied points in the data series. This function
1917 * takes care of cleanup of previously-drawn dots.
1920 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1921 /*var defaultPrevented = */
1922 this.cascadeEvents_('select', {
1923 selectedX
: this.lastx_
,
1924 selectedPoints
: this.selPoints_
1926 // TODO(danvk): use defaultPrevented here?
1928 // Clear the previously drawn vertical, if there is one
1930 var ctx
= this.canvas_ctx_
;
1931 if (this.attr_('highlightSeriesOpts')) {
1932 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1933 var alpha
= 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
1935 // Activating background fade includes an animation effect for a gradual
1936 // fade. TODO(klausw): make this independently configurable if it causes
1937 // issues? Use a shared preference to control animations?
1938 var animateBackgroundFade
= true;
1939 if (animateBackgroundFade
) {
1940 if (opt_animFraction
=== undefined
) {
1941 // start a new animation
1942 this.animateSelection_(1);
1945 alpha
*= opt_animFraction
;
1947 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1948 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1951 // Redraw only the highlighted series in the interactive canvas (not the
1952 // static plot canvas, which is where series are usually drawn).
1953 this.plotter_
._renderLineChart(this.highlightSet_
, ctx
);
1954 } else if (this.previousVerticalX_
>= 0) {
1955 // Determine the maximum highlight circle size.
1956 var maxCircleSize
= 0;
1957 var labels
= this.attr_('labels');
1958 for (i
= 1; i
< labels
.length
; i
++) {
1959 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1960 if (r
> maxCircleSize
) maxCircleSize
= r
;
1962 var px
= this.previousVerticalX_
;
1963 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1964 2 * maxCircleSize
+ 2, this.height_
);
1967 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
1968 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
1971 if (this.selPoints_
.length
> 0) {
1972 // Draw colored circles over the center of each selected point
1973 var canvasx
= this.selPoints_
[0].canvasx
;
1975 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1976 var pt
= this.selPoints_
[i
];
1977 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1979 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1980 var callback
= this.attr_("drawHighlightPointCallback", pt
.name
);
1981 var color
= this.plotter_
.colors
[pt
.name
];
1983 callback
= Dygraph
.Circles
.DEFAULT
;
1985 ctx
.lineWidth
= this.attr_('strokeWidth', pt
.name
);
1986 ctx
.strokeStyle
= color
;
1987 ctx
.fillStyle
= color
;
1988 callback(this.g
, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1993 this.previousVerticalX_
= canvasx
;
1998 * Manually set the selected points and display information about them in the
1999 * legend. The selection can be cleared using clearSelection() and queried
2000 * using getSelection().
2001 * @param { Integer } row number that should be highlighted (i.e. appear with
2002 * hover dots on the chart). Set to false to clear any selection.
2003 * @param { seriesName } optional series name to highlight that series with the
2004 * the highlightSeriesOpts setting.
2005 * @param { locked } optional If true, keep seriesName selected when mousing
2006 * over the graph, disabling closest-series highlighting. Call clearSelection()
2009 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
, opt_locked
) {
2010 // Extract the points we've selected
2011 this.selPoints_
= [];
2013 if (row
!== false) {
2014 row
-= this.getLeftBoundary_();
2017 var changed
= false;
2018 if (row
!== false && row
>= 0) {
2019 if (row
!= this.lastRow_
) changed
= true;
2020 this.lastRow_
= row
;
2021 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
2022 var set
= this.layout_
.datasets
[setIdx
];
2023 if (row
< set
.length
) {
2024 var point
= this.layout_
.points
[setIdx
][row
];
2026 if (this.attr_("stackedGraph")) {
2027 point
= this.layout_
.unstackPointAtIndex(setIdx
, row
);
2030 if (point
.yval
!== null) this.selPoints_
.push(point
);
2034 if (this.lastRow_
>= 0) changed
= true;
2038 if (this.selPoints_
.length
) {
2039 this.lastx_
= this.selPoints_
[0].xval
;
2044 if (opt_seriesName
!== undefined
) {
2045 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
2046 this.highlightSet_
= opt_seriesName
;
2049 if (opt_locked
!== undefined
) {
2050 this.lockedSet_
= opt_locked
;
2054 this.updateSelection_(undefined
);
2060 * The mouse has left the canvas. Clear out whatever artifacts remain
2061 * @param {Object} event the mouseout event from the browser.
2064 Dygraph
.prototype.mouseOut_
= function(event
) {
2065 if (this.attr_("unhighlightCallback")) {
2066 this.attr_("unhighlightCallback")(event
);
2069 if (this.attr_("hideOverlayOnMouseOut") && !this.lockedSet_
) {
2070 this.clearSelection();
2075 * Clears the current selection (i.e. points that were highlighted by moving
2076 * the mouse over the chart).
2078 Dygraph
.prototype.clearSelection
= function() {
2079 this.cascadeEvents_('deselect', {});
2081 this.lockedSet_
= false;
2082 // Get rid of the overlay data
2083 if (this.fadeLevel
) {
2084 this.animateSelection_(-1);
2087 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
2089 this.selPoints_
= [];
2092 this.highlightSet_
= null;
2096 * Returns the number of the currently selected row. To get data for this row,
2097 * you can use the getValue method.
2098 * @return { Integer } row number, or -1 if nothing is selected
2100 Dygraph
.prototype.getSelection
= function() {
2101 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
2105 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; setIdx
++) {
2106 var points
= this.layout_
.points
[setIdx
];
2107 for (var row
= 0; row
< points
.length
; row
++) {
2108 if (points
[row
].x
== this.selPoints_
[0].x
) {
2109 return row
+ this.getLeftBoundary_();
2117 * Returns the name of the currently-highlighted series.
2118 * Only available when the highlightSeriesOpts option is in use.
2120 Dygraph
.prototype.getHighlightSeries
= function() {
2121 return this.highlightSet_
;
2125 * Returns true if the currently-highlighted series was locked
2126 * via setSelection(..., seriesName, true).
2128 Dygraph
.prototype.isSeriesLocked
= function() {
2129 return this.lockedSet_
;
2133 * Fires when there's data available to be graphed.
2134 * @param {String} data Raw CSV data to be plotted
2137 Dygraph
.prototype.loadedEvent_
= function(data
) {
2138 this.rawData_
= this.parseCSV_(data
);
2143 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2146 Dygraph
.prototype.addXTicks_
= function() {
2147 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2149 if (this.dateWindow_
) {
2150 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2152 range
= this.xAxisExtremes();
2155 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2156 var xTicks
= xAxisOptionsView('ticker')(
2159 this.width_
, // TODO(danvk): should be area.width
2162 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2163 // console.log(msg);
2164 this.layout_
.setXTicks(xTicks
);
2169 * Computes the range of the data series (including confidence intervals).
2170 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2171 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2172 * @return [low, high]
2174 Dygraph
.prototype.extremeValues_
= function(series
) {
2175 var minY
= null, maxY
= null, j
, y
;
2177 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2179 // With custom bars, maxY is the max of the high values.
2180 for (j
= 0; j
< series
.length
; j
++) {
2181 y
= series
[j
][1][0];
2182 if (y
=== null || isNaN(y
)) continue;
2183 var low
= y
- series
[j
][1][1];
2184 var high
= y
+ series
[j
][1][2];
2185 if (low
> y
) low
= y
; // this can happen with custom bars,
2186 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2187 if (maxY
=== null || high
> maxY
) {
2190 if (minY
=== null || low
< minY
) {
2195 for (j
= 0; j
< series
.length
; j
++) {
2197 if (y
=== null || isNaN(y
)) continue;
2198 if (maxY
=== null || y
> maxY
) {
2201 if (minY
=== null || y
< minY
) {
2207 return [minY
, maxY
];
2212 * This function is called once when the chart's data is changed or the options
2213 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2214 * idea is that values derived from the chart's data can be computed here,
2215 * rather than every time the chart is drawn. This includes things like the
2216 * number of axes, rolling averages, etc.
2218 Dygraph
.prototype.predraw_
= function() {
2219 var start
= new Date();
2221 this.layout_
.computePlotArea();
2223 // TODO(danvk): move more computations out of drawGraph_ and into here.
2224 this.computeYAxes_();
2226 // Create a new plotter.
2227 if (this.plotter_
) {
2228 this.cascadeEvents_('clearChart');
2229 this.plotter_
.clear();
2231 this.plotter_
= new DygraphCanvasRenderer(this,
2236 // The roller sits in the bottom left corner of the chart. We don't know where
2237 // this will be until the options are available, so it's positioned here.
2238 this.createRollInterface_();
2240 this.cascadeEvents_('predraw');
2242 // Convert the raw data (a 2D array) into the internal format and compute
2243 // rolling averages.
2244 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2245 for (var i
= 1; i
< this.numColumns(); i
++) {
2246 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too
.
2247 var logScale
= this.attr_('logscale');
2248 var series
= this.extractSeries_(this.rawData_
, i
, logScale
);
2249 series
= this.rollingAverage(series
, this.rollPeriod_
);
2250 this.rolledSeries_
.push(series
);
2253 // If the data or options have changed, then we'd better redraw.
2256 // This is used to determine whether to do various animations.
2257 var end
= new Date();
2258 this.drawingTimeMs_
= (end
- start
);
2262 * Loop over all fields and create datasets, calculating extreme y-values for
2263 * each series and extreme x-indices as we go.
2265 * dateWindow is passed in as an explicit parameter so that we can compute
2266 * extreme values "speculatively", i.e. without actually setting state on the
2269 * TODO(danvk): make this more of a true function
2270 * @return [ datasets, seriesExtremes, boundaryIds ]
2273 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2274 var boundaryIds
= [];
2275 var cumulative_y
= []; // For stacked series.
2277 var extremes
= {}; // series name -> [low, high]
2280 // Loop over the fields (series). Go from the last to the first,
2281 // because if they're stacked that's how we accumulate the values.
2282 var num_series
= rolledSeries
.length
- 1;
2283 for (i
= num_series
; i
>= 1; i
--) {
2284 if (!this.visibility()[i
- 1]) continue;
2286 // Note: this copy _is_ necessary at the moment.
2287 // If you remove it, it breaks zooming with error bars on.
2288 // TODO(danvk): investigate further & write a test for this.
2290 for (j
= 0; j
< rolledSeries
[i
].length
; j
++) {
2291 series
.push(rolledSeries
[i
][j
]);
2294 // Prune down to the desired range, if necessary (for zooming)
2295 // Because there can be lines going to points outside of the visible area,
2296 // we actually prune to visible points, plus one on either side.
2297 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2299 var low
= dateWindow
[0];
2300 var high
= dateWindow
[1];
2302 // TODO(danvk): do binary search instead of linear search.
2303 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2304 var firstIdx
= null, lastIdx
= null;
2305 for (k
= 0; k
< series
.length
; k
++) {
2306 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2309 if (series
[k
][0] <= high
) {
2313 if (firstIdx
=== null) firstIdx
= 0;
2314 if (firstIdx
> 0) firstIdx
--;
2315 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2316 if (lastIdx
< series
.length
- 1) lastIdx
++;
2317 boundaryIds
[i
-1] = [firstIdx
, lastIdx
];
2318 for (k
= firstIdx
; k
<= lastIdx
; k
++) {
2319 pruned
.push(series
[k
]);
2323 boundaryIds
[i
-1] = [0, series
.length
-1];
2326 var seriesExtremes
= this.extremeValues_(series
);
2329 for (j
=0; j
<series
.length
; j
++) {
2330 series
[j
] = [series
[j
][0],
2335 } else if (this.attr_("stackedGraph")) {
2336 var actual_y
, last_x
;
2337 for (j
= 0; j
< series
.length
; j
++) {
2338 // If one data set has a NaN, let all subsequent stacked
2339 // sets inherit the NaN -- only start at 0 for the first set.
2340 var x
= series
[j
][0];
2341 if (cumulative_y
[x
] === undefined
) {
2342 cumulative_y
[x
] = 0;
2345 actual_y
= series
[j
][1];
2346 if (actual_y
=== null) {
2347 series
[j
] = [x
, null];
2351 if (j
=== 0 || last_x
!= x
) {
2352 cumulative_y
[x
] += actual_y
;
2353 // If an x-value is repeated, we ignore the duplicates.
2357 series
[j
] = [x
, cumulative_y
[x
]];
2359 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2360 seriesExtremes
[1] = cumulative_y
[x
];
2362 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2363 seriesExtremes
[0] = cumulative_y
[x
];
2368 var seriesName
= this.attr_("labels")[i
];
2369 extremes
[seriesName
] = seriesExtremes
;
2370 datasets
[i
] = series
;
2373 // For stacked graphs, a NaN value for any point in the sum should create a
2374 // clean gap in the graph. Back-propagate NaNs to all points at this X value.
2375 if (this.attr_("stackedGraph")) {
2376 for (k
= datasets
.length
- 1; k
>= 0; --k
) {
2377 // Use the first nonempty dataset to get X values.
2378 if (!datasets
[k
]) continue;
2379 for (j
= 0; j
< datasets
[k
].length
; j
++) {
2380 var x
= datasets
[k
][j
][0];
2381 if (isNaN(cumulative_y
[x
])) {
2382 // Set all Y values to NaN at that X value.
2383 for (i
= datasets
.length
- 1; i
>= 0; i
--) {
2384 if (!datasets
[i
]) continue;
2385 datasets
[i
][j
][1] = NaN
;
2393 return [ datasets
, extremes
, boundaryIds
];
2397 * Update the graph with new data. This method is called when the viewing area
2398 * has changed. If the underlying data or options have changed, predraw_ will
2399 * be called before drawGraph_ is called.
2403 Dygraph
.prototype.drawGraph_
= function() {
2404 var start
= new Date();
2406 // This is used to set the second parameter to drawCallback, below.
2407 var is_initial_draw
= this.is_initial_draw_
;
2408 this.is_initial_draw_
= false;
2410 this.layout_
.removeAllDatasets();
2412 this.attrs_
.pointSize
= 0.5 * this.attr_('highlightCircleSize');
2414 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2415 var datasets
= packed
[0];
2416 var extremes
= packed
[1];
2417 this.boundaryIds_
= packed
[2];
2419 this.setIndexByName_
= {};
2420 var labels
= this.attr_("labels");
2421 if (labels
.length
> 0) {
2422 this.setIndexByName_
[labels
[0]] = 0;
2425 for (var i
= 1; i
< datasets
.length
; i
++) {
2426 this.setIndexByName_
[labels
[i
]] = i
;
2427 if (!this.visibility()[i
- 1]) continue;
2428 this.layout_
.addDataset(labels
[i
], datasets
[i
]);
2429 this.datasetIndex_
[i
] = dataIdx
++;
2432 this.computeYAxisRanges_(extremes
);
2433 this.layout_
.setYAxes(this.axes_
);
2437 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2438 var tmp_zoomed_x
= this.zoomed_x_
;
2439 // Tell PlotKit to use this new data and render itself
2440 this.layout_
.setDateWindow(this.dateWindow_
);
2441 this.zoomed_x_
= tmp_zoomed_x
;
2442 this.layout_
.evaluateWithError();
2443 this.renderGraph_(is_initial_draw
);
2445 if (this.attr_("timingName")) {
2446 var end
= new Date();
2447 Dygraph
.info(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2452 * This does the work of drawing the chart. It assumes that the layout and axis
2453 * scales have already been set (e.g. by predraw_).
2457 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2458 this.cascadeEvents_('clearChart');
2459 this.plotter_
.clear();
2461 if (this.attr_('underlayCallback')) {
2462 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2463 // users who expect a deprecated form of this callback.
2464 this.attr_('underlayCallback')(
2465 this.hidden_ctx_
, this.layout_
.getPlotArea(), this, this);
2469 canvas
: this.hidden_
,
2470 drawingContext
: this.hidden_ctx_
2472 this.cascadeEvents_('willDrawChart', e
);
2473 this.plotter_
.render();
2474 this.cascadeEvents_('didDrawChart', e
);
2475 this.lastRow_
= -1; // because plugins/legend.js clears the legend
2477 // TODO(danvk): is this a performance bottleneck when panning?
2478 // The interaction canvas should already be empty in that situation.
2479 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2480 this.canvas_
.height
);
2482 if (this.attr_("drawCallback") !== null) {
2483 this.attr_("drawCallback")(this, is_initial_draw
);
2489 * Determine properties of the y-axes which are independent of the data
2490 * currently being displayed. This includes things like the number of axes and
2491 * the style of the axes. It does not include the range of each axis and its
2493 * This fills in this.axes_.
2494 * axes_ = [ { options } ]
2495 * indices are into the axes_ array.
2497 Dygraph
.prototype.computeYAxes_
= function() {
2498 // Preserve valueWindow settings if they exist, and if the user hasn't
2499 // specified a new valueRange.
2500 var valueWindows
, axis
, index
, opts
, v
;
2501 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2503 for (index
= 0; index
< this.axes_
.length
; index
++) {
2504 valueWindows
.push(this.axes_
[index
].valueWindow
);
2508 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2509 // data computation as well as options storage.
2510 // Go through once and add all the axes.
2513 for (axis
= 0; axis
< this.attributes_
.numAxes(); axis
++) {
2514 // Add a new axis, making a copy of its per-axis options.
2515 opts
= { g
: this };
2516 Dygraph
.update(opts
, this.attributes_
.axisOptions(axis
));
2517 this.axes_
[axis
] = opts
;
2521 // Copy global valueRange option over to the first axis.
2522 // NOTE(konigsberg): Are these two statements necessary?
2523 // I tried removing it. The automated tests pass, and manually
2524 // messing with tests/zoom
.html showed no trouble
.
2525 v
= this.attr_('valueRange');
2526 if (v
) this.axes_
[0].valueRange
= v
;
2528 if (valueWindows
!== undefined
) {
2529 // Restore valueWindow settings.
2530 for (index
= 0; index
< valueWindows
.length
; index
++) {
2531 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2535 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2537 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2538 v
= opts("valueRange");
2539 if (v
) this.axes_
[axis
].valueRange
= v
;
2540 } else { // To keep old behavior
2541 var axes
= this.user_attrs_
.axes
;
2542 if (axes
&& axes
.y2
) {
2543 v
= axes
.y2
.valueRange
;
2544 if (v
) this.axes_
[axis
].valueRange
= v
;
2551 * Returns the number of y-axes on the chart.
2552 * @return {Number} the number of axes.
2554 Dygraph
.prototype.numAxes
= function() {
2555 return this.attributes_
.numAxes();
2560 * Returns axis properties for the given series.
2561 * @param { String } setName The name of the series for which to get axis
2562 * properties, e.g. 'Y1'.
2563 * @return { Object } The axis properties.
2565 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2566 // TODO(danvk): handle errors.
2567 return this.axes_
[this.attributes_
.axisForSeries(series
)];
2572 * Determine the value range and tick marks for each axis.
2573 * @param {Object} extremes A mapping from seriesName -> [low, high]
2574 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2576 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2577 var isNullUndefinedOrNaN
= function(num
) {
2578 return isNaN(parseFloat(num
));
2580 var numAxes
= this.attributes_
.numAxes();
2581 var ypadCompat
, span
, series
, ypad
;
2583 // Compute extreme values, a span and tick marks for each axis.
2584 for (var i
= 0; i
< numAxes
; i
++) {
2585 var axis
= this.axes_
[i
];
2586 var logscale
= this.attributes_
.getForAxis("logscale", i
);
2587 var includeZero
= this.attributes_
.getForAxis("includeZero", i
);
2588 series
= this.attributes_
.seriesForAxis(i
);
2590 if (series
.length
=== 0) {
2591 // If no series are defined or visible then use a reasonable default
2592 axis
.extremeRange
= [0, 1];
2594 // Calculate the extremes of extremes.
2595 var minY
= Infinity
; // extremes[series[0]][0];
2596 var maxY
= -Infinity
; // extremes[series[0]][1];
2597 var extremeMinY
, extremeMaxY
;
2599 for (var j
= 0; j
< series
.length
; j
++) {
2600 // this skips invisible series
2601 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2603 // Only use valid extremes to stop null data series' from corrupting the scale.
2604 extremeMinY
= extremes
[series
[j
]][0];
2605 if (extremeMinY
!== null) {
2606 minY
= Math
.min(extremeMinY
, minY
);
2608 extremeMaxY
= extremes
[series
[j
]][1];
2609 if (extremeMaxY
!== null) {
2610 maxY
= Math
.max(extremeMaxY
, maxY
);
2614 // Include zero if requested by the user.
2615 if (includeZero
&& !logscale
) {
2616 if (minY
> 0) minY
= 0;
2617 if (maxY
< 0) maxY
= 0;
2620 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2621 if (minY
== Infinity
) minY
= 0;
2622 if (maxY
== -Infinity
) maxY
= 1;
2625 // special case: if we have no sense of scale, center on the sole value.
2628 span
= Math
.abs(maxY
);
2630 // ... and if the sole value is zero, use range 0-1.
2636 // Add some padding. This supports two Y padding operation modes:
2638 // - backwards compatible (yRangePad not set):
2639 // 10% padding for automatic Y ranges, but not for user-supplied
2640 // ranges, and move a close-to-zero edge to zero except if
2641 // avoidMinZero is set, since drawing at the edge results in
2642 // invisible lines. Unfortunately lines drawn at the edge of a
2643 // user-supplied range will still be invisible. If logscale is
2644 // set, add a variable amount of padding at the top but
2645 // none at the bottom.
2647 // - new-style (yRangePad set by the user):
2648 // always add the specified Y padding.
2651 ypad
= 0.1; // add 10%
2652 if (this.attr_('yRangePad') !== null) {
2654 // Convert pixel padding to ratio
2655 ypad
= this.attr_('yRangePad') / this.plotter_
.area
.h
;
2658 var maxAxisY
, minAxisY
;
2661 maxAxisY
= maxY
+ ypad
* span
;
2664 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2665 maxAxisY
= maxY
* logpad
;
2666 minAxisY
= minY
/ logpad
;
2669 maxAxisY
= maxY
+ ypad
* span
;
2670 minAxisY
= minY
- ypad
* span
;
2672 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2673 // close to zero, but not if avoidMinZero is set.
2674 if (ypadCompat
&& !this.attr_("avoidMinZero")) {
2675 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2676 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2679 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2681 if (axis
.valueWindow
) {
2682 // This is only set if the user has zoomed on the y-axis. It is never set
2683 // by a user. It takes precedence over axis.valueRange because, if you set
2684 // valueRange, you'd still expect to be able to pan.
2685 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2686 } else if (axis
.valueRange
) {
2687 // This is a user-set value range for this axis.
2688 var y0
= isNullUndefinedOrNaN(axis
.valueRange
[0]) ? axis
.extremeRange
[0] : axis
.valueRange
[0];
2689 var y1
= isNullUndefinedOrNaN(axis
.valueRange
[1]) ? axis
.extremeRange
[1] : axis
.valueRange
[1];
2691 if (axis
.logscale
) {
2692 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2701 axis
.computedValueRange
= [y0
, y1
];
2703 axis
.computedValueRange
= axis
.extremeRange
;
2706 // Add ticks. By default, all axes inherit the tick positions of the
2707 // primary axis. However, if an axis is specifically marked as having
2708 // independent ticks, then that is permissible as well.
2709 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2710 var ticker
= opts('ticker');
2711 if (i
=== 0 || axis
.independentTicks
) {
2712 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2713 axis
.computedValueRange
[1],
2714 this.height_
, // TODO(danvk): should be area.height
2718 var p_axis
= this.axes_
[0];
2719 var p_ticks
= p_axis
.ticks
;
2720 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2721 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2722 var tick_values
= [];
2723 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2724 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2725 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2726 tick_values
.push(y_val
);
2729 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2730 axis
.computedValueRange
[1],
2731 this.height_
, // TODO(danvk): should be area.height
2740 * Extracts one series from the raw data (a 2D array) into an array of (date,
2743 * This is where undesirable points (i.e. negative values on log scales and
2744 * missing values through which we wish to connect lines) are dropped.
2745 * TODO(danvk): the "missing values" bit above doesn't seem right.
2749 Dygraph
.prototype.extractSeries_
= function(rawData
, i
, logScale
) {
2750 // TODO(danvk): pre-allocate series here.
2752 for (var j
= 0; j
< rawData
.length
; j
++) {
2753 var x
= rawData
[j
][0];
2754 var point
= rawData
[j
][i
];
2756 // On the log scale, points less than zero do not exist.
2757 // This will create a gap in the chart.
2762 series
.push([x
, point
]);
2769 * Calculates the rolling average of a data set.
2770 * If originalData is [label, val], rolls the average of those.
2771 * If originalData is [label, [, it's interpreted as [value, stddev]
2772 * and the roll is returned in the same form, with appropriately reduced
2773 * stddev for each value.
2774 * Note that this is where fractional input (i.e. '5/10') is converted into
2776 * @param {Array} originalData The data in the appropriate format (see above)
2777 * @param {Number} rollPeriod The number of points over which to average the
2780 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2781 rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2782 var rollingData
= [];
2783 var sigma
= this.attr_("sigma");
2785 var low
, high
, i
, j
, y
, sum
, num_ok
, stddev
;
2786 if (this.fractions_
) {
2788 var den
= 0; // numerator/denominator
2790 for (i
= 0; i
< originalData
.length
; i
++) {
2791 num
+= originalData
[i
][1][0];
2792 den
+= originalData
[i
][1][1];
2793 if (i
- rollPeriod
>= 0) {
2794 num
-= originalData
[i
- rollPeriod
][1][0];
2795 den
-= originalData
[i
- rollPeriod
][1][1];
2798 var date
= originalData
[i
][0];
2799 var value
= den
? num
/ den
: 0.0;
2800 if (this.attr_("errorBars")) {
2801 if (this.attr_("wilsonInterval")) {
2802 // For more details on this confidence interval, see:
2803 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2805 var p
= value
< 0 ? 0 : value
, n
= den
;
2806 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2807 var denom
= 1 + sigma
* sigma
/ den
;
2808 low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2809 high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2810 rollingData
[i
] = [date
,
2811 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2813 rollingData
[i
] = [date
, [0, 0, 0]];
2816 stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2817 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2820 rollingData
[i
] = [date
, mult
* value
];
2823 } else if (this.attr_("customBars")) {
2828 for (i
= 0; i
< originalData
.length
; i
++) {
2829 var data
= originalData
[i
][1];
2831 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2833 if (y
!== null && !isNaN(y
)) {
2839 if (i
- rollPeriod
>= 0) {
2840 var prev
= originalData
[i
- rollPeriod
];
2841 if (prev
[1][1] !== null && !isNaN(prev
[1][1])) {
2849 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2850 1.0 * (mid
- low
) / count
,
2851 1.0 * (high
- mid
) / count
]];
2853 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2857 // Calculate the rolling average for the first rollPeriod - 1 points where
2858 // there is not enough data to roll over the full number of points
2859 if (!this.attr_("errorBars")){
2860 if (rollPeriod
== 1) {
2861 return originalData
;
2864 for (i
= 0; i
< originalData
.length
; i
++) {
2867 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2868 y
= originalData
[j
][1];
2869 if (y
=== null || isNaN(y
)) continue;
2871 sum
+= originalData
[j
][1];
2874 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2876 rollingData
[i
] = [originalData
[i
][0], null];
2881 for (i
= 0; i
< originalData
.length
; i
++) {
2885 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2886 y
= originalData
[j
][1][0];
2887 if (y
=== null || isNaN(y
)) continue;
2889 sum
+= originalData
[j
][1][0];
2890 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2893 stddev
= Math
.sqrt(variance
) / num_ok
;
2894 rollingData
[i
] = [originalData
[i
][0],
2895 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2897 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2907 * Detects the type of the str (date or numeric) and sets the various
2908 * formatting attributes in this.attrs_ based on this type.
2909 * @param {String} str An x value.
2912 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2914 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2915 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
2916 str
.indexOf('/') >= 0 ||
2917 isNaN(parseFloat(str
))) {
2919 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2920 // TODO(danvk): remove support for this format.
2924 this.setXAxisOptions_(isDate
);
2927 Dygraph
.prototype.setXAxisOptions_
= function(isDate
) {
2929 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2930 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
2931 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2932 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2934 /** @private (shut up, jsdoc!) */
2935 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2936 // TODO(danvk): use Dygraph.numberValueFormatter here?
2937 /** @private (shut up, jsdoc!) */
2938 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2939 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
2940 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2945 * Parses the value as a floating point number. This is like the parseFloat()
2946 * built-in, but with a few differences:
2947 * - the empty string is parsed as null, rather than NaN.
2948 * - if the string cannot be parsed at all, an error is logged.
2949 * If the string can't be parsed, this method returns null.
2950 * @param {String} x The string to be parsed
2951 * @param {Number} opt_line_no The line number from which the string comes.
2952 * @param {String} opt_line The text of the line from which the string comes.
2956 // Parse the x as a float or return null if it's not a number.
2957 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
2958 var val
= parseFloat(x
);
2959 if (!isNaN(val
)) return val
;
2961 // Try to figure out what happeend.
2962 // If the value is the empty string, parse it as null.
2963 if (/^ *$/.test(x
)) return null;
2965 // If it was actually "NaN", return it as NaN.
2966 if (/^ *nan *$/i.test(x
)) return NaN
;
2968 // Looks like a parsing error.
2969 var msg
= "Unable to parse '" + x
+ "' as a number";
2970 if (opt_line
!== null && opt_line_no
!== null) {
2971 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
2980 * Parses a string in a special csv format. We expect a csv file where each
2981 * line is a date point, and the first field in each line is the date string.
2982 * We also expect that all remaining fields represent series.
2983 * if the errorBars attribute is set, then interpret the fields as:
2984 * date, series1, stddev1, series2, stddev2, ...
2985 * @param {[Object]} data See above.
2987 * @return [Object] An array with one entry for each row. These entries
2988 * are an array of cells in that row. The first entry is the parsed x-value for
2989 * the row. The second, third, etc. are the y-values. These can take on one of
2990 * three forms, depending on the CSV and constructor parameters:
2992 * 2. [ value, stddev ]
2993 * 3. [ low value, center value, high value ]
2995 Dygraph
.prototype.parseCSV_
= function(data
) {
2997 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
2998 var lines
= data
.split(line_delimiter
|| "\n");
3001 // Use the default delimiter or fall back to a tab if that makes sense.
3002 var delim
= this.attr_('delimiter');
3003 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
3008 if (!('labels' in this.user_attrs_
)) {
3009 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3011 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
3012 this.attributes_
.reparseSeries();
3017 var defaultParserSet
= false; // attempt to auto-detect x value type
3018 var expectedCols
= this.attr_("labels").length
;
3019 var outOfOrder
= false;
3020 for (var i
= start
; i
< lines
.length
; i
++) {
3021 var line
= lines
[i
];
3023 if (line
.length
=== 0) continue; // skip blank lines
3024 if (line
[0] == '#') continue; // skip comment lines
3025 var inFields
= line
.split(delim
);
3026 if (inFields
.length
< 2) continue;
3029 if (!defaultParserSet
) {
3030 this.detectTypeFromString_(inFields
[0]);
3031 xParser
= this.attr_("xValueParser");
3032 defaultParserSet
= true;
3034 fields
[0] = xParser(inFields
[0], this);
3036 // If fractions are expected, parse the numbers as "A/B
"
3037 if (this.fractions_) {
3038 for (j = 1; j < inFields.length; j++) {
3039 // TODO(danvk): figure out an appropriate way to flag parse errors.
3040 vals = inFields[j].split("/");
3041 if (vals.length != 2) {
3042 this.error('Expected fractional "num
/den
" values in CSV data ' +
3043 "but found a value
'" + inFields[j] + "' on line
" +
3044 (1 + i) + " ('" + line + "') which is not of
this form
.");
3047 fields[j] = [this.parseFloat_(vals[0], i, line),
3048 this.parseFloat_(vals[1], i, line)];
3051 } else if (this.attr_("errorBars
")) {
3052 // If there are error bars, values are (value, stddev) pairs
3053 if (inFields.length % 2 != 1) {
3054 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3055 'but line ' + (1 + i) + ' has an odd number of values (' +
3056 (inFields.length - 1) + "): '" + line + "'");
3058 for (j = 1; j < inFields.length; j += 2) {
3059 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3060 this.parseFloat_(inFields[j + 1], i, line)];
3062 } else if (this.attr_("customBars
")) {
3063 // Bars are a low;center;high tuple
3064 for (j = 1; j < inFields.length; j++) {
3065 var val = inFields[j];
3066 if (/^ *$/.test(val)) {
3067 fields[j] = [null, null, null];
3069 vals = val.split(";");
3070 if (vals.length == 3) {
3071 fields[j] = [ this.parseFloat_(vals[0], i, line),
3072 this.parseFloat_(vals[1], i, line),
3073 this.parseFloat_(vals[2], i, line) ];
3075 this.warn('When using customBars, values must be either blank ' +
3076 'or "low
;center
;high
" tuples (got "' + val +
3077 '" on line ' + (1+i));
3082 // Values are just numbers
3083 for (j = 1; j < inFields.length; j++) {
3084 fields[j] = this.parseFloat_(inFields[j], i, line);
3087 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3091 if (fields.length != expectedCols) {
3092 this.error("Number of columns
in line
" + i + " (" + fields.length +
3093 ") does not agree
with number of
labels (" + expectedCols +
3097 // If the user specified the 'labels' option and none of the cells of the
3098 // first row parsed correctly, then they probably double-specified the
3099 // labels. We go with the values set in the option, discard this row and
3100 // log a warning to the JS console.
3101 if (i === 0 && this.attr_('labels')) {
3102 var all_null = true;
3103 for (j = 0; all_null && j < fields.length; j++) {
3104 if (fields[j]) all_null = false;
3107 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
3108 "CSV
data ('" + line + "') appears to also contain labels
. " +
3109 "Will drop the CSV labels and
use the option labels
.");
3117 this.warn("CSV is out of order
; order it correctly to speed loading
.");
3118 ret.sort(function(a,b) { return a[0] - b[0]; });
3126 * The user has provided their data as a pre-packaged JS array. If the x values
3127 * are numeric, this is the same as dygraphs' internal format. If the x values
3128 * are dates, we need to convert them from Date objects to ms since epoch.
3129 * @param {[Object]} data
3130 * @return {[Object]} data with numeric x values.
3132 Dygraph.prototype.parseArray_ = function(data) {
3133 // Peek at the first x value to see if it's numeric.
3134 if (data.length === 0) {
3135 this.error("Can
't plot empty data set");
3138 if (data[0].length === 0) {
3139 this.error("Data set cannot contain an empty row");
3144 if (this.attr_("labels") === null) {
3145 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3146 "in the options parameter");
3147 this.attrs_.labels = [ "X" ];
3148 for (i = 1; i < data[0].length; i++) {
3149 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
3151 this.attributes_.reparseSeries();
3153 var num_labels = this.attr_("labels");
3154 if (num_labels.length != data[0].length) {
3155 this.error("Mismatch between number of labels (" + num_labels +
3156 ") and number of columns in array (" + data[0].length + ")");
3161 if (Dygraph.isDateLike(data[0][0])) {
3162 // Some intelligent defaults for a date x-axis.
3163 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3164 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3165 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3167 // Assume they're all dates
.
3168 var parsedData
= Dygraph
.clone(data
);
3169 for (i
= 0; i
< data
.length
; i
++) {
3170 if (parsedData
[i
].length
=== 0) {
3171 this.error("Row " + (1 + i
) + " of data is empty");
3174 if (parsedData
[i
][0] === null ||
3175 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3176 isNaN(parsedData
[i
][0].getTime())) {
3177 this.error("x value in row " + (1 + i
) + " is not a Date");
3180 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3184 // Some intelligent defaults for a numeric x-axis.
3185 /** @private (shut up, jsdoc!) */
3186 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3187 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3188 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3194 * Parses a DataTable object from gviz.
3195 * The data is expected to have a first column that is either a date or a
3196 * number. All subsequent columns must be numbers. If there is a clear mismatch
3197 * between this.xValueParser_ and the type of the first column, it will be
3198 * fixed. Fills out rawData_.
3199 * @param {[Object]} data See above.
3202 Dygraph
.prototype.parseDataTable_
= function(data
) {
3203 var shortTextForAnnotationNum
= function(num
) {
3204 // converts [0-9]+ [A-Z][a-z]*
3205 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3206 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3207 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3208 num
= Math
.floor(num
/ 26);
3210 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3211 num
= Math
.floor((num
- 1) / 26);
3216 var cols
= data
.getNumberOfColumns();
3217 var rows
= data
.getNumberOfRows();
3219 var indepType
= data
.getColumnType(0);
3220 if (indepType
== 'date' || indepType
== 'datetime') {
3221 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3222 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3223 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3224 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3225 } else if (indepType
== 'number') {
3226 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3227 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3228 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3229 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3231 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3232 "column 1 of DataTable input (Got '" + indepType
+ "')");
3236 // Array of the column indices which contain data (and not annotations).
3238 var annotationCols
= {}; // data index -> [annotation cols]
3239 var hasAnnotations
= false;
3241 for (i
= 1; i
< cols
; i
++) {
3242 var type
= data
.getColumnType(i
);
3243 if (type
== 'number') {
3245 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3246 // This is OK -- it's an annotation column.
3247 var dataIdx
= colIdx
[colIdx
.length
- 1];
3248 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3249 annotationCols
[dataIdx
] = [i
];
3251 annotationCols
[dataIdx
].push(i
);
3253 hasAnnotations
= true;
3255 this.error("Only 'number' is supported as a dependent type with Gviz." +
3256 " 'string' is only supported if displayAnnotations is true");
3260 // Read column labels
3261 // TODO(danvk): add support back for errorBars
3262 var labels
= [data
.getColumnLabel(0)];
3263 for (i
= 0; i
< colIdx
.length
; i
++) {
3264 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3265 if (this.attr_("errorBars")) i
+= 1;
3267 this.attrs_
.labels
= labels
;
3268 cols
= labels
.length
;
3271 var outOfOrder
= false;
3272 var annotations
= [];
3273 for (i
= 0; i
< rows
; i
++) {
3275 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3276 data
.getValue(i
, 0) === null) {
3277 this.warn("Ignoring row " + i
+
3278 " of DataTable because of undefined or null first column.");
3282 if (indepType
== 'date' || indepType
== 'datetime') {
3283 row
.push(data
.getValue(i
, 0).getTime());
3285 row
.push(data
.getValue(i
, 0));
3287 if (!this.attr_("errorBars")) {
3288 for (j
= 0; j
< colIdx
.length
; j
++) {
3289 var col
= colIdx
[j
];
3290 row
.push(data
.getValue(i
, col
));
3291 if (hasAnnotations
&&
3292 annotationCols
.hasOwnProperty(col
) &&
3293 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3295 ann
.series
= data
.getColumnLabel(col
);
3297 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3299 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3300 if (k
) ann
.text
+= "\n";
3301 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3303 annotations
.push(ann
);
3307 // Strip out infinities, which give dygraphs problems later on.
3308 for (j
= 0; j
< row
.length
; j
++) {
3309 if (!isFinite(row
[j
])) row
[j
] = null;
3312 for (j
= 0; j
< cols
- 1; j
++) {
3313 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3316 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3323 this.warn("DataTable is out of order; order it correctly to speed loading.");
3324 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3326 this.rawData_
= ret
;
3328 if (annotations
.length
> 0) {
3329 this.setAnnotations(annotations
, true);
3331 this.attributes_
.reparseSeries();
3335 * Get the CSV data. If it's in a function, call that function. If it's in a
3336 * file, do an XMLHttpRequest to get it.
3339 Dygraph
.prototype.start_
= function() {
3340 var data
= this.file_
;
3342 // Functions can return references of all other types.
3343 if (typeof data
== 'function') {
3347 if (Dygraph
.isArrayLike(data
)) {
3348 this.rawData_
= this.parseArray_(data
);
3350 } else if (typeof data
== 'object' &&
3351 typeof data
.getColumnRange
== 'function') {
3352 // must be a DataTable from gviz.
3353 this.parseDataTable_(data
);
3355 } else if (typeof data
== 'string') {
3356 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3357 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3358 if (line_delimiter
) {
3359 this.loadedEvent_(data
);
3361 var req
= new XMLHttpRequest();
3363 req
.onreadystatechange
= function () {
3364 if (req
.readyState
== 4) {
3365 if (req
.status
=== 200 || // Normal http
3366 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3367 caller
.loadedEvent_(req
.responseText
);
3372 req
.open("GET", data
, true);
3376 this.error("Unknown data format: " + (typeof data
));
3381 * Changes various properties of the graph. These can include:
3383 * <li>file: changes the source data for the graph</li>
3384 * <li>errorBars: changes whether the data contains stddev</li>
3387 * There's a huge variety of options that can be passed to this method. For a
3388 * full list, see http://dygraphs.com/options.html.
3390 * @param {Object} attrs The new properties and values
3391 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3392 * call to updateOptions(). If you know better, you can pass true to explicitly
3393 * block the redraw. This can be useful for chaining updateOptions() calls,
3394 * avoiding the occasional infinite loop and preventing redraws when it's not
3395 * necessary (e.g. when updating a callback).
3397 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3398 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3400 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3401 var file
= input_attrs
.file
;
3402 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3404 // TODO(danvk): this is a mess. Move these options into attr_.
3405 if ('rollPeriod' in attrs
) {
3406 this.rollPeriod_
= attrs
.rollPeriod
;
3408 if ('dateWindow' in attrs
) {
3409 this.dateWindow_
= attrs
.dateWindow
;
3410 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3411 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3414 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3415 this.zoomed_y_
= (attrs
.valueRange
!== null);
3418 // TODO(danvk): validate per-series options.
3423 // highlightCircleSize
3425 // Check if this set options will require new points.
3426 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3428 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3430 this.attributes_
.reparseSeries();
3434 if (!block_redraw
) this.start_();
3436 if (!block_redraw
) {
3437 if (requiresNewPoints
) {
3440 this.renderGraph_(false);
3447 * Returns a copy of the options with deprecated names converted into current
3448 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3449 * interested in that, they should save a copy before calling this.
3452 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3454 for (var k
in attrs
) {
3455 if (k
== 'file') continue;
3456 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3459 var set
= function(axis
, opt
, value
) {
3460 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3461 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3462 my_attrs
.axes
[axis
][opt
] = value
;
3464 var map
= function(opt
, axis
, new_opt
) {
3465 if (typeof(attrs
[opt
]) != 'undefined') {
3466 Dygraph
.warn("Option " + opt
+ " is deprecated. Use the " +
3467 new_opt
+ " option for the " + axis
+ " axis instead. " +
3468 "(e.g. { axes : { " + axis
+ " : { " + new_opt
+ " : ... } } } " +
3469 "(see http://dygraphs.com/per-axis.html for more information.");
3470 set(axis
, new_opt
, attrs
[opt
]);
3471 delete my_attrs
[opt
];
3475 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3476 map('xValueFormatter', 'x', 'valueFormatter');
3477 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3478 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3479 map('xTicker', 'x', 'ticker');
3480 map('yValueFormatter', 'y', 'valueFormatter');
3481 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3482 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3483 map('yTicker', 'y', 'ticker');
3488 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3489 * containing div (which has presumably changed size since the dygraph was
3490 * instantiated. If the width/height are specified, the div will be resized.
3492 * This is far more efficient than destroying and re-instantiating a
3493 * Dygraph, since it doesn't have to reparse the underlying data.
3495 * @param {Number} [width] Width (in pixels)
3496 * @param {Number} [height] Height (in pixels)
3498 Dygraph
.prototype.resize
= function(width
, height
) {
3499 if (this.resize_lock
) {
3502 this.resize_lock
= true;
3504 if ((width
=== null) != (height
=== null)) {
3505 this.warn("Dygraph.resize() should be called with zero parameters or " +
3506 "two non-NULL parameters. Pretending it was zero.");
3507 width
= height
= null;
3510 var old_width
= this.width_
;
3511 var old_height
= this.height_
;
3514 this.maindiv_
.style
.width
= width
+ "px";
3515 this.maindiv_
.style
.height
= height
+ "px";
3516 this.width_
= width
;
3517 this.height_
= height
;
3519 this.width_
= this.maindiv_
.clientWidth
;
3520 this.height_
= this.maindiv_
.clientHeight
;
3523 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3524 // TODO(danvk): there should be a clear() method.
3525 this.maindiv_
.innerHTML
= "";
3526 this.roller_
= null;
3527 this.attrs_
.labelsDiv
= null;
3528 this.createInterface_();
3529 if (this.annotations_
.length
) {
3530 // createInterface_ reset the layout, so we need to do this.
3531 this.layout_
.setAnnotations(this.annotations_
);
3533 this.createDragInterface_();
3537 this.resize_lock
= false;
3541 * Adjusts the number of points in the rolling average. Updates the graph to
3542 * reflect the new averaging period.
3543 * @param {Number} length Number of points over which to average the data.
3545 Dygraph
.prototype.adjustRoll
= function(length
) {
3546 this.rollPeriod_
= length
;
3551 * Returns a boolean array of visibility statuses.
3553 Dygraph
.prototype.visibility
= function() {
3554 // Do lazy-initialization, so that this happens after we know the number of
3556 if (!this.attr_("visibility")) {
3557 this.attrs_
.visibility
= [];
3559 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3560 while (this.attr_("visibility").length
< this.numColumns() - 1) {
3561 this.attrs_
.visibility
.push(true);
3563 return this.attr_("visibility");
3567 * Changes the visiblity of a series.
3569 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3570 var x
= this.visibility();
3571 if (num
< 0 || num
>= x
.length
) {
3572 this.warn("invalid series number in setVisibility: " + num
);
3580 * How large of an area will the dygraph render itself in?
3581 * This is used for testing.
3582 * @return A {width: w, height: h} object.
3585 Dygraph
.prototype.size
= function() {
3586 return { width
: this.width_
, height
: this.height_
};
3590 * Update the list of annotations and redraw the chart.
3591 * See dygraphs.com/annotations.html for more info on how to use annotations.
3592 * @param ann {Array} An array of annotation objects.
3593 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3595 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3596 // Only add the annotation CSS rule once we know it will be used.
3597 Dygraph
.addAnnotationRule();
3598 this.annotations_
= ann
;
3599 this.layout_
.setAnnotations(this.annotations_
);
3600 if (!suppressDraw
) {
3606 * Return the list of annotations.
3608 Dygraph
.prototype.annotations
= function() {
3609 return this.annotations_
;
3613 * Get the list of label names for this graph. The first column is the
3614 * x-axis, so the data series names start at index 1.
3616 * Returns null when labels have not yet been defined.
3618 Dygraph
.prototype.getLabels
= function() {
3619 var labels
= this.attr_("labels");
3620 return labels
? labels
.slice() : null;
3624 * Get the index of a series (column) given its name. The first column is the
3625 * x-axis, so the data series start with index 1.
3627 Dygraph
.prototype.indexFromSetName
= function(name
) {
3628 return this.setIndexByName_
[name
];
3632 * Get the internal dataset index given its name. These are numbered starting from 0,
3633 * and only count visible sets.
3636 Dygraph
.prototype.datasetIndexFromSetName_
= function(name
) {
3637 return this.datasetIndex_
[this.indexFromSetName(name
)];
3642 * Adds a default style for the annotation CSS classes to the document. This is
3643 * only executed when annotations are actually used. It is designed to only be
3644 * called once -- all calls after the first will return immediately.
3646 Dygraph
.addAnnotationRule
= function() {
3647 // TODO(danvk): move this function into plugins/annotations.js
?
3648 if (Dygraph
.addedAnnotationCSS
) return;
3650 var rule
= "border: 1px solid black; " +
3651 "background-color: white; " +
3652 "text-align: center;";
3654 var styleSheetElement
= document
.createElement("style");
3655 styleSheetElement
.type
= "text/css";
3656 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3658 // Find the first style sheet that we can access.
3659 // We may not add a rule to a style sheet from another domain for security
3660 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3661 // adds its own style sheets from google.com.
3662 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3663 if (document
.styleSheets
[i
].disabled
) continue;
3664 var mysheet
= document
.styleSheets
[i
];
3666 if (mysheet
.insertRule
) { // Firefox
3667 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3668 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3669 } else if (mysheet
.addRule
) { // IE
3670 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3672 Dygraph
.addedAnnotationCSS
= true;
3675 // Was likely a security exception.
3679 this.warn("Unable to add default annotation CSS rule; display may be off.");
3682 // Older pages may still use this name.
3683 var DateGraph
= Dygraph
;