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 // Label constants for the labelsKMB and labelsKMG2 options.
99 // (i.e. '100000' -> '100K')
100 Dygraph
.KMB_LABELS
= [ 'K', 'M', 'B', 'T', 'Q' ];
101 Dygraph
.KMG2_BIG_LABELS
= [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
102 Dygraph
.KMG2_SMALL_LABELS
= [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
104 // These are defined before DEFAULT_ATTRS so that it can refer to them.
107 * Return a string version of a number. This respects the digitsAfterDecimal
108 * and maxNumberWidth options.
109 * @param {Number} x The number to be formatted
110 * @param {Dygraph} opts An options view
111 * @param {String} name The name of the point's data series
112 * @param {Dygraph} g The dygraph object
114 Dygraph
.numberValueFormatter
= function(x
, opts
, pt
, g
) {
115 var sigFigs
= opts('sigFigs');
117 if (sigFigs
!== null) {
118 // User has opted for a fixed number of significant figures.
119 return Dygraph
.floatFormat(x
, sigFigs
);
122 var digits
= opts('digitsAfterDecimal');
123 var maxNumberWidth
= opts('maxNumberWidth');
125 var kmb
= opts('labelsKMB');
126 var kmg2
= opts('labelsKMG2');
130 // switch to scientific notation if we underflow or overflow fixed display.
132 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
133 Math
.abs(x
) < Math
.pow(10, -digits
))) {
134 label
= x
.toExponential(digits
);
136 label
= '' + Dygraph
.round_(x
, digits
);
145 k_labels
= Dygraph
.KMB_LABELS
;
148 if (kmb
) Dygraph
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
150 k_labels
= Dygraph
.KMG2_BIG_LABELS
;
151 m_labels
= Dygraph
.KMG2_SMALL_LABELS
;
154 var absx
= Math
.abs(x
);
155 var n
= Dygraph
.pow(k
, k_labels
.length
);
156 for (var j
= k_labels
.length
- 1; j
>= 0; j
--, n
/= k
) {
158 label
= Dygraph
.round_(x
/ n
, digits
) + k_labels
[j
];
163 // TODO(danvk): clean up this logic. Why so different than kmb?
164 var x_parts
= String(x
.toExponential()).split('e-');
165 if (x_parts
.length
=== 2 && x_parts
[1] >= 3 && x_parts
[1] <= 24) {
166 if (x_parts
[1] % 3 > 0) {
167 label
= Dygraph
.round_(x_parts
[0] /
168 Dygraph
.pow(10, (x_parts
[1] % 3)),
171 label
= Number(x_parts
[0]).toFixed(2);
173 label
+= m_labels
[Math
.floor(x_parts
[1] / 3) - 1];
182 * variant for use as an axisLabelFormatter.
185 Dygraph
.numberAxisLabelFormatter
= function(x
, granularity
, opts
, g
) {
186 return Dygraph
.numberValueFormatter(x
, opts
, g
);
190 * Convert a JS date (millis since epoch) to YYYY/MM/DD
191 * @param {Number} date The JavaScript date (ms since epoch)
192 * @return {String} A date of the form "YYYY/MM/DD"
195 Dygraph
.dateString_
= function(date
) {
196 var zeropad
= Dygraph
.zeropad
;
197 var d
= new Date(date
);
200 var year
= "" + d
.getFullYear();
201 // Get a 0 padded month string
202 var month
= zeropad(d
.getMonth() + 1); //months are 0-offset, sigh
203 // Get a 0 padded day string
204 var day
= zeropad(d
.getDate());
207 var frac
= d
.getHours() * 3600 + d
.getMinutes() * 60 + d
.getSeconds();
208 if (frac
) ret
= " " + Dygraph
.hmsString_(date
);
210 return year
+ "/" + month + "/" + day
+ ret
;
214 * Convert a JS date to a string appropriate to display on an axis that
215 * is displaying values at the stated granularity.
216 * @param {Date} date The date to format
217 * @param {Number} granularity One of the Dygraph granularity constants
218 * @return {String} The formatted date
221 Dygraph
.dateAxisFormatter
= function(date
, granularity
) {
222 if (granularity
>= Dygraph
.DECADAL
) {
223 return date
.strftime('%Y');
224 } else if (granularity
>= Dygraph
.MONTHLY
) {
225 return date
.strftime('%b %y');
227 var frac
= date
.getHours() * 3600 + date
.getMinutes() * 60 + date
.getSeconds() + date
.getMilliseconds();
228 if (frac
=== 0 || granularity
>= Dygraph
.DAILY
) {
229 return new Date(date
.getTime() + 3600*1000).strftime('%d%b');
231 return Dygraph
.hmsString_(date
.getTime());
237 * Standard plotters. These may be used by clients.
238 * Available plotters are:
239 * - Dygraph.Plotters.linePlotter: draws central lines (most common)
240 * - Dygraph.Plotters.errorPlotter: draws error bars
241 * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph)
243 * By default, the plotter is [fillPlotter, errorPlotter, linePlotter].
244 * This causes all the lines to be drawn over all the fills/error bars.
246 Dygraph
.Plotters
= DygraphCanvasRenderer
._Plotters
;
249 // Default attribute values.
250 Dygraph
.DEFAULT_ATTRS
= {
251 highlightCircleSize
: 3,
252 highlightSeriesOpts
: null,
253 highlightSeriesBackgroundAlpha
: 0.5,
257 // TODO(danvk): move defaults from createStatusMessage_ here.
259 labelsSeparateLines
: false,
260 labelsShowZeroValues
: true,
263 showLabelsOnHighlight
: true,
265 digitsAfterDecimal
: 2,
270 strokeBorderWidth
: 0,
271 strokeBorderColor
: "white",
274 axisLabelFontSize
: 14,
280 xValueParser
: Dygraph
.dateParser
,
287 wilsonInterval
: true, // only relevant if fractions is true
291 connectSeparatedPoints
: false,
294 hideOverlayOnMouseOut
: true,
296 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
297 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
303 drawAxesAtZero
: false,
305 // Sizes of the various chart labels.
312 axisLineColor
: "black",
315 axisLabelColor
: "black",
316 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
320 gridLineColor
: "rgb(128,128,128)",
322 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
323 animatedZooms
: false, // (for now)
325 // Range selector options
326 showRangeSelector
: false,
327 rangeSelectorHeight
: 40,
328 rangeSelectorPlotStrokeColor
: "#808FAB",
329 rangeSelectorPlotFillColor
: "#A7B1C4",
331 // The ordering here ensures that central lines always appear above any
332 // fill bars/error bars
.
334 Dygraph
.Plotters
.fillPlotter
,
335 Dygraph
.Plotters
.errorPlotter
,
336 Dygraph
.Plotters
.linePlotter
345 axisLabelFormatter
: Dygraph
.dateAxisFormatter
,
346 valueFormatter
: Dygraph
.dateString_
,
347 ticker
: null // will be set in dygraph-tickers.js
351 valueFormatter
: Dygraph
.numberValueFormatter
,
352 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
353 ticker
: null // will be set in dygraph-tickers.js
357 valueFormatter
: Dygraph
.numberValueFormatter
,
358 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
359 ticker
: null // will be set in dygraph-tickers.js
364 // Directions for panning and zooming. Use bit operations when combined
365 // values are possible.
366 Dygraph
.HORIZONTAL
= 1;
367 Dygraph
.VERTICAL
= 2;
369 // Installed plugins, in order of precedence (most-general to most-specific).
370 // Plugins are installed after they are defined, in plugins/install.js
.
374 // Used for initializing annotation CSS rules only once.
375 Dygraph
.addedAnnotationCSS
= false;
377 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
378 // Labels is no longer a constructor parameter, since it's typically set
379 // directly from the data source. It also conains a name for the x-axis,
380 // which the previous constructor form did not.
381 if (labels
!== null) {
382 var new_labels
= ["Date"];
383 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
384 Dygraph
.update(attrs
, { 'labels': new_labels
});
386 this.__init__(div
, file
, attrs
);
390 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
391 * and context <canvas> inside of it. See the constructor for details.
393 * @param {Element} div the Element to render the graph into.
394 * @param {String | Function} file Source data
395 * @param {Object} attrs Miscellaneous other options
398 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
399 // Hack for IE: if we're using excanvas and the document hasn't finished
400 // loading yet (and hence may not have initialized whatever it needs to
401 // initialize), then keep calling this routine periodically until it has.
402 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
403 typeof(G_vmlCanvasManager
) != 'undefined' &&
404 document
.readyState
!= 'complete') {
406 setTimeout(function() { self
.__init__(div
, file
, attrs
); }, 100);
410 // Support two-argument constructor
411 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
413 attrs
= Dygraph
.mapLegacyOptions_(attrs
);
415 if (typeof(div
) == 'string') {
416 div
= document
.getElementById(div
);
420 Dygraph
.error("Constructing dygraph with a non-existent div!");
424 this.isUsingExcanvas_
= typeof(G_vmlCanvasManager
) != 'undefined';
426 // Copy the important bits into the object
427 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
430 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
431 this.previousVerticalX_
= -1;
432 this.fractions_
= attrs
.fractions
|| false;
433 this.dateWindow_
= attrs
.dateWindow
|| null;
435 this.is_initial_draw_
= true;
436 this.annotations_
= [];
438 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
439 this.zoomed_x_
= false;
440 this.zoomed_y_
= false;
442 // Clear the div. This ensure that, if multiple dygraphs are passed the same
443 // div, then only one will be drawn.
446 // For historical reasons, the 'width' and 'height' options trump all CSS
447 // rules _except_ for an explicit 'width' or 'height' on the div.
448 // As an added convenience, if the div has zero height (like <div></div> does
449 // without any styles), then we use a default height/width
.
450 if (div
.style
.width
=== '' && attrs
.width
) {
451 div
.style
.width
= attrs
.width
+ "px";
453 if (div
.style
.height
=== '' && attrs
.height
) {
454 div
.style
.height
= attrs
.height
+ "px";
456 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
457 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
458 if (div
.style
.width
=== '') {
459 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
462 // these will be zero if the dygraph's div is hidden.
463 this.width_
= div
.clientWidth
;
464 this.height_
= div
.clientHeight
;
466 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
467 if (attrs
.stackedGraph
) {
468 attrs
.fillGraph
= true;
469 // TODO(nikhilk): Add any other stackedGraph checks here.
472 // DEPRECATION WARNING: All option processing should be moved from
473 // attrs_ and user_attrs_ to options_, which holds all this information.
475 // Dygraphs has many options, some of which interact with one another.
476 // To keep track of everything, we maintain two sets of options:
478 // this.user_attrs_ only options explicitly set by the user.
479 // this.attrs_ defaults, options derived from user_attrs_, data.
481 // Options are then accessed this.attr_('attr'), which first looks at
482 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
483 // defaults without overriding behavior that the user specifically asks for.
484 this.user_attrs_
= {};
485 Dygraph
.update(this.user_attrs_
, attrs
);
487 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
489 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
491 this.boundaryIds_
= [];
492 this.setIndexByName_
= {};
493 this.datasetIndex_
= [];
495 this.registeredEvents_
= [];
496 this.eventListeners_
= {};
498 this.attributes_
= new DygraphOptions(this);
500 // Create the containing DIV and other interactive elements
501 this.createInterface_();
505 var plugins
= Dygraph
.PLUGINS
.concat(this.getOption('plugins'));
506 for (var i
= 0; i
< plugins
.length
; i
++) {
507 var Plugin
= plugins
[i
];
508 var pluginInstance
= new Plugin();
510 plugin
: pluginInstance
,
516 var handlers
= pluginInstance
.activate(this);
517 for (var eventName
in handlers
) {
518 // TODO(danvk): validate eventName.
519 pluginDict
.events
[eventName
] = handlers
[eventName
];
522 this.plugins_
.push(pluginDict
);
525 // At this point, plugins can no longer register event handlers.
526 // Construct a map from event -> ordered list of [callback, plugin].
527 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
528 var plugin_dict
= this.plugins_
[i
];
529 for (var eventName
in plugin_dict
.events
) {
530 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
531 var callback
= plugin_dict
.events
[eventName
];
533 var pair
= [plugin_dict
.plugin
, callback
];
534 if (!(eventName
in this.eventListeners_
)) {
535 this.eventListeners_
[eventName
] = [pair
];
537 this.eventListeners_
[eventName
].push(pair
);
542 this.createDragInterface_();
548 * Triggers a cascade of events to the various plugins which are interested in them.
549 * Returns true if the "default behavior" should be performed, i.e. if none of
550 * the event listeners called event.preventDefault().
553 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
554 if (!(name
in this.eventListeners_
)) return true;
556 // QUESTION: can we use objects & prototypes to speed this up?
560 defaultPrevented
: false,
561 preventDefault
: function() {
562 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
563 e
.defaultPrevented
= true;
565 propagationStopped
: false,
566 stopPropagation
: function() {
567 e
.propagationStopped
= true;
570 Dygraph
.update(e
, extra_props
);
572 var callback_plugin_pairs
= this.eventListeners_
[name
];
573 if (callback_plugin_pairs
) {
574 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
575 var plugin
= callback_plugin_pairs
[i
][0];
576 var callback
= callback_plugin_pairs
[i
][1];
577 callback
.call(plugin
, e
);
578 if (e
.propagationStopped
) break;
581 return e
.defaultPrevented
;
585 * Returns the zoomed status of the chart for one or both axes.
587 * Axis is an optional parameter. Can be set to 'x' or 'y'.
589 * The zoomed status for an axis is set whenever a user zooms using the mouse
590 * or when the dateWindow or valueRange are updated (unless the
591 * isZoomedIgnoreProgrammaticZoom option is also specified).
593 Dygraph
.prototype.isZoomed
= function(axis
) {
594 if (axis
=== null || axis
=== undefined
) {
595 return this.zoomed_x_
|| this.zoomed_y_
;
597 if (axis
=== 'x') return this.zoomed_x_
;
598 if (axis
=== 'y') return this.zoomed_y_
;
599 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
603 * Returns information about the Dygraph object, including its containing ID.
605 Dygraph
.prototype.toString
= function() {
606 var maindiv
= this.maindiv_
;
607 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
608 return "[Dygraph " + id
+ "]";
613 * Returns the value of an option. This may be set by the user (either in the
614 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
616 * @param { String } name The name of the option, e.g. 'rollPeriod'.
617 * @param { String } [seriesName] The name of the series to which the option
618 * will be applied. If no per-series value of this option is available, then
619 * the global value is returned. This is optional.
620 * @return { ... } The value of the option.
622 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
623 // <REMOVE_FOR_COMBINED>
624 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
625 this.error('Must include options reference JS for testing');
626 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
627 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
628 'in the Dygraphs.OPTIONS_REFERENCE listing.');
629 // Only log this error once.
630 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
632 // </REMOVE_FOR_COMBINED
>
633 return seriesName
? this.attributes_
.getForSeries(name
, seriesName
) : this.attributes_
.get(name
);
637 * Returns the current value for an option, as set in the constructor or via
638 * updateOptions. You may pass in an (optional) series name to get per-series
639 * values for the option.
641 * All values returned by this method should be considered immutable. If you
642 * modify them, there is no guarantee that the changes will be honored or that
643 * dygraphs will remain in a consistent state. If you want to modify an option,
644 * use updateOptions() instead.
646 * @param { String } name The name of the option (e.g. 'strokeWidth')
647 * @param { String } [opt_seriesName] Series name to get per-series values.
648 * @return { ... } The value of the option.
650 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
651 return this.attr_(name
, opt_seriesName
);
654 Dygraph
.prototype.getOptionForAxis
= function(name
, axis
) {
655 return this.attributes_
.getForAxis(name
, axis
);
660 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
661 * @return { ... } A function mapping string -> option value
663 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
665 return function(opt
) {
666 var axis_opts
= self
.user_attrs_
.axes
;
667 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
668 return axis_opts
[axis
][opt
];
670 // user-specified attributes always trump defaults, even if they're less
672 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
673 return self
.user_attrs_
[opt
];
676 axis_opts
= self
.attrs_
.axes
;
677 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
678 return axis_opts
[axis
][opt
];
680 // check old-style axis options
681 // TODO(danvk): add a deprecation warning if either of these match.
682 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
683 return self
.axes_
[0][opt
];
684 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
685 return self
.axes_
[1][opt
];
687 return self
.attr_(opt
);
692 * Returns the current rolling period, as set by the user or an option.
693 * @return {Number} The number of points in the rolling window
695 Dygraph
.prototype.rollPeriod
= function() {
696 return this.rollPeriod_
;
700 * Returns the currently-visible x-range. This can be affected by zooming,
701 * panning or a call to updateOptions.
702 * Returns a two-element array: [left, right].
703 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
705 Dygraph
.prototype.xAxisRange
= function() {
706 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
710 * Returns the lower- and upper-bound x-axis values of the
713 Dygraph
.prototype.xAxisExtremes
= function() {
714 var pad
= this.attr_('xRangePad') / this.plotter_
.area
.w
;
715 if (this.numRows() === 0) {
716 return [0 - pad
, 1 + pad
];
718 var left
= this.rawData_
[0][0];
719 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
721 // Must keep this in sync with dygraph-layout _evaluateLimits()
722 var range
= right
- left
;
724 right
+= range
* pad
;
726 return [left
, right
];
730 * Returns the currently-visible y-range for an axis. This can be affected by
731 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
732 * called with no arguments, returns the range of the first axis.
733 * Returns a two-element array: [bottom, top].
735 Dygraph
.prototype.yAxisRange
= function(idx
) {
736 if (typeof(idx
) == "undefined") idx
= 0;
737 if (idx
< 0 || idx
>= this.axes_
.length
) {
740 var axis
= this.axes_
[idx
];
741 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
745 * Returns the currently-visible y-ranges for each axis. This can be affected by
746 * zooming, panning, calls to updateOptions, etc.
747 * Returns an array of [bottom, top] pairs, one for each y-axis.
749 Dygraph
.prototype.yAxisRanges
= function() {
751 for (var i
= 0; i
< this.axes_
.length
; i
++) {
752 ret
.push(this.yAxisRange(i
));
757 // TODO(danvk): use these functions throughout dygraphs.
759 * Convert from data coordinates to canvas/div X/Y coordinates.
760 * If specified, do this conversion for the coordinate system of a particular
761 * axis. Uses the first axis by default.
762 * Returns a two-element array: [X, Y]
764 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
765 * instead of toDomCoords(null, y, axis).
767 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
768 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
772 * Convert from data x coordinates to canvas/div X coordinate.
773 * If specified, do this conversion for the coordinate system of a particular
775 * Returns a single value or null if x is null.
777 Dygraph
.prototype.toDomXCoord
= function(x
) {
782 var area
= this.plotter_
.area
;
783 var xRange
= this.xAxisRange();
784 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
788 * Convert from data x coordinates to canvas/div Y coordinate and optional
789 * axis. Uses the first axis by default.
791 * returns a single value or null if y is null.
793 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
794 var pct
= this.toPercentYCoord(y
, axis
);
799 var area
= this.plotter_
.area
;
800 return area
.y
+ pct
* area
.h
;
804 * Convert from canvas/div coords to data coordinates.
805 * If specified, do this conversion for the coordinate system of a particular
806 * axis. Uses the first axis by default.
807 * Returns a two-element array: [X, Y].
809 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
810 * instead of toDataCoords(null, y, axis).
812 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
813 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
817 * Convert from canvas/div x coordinate to data coordinate.
819 * If x is null, this returns null.
821 Dygraph
.prototype.toDataXCoord
= function(x
) {
826 var area
= this.plotter_
.area
;
827 var xRange
= this.xAxisRange();
828 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
832 * Convert from canvas/div y coord to value.
834 * If y is null, this returns null.
835 * if axis is null, this uses the first axis.
837 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
842 var area
= this.plotter_
.area
;
843 var yRange
= this.yAxisRange(axis
);
845 if (typeof(axis
) == "undefined") axis
= 0;
846 if (!this.axes_
[axis
].logscale
) {
847 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
849 // Computing the inverse of toDomCoord.
850 var pct
= (y
- area
.y
) / area
.h
;
852 // Computing the inverse of toPercentYCoord. The function was arrived at with
853 // the following steps:
855 // Original calcuation:
856 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
858 // Move denominator to both sides:
859 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
861 // subtract logr1, and take the negative value.
862 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
864 // Swap both sides of the equation, and we can compute the log of the
865 // return value. Which means we just need to use that as the exponent in
867 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
869 var logr1
= Dygraph
.log10(yRange
[1]);
870 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
871 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
877 * Converts a y for an axis to a percentage from the top to the
878 * bottom of the drawing area.
880 * If the coordinate represents a value visible on the canvas, then
881 * the value will be between 0 and 1, where 0 is the top of the canvas.
882 * However, this method will return values outside the range, as
883 * values can fall outside the canvas.
885 * If y is null, this returns null.
886 * if axis is null, this uses the first axis.
888 * @param { Number } y The data y-coordinate.
889 * @param { Number } [axis] The axis number on which the data coordinate lives.
890 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
892 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
896 if (typeof(axis
) == "undefined") axis
= 0;
898 var yRange
= this.yAxisRange(axis
);
901 var logscale
= this.attributes_
.getForAxis("logscale", axis
);
903 // yRange[1] - y is unit distance from the bottom.
904 // yRange[1] - yRange[0] is the scale of the range.
905 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
906 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
908 var logr1
= Dygraph
.log10(yRange
[1]);
909 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
915 * Converts an x value to a percentage from the left to the right of
918 * If the coordinate represents a value visible on the canvas, then
919 * the value will be between 0 and 1, where 0 is the left of the canvas.
920 * However, this method will return values outside the range, as
921 * values can fall outside the canvas.
923 * If x is null, this returns null.
924 * @param { Number } x The data x-coordinate.
925 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
927 Dygraph
.prototype.toPercentXCoord
= function(x
) {
932 var xRange
= this.xAxisRange();
933 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
937 * Returns the number of columns (including the independent variable).
938 * @return { Integer } The number of columns.
940 Dygraph
.prototype.numColumns
= function() {
941 if (!this.rawData_
) return 0;
942 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
946 * Returns the number of rows (excluding any header/label row).
947 * @return { Integer } The number of rows, less any header.
949 Dygraph
.prototype.numRows
= function() {
950 if (!this.rawData_
) return 0;
951 return this.rawData_
.length
;
955 * Returns the value in the given row and column. If the row and column exceed
956 * the bounds on the data, returns null. Also returns null if the value is
958 * @param { Number} row The row number of the data (0-based). Row 0 is the
959 * first row of data, not a header row.
960 * @param { Number} col The column number of the data (0-based)
961 * @return { Number } The value in the specified cell or null if the row/col
964 Dygraph
.prototype.getValue
= function(row
, col
) {
965 if (row
< 0 || row
> this.rawData_
.length
) return null;
966 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
968 return this.rawData_
[row
][col
];
972 * Generates interface elements for the Dygraph: a containing div, a div to
973 * display the current point, and a textbox to adjust the rolling average
974 * period. Also creates the Renderer/Layout elements.
977 Dygraph
.prototype.createInterface_
= function() {
978 // Create the all-enclosing graph div
979 var enclosing
= this.maindiv_
;
981 this.graphDiv
= document
.createElement("div");
982 this.graphDiv
.style
.width
= this.width_
+ "px";
983 this.graphDiv
.style
.height
= this.height_
+ "px";
984 // TODO(danvk): any other styles that are useful to set here?
985 this.graphDiv
.style
.textAlign
= 'left'; // This is a CSS "reset"
986 enclosing
.appendChild(this.graphDiv
);
988 // Create the canvas for interactive parts of the chart.
989 this.canvas_
= Dygraph
.createCanvas();
990 this.canvas_
.style
.position
= "absolute";
991 this.canvas_
.width
= this.width_
;
992 this.canvas_
.height
= this.height_
;
993 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
994 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
996 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
998 // ... and for static parts of the chart.
999 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
1000 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
1002 // The interactive parts of the graph are drawn on top of the chart.
1003 this.graphDiv
.appendChild(this.hidden_
);
1004 this.graphDiv
.appendChild(this.canvas_
);
1005 this.mouseEventElement_
= this.createMouseEventElement_();
1007 // Create the grapher
1008 this.layout_
= new DygraphLayout(this);
1012 this.mouseMoveHandler_
= function(e
) {
1013 dygraph
.mouseMove_(e
);
1016 this.mouseOutHandler_
= function(e
) {
1017 // The mouse has left the chart if:
1018 // 1. e.target is inside the chart
1019 // 2. e.relatedTarget is outside the chart
1020 var target
= e
.target
|| e
.fromElement
;
1021 var relatedTarget
= e
.relatedTarget
|| e
.toElement
;
1022 if (Dygraph
.isElementContainedBy(target
, dygraph
.graphDiv
) &&
1023 !Dygraph
.isElementContainedBy(relatedTarget
, dygraph
.graphDiv
)) {
1024 dygraph
.mouseOut_(e
);
1028 this.addEvent(window
, 'mouseout', this.mouseOutHandler_
);
1029 this.addEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1031 // Don't recreate and register the resize handler on subsequent calls.
1032 // This happens when the graph is resized.
1033 if (!this.resizeHandler_
) {
1034 this.resizeHandler_
= function(e
) {
1038 // Update when the window is resized.
1039 // TODO(danvk): drop frames depending on complexity of the chart.
1040 this.addEvent(window
, 'resize', this.resizeHandler_
);
1045 * Detach DOM elements in the dygraph and null out all data references.
1046 * Calling this when you're done with a dygraph can dramatically reduce memory
1047 * usage. See, e.g., the tests/perf.html example.
1049 Dygraph
.prototype.destroy
= function() {
1050 var removeRecursive
= function(node
) {
1051 while (node
.hasChildNodes()) {
1052 removeRecursive(node
.firstChild
);
1053 node
.removeChild(node
.firstChild
);
1057 if (this.registeredEvents_
) {
1058 for (var idx
= 0; idx
< this.registeredEvents_
.length
; idx
++) {
1059 var reg
= this.registeredEvents_
[idx
];
1060 Dygraph
.removeEvent(reg
.elem
, reg
.type
, reg
.fn
);
1064 this.registeredEvents_
= [];
1066 // remove mouse event handlers (This may not be necessary anymore)
1067 Dygraph
.removeEvent(window
, 'mouseout', this.mouseOutHandler_
);
1068 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1069 Dygraph
.removeEvent(this.mouseEventElement_
, 'mouseup', this.mouseUpHandler_
);
1071 // remove window handlers
1072 Dygraph
.removeEvent(window
,'resize',this.resizeHandler_
);
1073 this.resizeHandler_
= null;
1075 removeRecursive(this.maindiv_
);
1077 var nullOut
= function(obj
) {
1078 for (var n
in obj
) {
1079 if (typeof(obj
[n
]) === 'object') {
1084 // These may not all be necessary, but it can't hurt...
1085 nullOut(this.layout_
);
1086 nullOut(this.plotter_
);
1091 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1092 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1093 * or the zoom rectangles) is done on this.canvas_.
1094 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1095 * @return {Object} The newly-created canvas
1098 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1099 var h
= Dygraph
.createCanvas();
1100 h
.style
.position
= "absolute";
1101 // TODO(danvk): h should be offset from canvas. canvas needs to include
1102 // some extra area to make it easier to zoom in on the far left and far
1103 // right. h needs to be precisely the plot area, so that clipping occurs.
1104 h
.style
.top
= canvas
.style
.top
;
1105 h
.style
.left
= canvas
.style
.left
;
1106 h
.width
= this.width_
;
1107 h
.height
= this.height_
;
1108 h
.style
.width
= this.width_
+ "px"; // for IE
1109 h
.style
.height
= this.height_
+ "px"; // for IE
1114 * Creates an overlay element used to handle mouse events.
1115 * @return {Object} The mouse event element.
1118 Dygraph
.prototype.createMouseEventElement_
= function() {
1119 if (this.isUsingExcanvas_
) {
1120 var elem
= document
.createElement("div");
1121 elem
.style
.position
= 'absolute';
1122 elem
.style
.backgroundColor
= 'white';
1123 elem
.style
.filter
= 'alpha(opacity=0)';
1124 elem
.style
.width
= this.width_
+ "px";
1125 elem
.style
.height
= this.height_
+ "px";
1126 this.graphDiv
.appendChild(elem
);
1129 return this.canvas_
;
1134 * Generate a set of distinct colors for the data series. This is done with a
1135 * color wheel. Saturation/Value are customizable, and the hue is
1136 * equally-spaced around the color wheel. If a custom set of colors is
1137 * specified, that is used instead.
1140 Dygraph
.prototype.setColors_
= function() {
1141 var labels
= this.getLabels();
1142 var num
= labels
.length
- 1;
1144 this.colorsMap_
= {};
1145 var colors
= this.attr_('colors');
1148 var sat
= this.attr_('colorSaturation') || 1.0;
1149 var val
= this.attr_('colorValue') || 0.5;
1150 var half
= Math
.ceil(num
/ 2);
1151 for (i
= 1; i
<= num
; i
++) {
1152 if (!this.visibility()[i
-1]) continue;
1153 // alternate colors for high contrast.
1154 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
1155 var hue
= (1.0 * idx
/ (1 + num
));
1156 var colorStr
= Dygraph
.hsvToRGB(hue
, sat
, val
);
1157 this.colors_
.push(colorStr
);
1158 this.colorsMap_
[labels
[i
]] = colorStr
;
1161 for (i
= 0; i
< num
; i
++) {
1162 if (!this.visibility()[i
]) continue;
1163 var colorStr
= colors
[i
% colors
.length
];
1164 this.colors_
.push(colorStr
);
1165 this.colorsMap_
[labels
[1 + i
]] = colorStr
;
1171 * Return the list of colors. This is either the list of colors passed in the
1172 * attributes or the autogenerated list of rgb(r,g,b) strings.
1173 * This does not return colors for invisible series.
1174 * @return {Array<string>} The list of colors.
1176 Dygraph
.prototype.getColors
= function() {
1177 return this.colors_
;
1181 * Returns a few attributes of a series, i.e. its color, its visibility, which
1182 * axis it's assigned to, and its column in the original data.
1183 * Returns null if the series does not exist.
1184 * Otherwise, returns an object with column, visibility, color and axis properties.
1185 * The "axis" property will be set to 1 for y1 and 2 for y2.
1186 * The "column" property can be fed back into getValue(row, column) to get
1187 * values for this series.
1189 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1191 var labels
= this.getLabels();
1192 for (var i
= 1; i
< labels
.length
; i
++) {
1193 if (labels
[i
] == series_name
) {
1198 if (idx
== -1) return null;
1203 visible
: this.visibility()[idx
- 1],
1204 color
: this.colorsMap_
[series_name
],
1205 axis
: 1 + this.attributes_
.axisForSeries(series_name
)
1210 * Create the text box to adjust the averaging period
1213 Dygraph
.prototype.createRollInterface_
= function() {
1214 // Create a roller if one doesn't exist already.
1215 if (!this.roller_
) {
1216 this.roller_
= document
.createElement("input");
1217 this.roller_
.type
= "text";
1218 this.roller_
.style
.display
= "none";
1219 this.graphDiv
.appendChild(this.roller_
);
1222 var display
= this.attr_('showRoller') ? 'block' : 'none';
1224 var area
= this.plotter_
.area
;
1225 var textAttr
= { "position": "absolute",
1227 "top": (area
.y
+ area
.h
- 25) + "px",
1228 "left": (area
.x
+ 1) + "px",
1231 this.roller_
.size
= "2";
1232 this.roller_
.value
= this.rollPeriod_
;
1233 for (var name
in textAttr
) {
1234 if (textAttr
.hasOwnProperty(name
)) {
1235 this.roller_
.style
[name
] = textAttr
[name
];
1240 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1245 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1246 * canvas (i.e. DOM Coords).
1248 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1249 return Dygraph
.pageX(e
) - context
.px
;
1254 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1255 * canvas (i.e. DOM Coords).
1257 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1258 return Dygraph
.pageY(e
) - context
.py
;
1262 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1266 Dygraph
.prototype.createDragInterface_
= function() {
1268 // Tracks whether the mouse is down right now
1270 isPanning
: false, // is this drag part of a pan?
1271 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1272 dragStartX
: null, // pixel coordinates
1273 dragStartY
: null, // pixel coordinates
1274 dragEndX
: null, // pixel coordinates
1275 dragEndY
: null, // pixel coordinates
1276 dragDirection
: null,
1277 prevEndX
: null, // pixel coordinates
1278 prevEndY
: null, // pixel coordinates
1279 prevDragDirection
: null,
1280 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1282 // The value on the left side of the graph when a pan operation starts.
1283 initialLeftmostDate
: null,
1285 // The number of units each pixel spans. (This won't be valid for log
1287 xUnitsPerPixel
: null,
1289 // TODO(danvk): update this comment
1290 // The range in second/value units that the viewport encompasses during a
1291 // panning operation.
1294 // Top-left corner of the canvas, in DOM coords
1295 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1299 // Values for use with panEdgeFraction, which limit how far outside the
1300 // graph's data boundaries it can be panned.
1301 boundedDates
: null, // [minDate, maxDate]
1302 boundedValues
: null, // [[minValue, maxValue] ...]
1304 // We cover iframes during mouse interactions. See comments in
1305 // dygraph-utils.js for more info on why this is a good idea.
1306 tarp
: new Dygraph
.IFrameTarp(),
1308 // contextB is the same thing as this context object but renamed.
1309 initializeMouseDown
: function(event
, g
, contextB
) {
1310 // prevents mouse drags from selecting page text.
1311 if (event
.preventDefault
) {
1312 event
.preventDefault(); // Firefox, Chrome, etc.
1314 event
.returnValue
= false; // IE
1315 event
.cancelBubble
= true;
1318 contextB
.px
= Dygraph
.findPosX(g
.canvas_
);
1319 contextB
.py
= Dygraph
.findPosY(g
.canvas_
);
1320 contextB
.dragStartX
= g
.dragGetX_(event
, contextB
);
1321 contextB
.dragStartY
= g
.dragGetY_(event
, contextB
);
1322 contextB
.cancelNextDblclick
= false;
1323 contextB
.tarp
.cover();
1327 var interactionModel
= this.attr_("interactionModel");
1329 // Self is the graph.
1332 // Function that binds the graph and context to the handler.
1333 var bindHandler
= function(handler
) {
1334 return function(event
) {
1335 handler(event
, self
, context
);
1339 for (var eventName
in interactionModel
) {
1340 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1341 this.addEvent(this.mouseEventElement_
, eventName
,
1342 bindHandler(interactionModel
[eventName
]));
1345 // unregister the handler on subsequent calls.
1346 // This happens when the graph is resized.
1347 if (this.mouseUpHandler_
) {
1348 Dygraph
.removeEvent(document
, 'mouseup', this.mouseUpHandler_
);
1351 // If the user releases the mouse button during a drag, but not over the
1352 // canvas, then it doesn't count as a zooming action.
1353 this.mouseUpHandler_
= function(event
) {
1354 if (context
.isZooming
|| context
.isPanning
) {
1355 context
.isZooming
= false;
1356 context
.dragStartX
= null;
1357 context
.dragStartY
= null;
1360 if (context
.isPanning
) {
1361 context
.isPanning
= false;
1362 context
.draggingDate
= null;
1363 context
.dateRange
= null;
1364 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1365 delete self
.axes_
[i
].draggingValue
;
1366 delete self
.axes_
[i
].dragValueRange
;
1370 context
.tarp
.uncover();
1373 this.addEvent(document
, 'mouseup', this.mouseUpHandler_
);
1377 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1378 * up any previous zoom rectangles that were drawn. This could be optimized to
1379 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1382 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1383 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1384 * @param {Number} startX The X position where the drag started, in canvas
1386 * @param {Number} endX The current X position of the drag, in canvas coords.
1387 * @param {Number} startY The Y position where the drag started, in canvas
1389 * @param {Number} endY The current Y position of the drag, in canvas coords.
1390 * @param {Number} prevDirection the value of direction on the previous call to
1391 * this function. Used to avoid excess redrawing
1392 * @param {Number} prevEndX The value of endX on the previous call to this
1393 * function. Used to avoid excess redrawing
1394 * @param {Number} prevEndY The value of endY on the previous call to this
1395 * function. Used to avoid excess redrawing
1398 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1399 endY
, prevDirection
, prevEndX
,
1401 var ctx
= this.canvas_ctx_
;
1403 // Clean up from the previous rect if necessary
1404 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1405 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1406 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1407 } else if (prevDirection
== Dygraph
.VERTICAL
){
1408 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1409 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1412 // Draw a light-grey rectangle to show the new viewing area
1413 if (direction
== Dygraph
.HORIZONTAL
) {
1414 if (endX
&& startX
) {
1415 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1416 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1417 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1419 } else if (direction
== Dygraph
.VERTICAL
) {
1420 if (endY
&& startY
) {
1421 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1422 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1423 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1427 if (this.isUsingExcanvas_
) {
1428 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1433 * Clear the zoom rectangle (and perform no zoom).
1436 Dygraph
.prototype.clearZoomRect_
= function() {
1437 this.currentZoomRectArgs_
= null;
1438 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1442 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1443 * the canvas. The exact zoom window may be slightly larger if there are no data
1444 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1445 * which accepts dates that match the raw data. This function redraws the graph.
1447 * @param {Number} lowX The leftmost pixel value that should be visible.
1448 * @param {Number} highX The rightmost pixel value that should be visible.
1451 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1452 this.currentZoomRectArgs_
= null;
1453 // Find the earliest and latest dates contained in this canvasx range.
1454 // Convert the call to date ranges of the raw data.
1455 var minDate
= this.toDataXCoord(lowX
);
1456 var maxDate
= this.toDataXCoord(highX
);
1457 this.doZoomXDates_(minDate
, maxDate
);
1461 * Transition function to use in animations. Returns values between 0.0
1462 * (totally old values) and 1.0 (totally new values) for each frame.
1465 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1467 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1471 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1472 * method with doZoomX which accepts pixel coordinates. This function redraws
1475 * @param {Number} minDate The minimum date that should be visible.
1476 * @param {Number} maxDate The maximum date that should be visible.
1479 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1480 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1481 // can produce strange effects. Rather than the y-axis transitioning slowly
1482 // between values, it can jerk around.)
1483 var old_window
= this.xAxisRange();
1484 var new_window
= [minDate
, maxDate
];
1485 this.zoomed_x_
= true;
1487 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1488 if (that
.attr_("zoomCallback")) {
1489 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1495 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1496 * the canvas. This function redraws the graph.
1498 * @param {Number} lowY The topmost pixel value that should be visible.
1499 * @param {Number} highY The lowest pixel value that should be visible.
1502 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1503 this.currentZoomRectArgs_
= null;
1504 // Find the highest and lowest values in pixel range for each axis.
1505 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1506 // This is because pixels increase as you go down on the screen, whereas data
1507 // coordinates increase as you go up the screen.
1508 var oldValueRanges
= this.yAxisRanges();
1509 var newValueRanges
= [];
1510 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1511 var hi
= this.toDataYCoord(lowY
, i
);
1512 var low
= this.toDataYCoord(highY
, i
);
1513 newValueRanges
.push([low
, hi
]);
1516 this.zoomed_y_
= true;
1518 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1519 if (that
.attr_("zoomCallback")) {
1520 var xRange
= that
.xAxisRange();
1521 that
.attr_("zoomCallback")(xRange
[0], xRange
[1], that
.yAxisRanges());
1527 * Reset the zoom to the original view coordinates. This is the same as
1528 * double-clicking on the graph.
1530 Dygraph
.prototype.resetZoom
= function() {
1531 var dirty
= false, dirtyX
= false, dirtyY
= false;
1532 if (this.dateWindow_
!== null) {
1537 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1538 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1544 // Clear any selection, since it's likely to be drawn in the wrong place.
1545 this.clearSelection();
1548 this.zoomed_x_
= false;
1549 this.zoomed_y_
= false;
1551 var minDate
= this.rawData_
[0][0];
1552 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1554 // With only one frame, don't bother calculating extreme ranges.
1555 // TODO(danvk): merge this block w/ the code below
.
1556 if (!this.attr_("animatedZooms")) {
1557 this.dateWindow_
= null;
1558 for (i
= 0; i
< this.axes_
.length
; i
++) {
1559 if (this.axes_
[i
].valueWindow
!== null) {
1560 delete this.axes_
[i
].valueWindow
;
1564 if (this.attr_("zoomCallback")) {
1565 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1570 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1572 oldWindow
= this.xAxisRange();
1573 newWindow
= [minDate
, maxDate
];
1577 oldValueRanges
= this.yAxisRanges();
1578 // TODO(danvk): this is pretty inefficient
1579 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1580 var extremes
= packed
[1];
1582 // this has the side-effect of modifying this.axes_.
1583 // this doesn't make much sense in this context, but it's convenient (we
1584 // need this.axes_[*].extremeValues) and not harmful since we'll be
1585 // calling drawGraph_ shortly, which clobbers these values.
1586 this.computeYAxisRanges_(extremes
);
1588 newValueRanges
= [];
1589 for (i
= 0; i
< this.axes_
.length
; i
++) {
1590 var axis
= this.axes_
[i
];
1591 newValueRanges
.push((axis
.valueRange
!== null &&
1592 axis
.valueRange
!== undefined
) ?
1593 axis
.valueRange
: axis
.extremeRange
);
1598 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1600 that
.dateWindow_
= null;
1601 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1602 if (that
.axes_
[i
].valueWindow
!== null) {
1603 delete that
.axes_
[i
].valueWindow
;
1606 if (that
.attr_("zoomCallback")) {
1607 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1614 * Combined animation logic for all zoom functions.
1615 * either the x parameters or y parameters may be null.
1618 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1619 var steps
= this.attr_("animatedZooms") ? Dygraph
.ANIMATION_STEPS
: 1;
1622 var valueRanges
= [];
1625 if (oldXRange
!== null && newXRange
!== null) {
1626 for (step
= 1; step
<= steps
; step
++) {
1627 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1628 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1629 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1633 if (oldYRanges
!== null && newYRanges
!== null) {
1634 for (step
= 1; step
<= steps
; step
++) {
1635 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1637 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1638 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1639 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1641 valueRanges
[step
-1] = thisRange
;
1646 Dygraph
.repeatAndCleanup(function(step
) {
1647 if (valueRanges
.length
) {
1648 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1649 var w
= valueRanges
[step
][i
];
1650 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1653 if (windows
.length
) {
1654 that
.dateWindow_
= windows
[step
];
1657 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1661 * Get the current graph's area object.
1663 * Returns: {x, y, w, h}
1665 Dygraph
.prototype.getArea
= function() {
1666 return this.plotter_
.area
;
1670 * Convert a mouse event to DOM coordinates relative to the graph origin.
1672 * Returns a two-element array: [X, Y].
1674 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1675 if (event
.offsetX
&& event
.offsetY
) {
1676 return [ event
.offsetX
, event
.offsetY
];
1678 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1679 var canvasy
= Dygraph
.pageY(event
) - Dygraph
.findPosY(this.mouseEventElement_
);
1680 return [canvasx
, canvasy
];
1685 * Given a canvas X coordinate, find the closest row.
1686 * @param {Number} domX graph-relative DOM X coordinate
1687 * Returns: row number, integer
1690 Dygraph
.prototype.findClosestRow
= function(domX
) {
1691 var minDistX
= Infinity
;
1692 var pointIdx
= -1, setIdx
= -1;
1693 var sets
= this.layout_
.points
;
1694 for (var i
= 0; i
< sets
.length
; i
++) {
1695 var points
= sets
[i
];
1696 var len
= points
.length
;
1697 for (var j
= 0; j
< len
; j
++) {
1698 var point
= points
[j
];
1699 if (!Dygraph
.isValidPoint(point
, true)) continue;
1700 var dist
= Math
.abs(point
.canvasx
- domX
);
1701 if (dist
< minDistX
) {
1709 // TODO(danvk): remove this function; it's trivial and has only one use.
1710 return this.idxToRow_(setIdx
, pointIdx
);
1714 * Given canvas X,Y coordinates, find the closest point.
1716 * This finds the individual data point across all visible series
1717 * that's closest to the supplied DOM coordinates using the standard
1718 * Euclidean X,Y distance.
1720 * @param {Number} domX graph-relative DOM X coordinate
1721 * @param {Number} domY graph-relative DOM Y coordinate
1722 * Returns: {row, seriesName, point}
1725 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1726 var minDist
= Infinity
;
1728 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
;
1729 for ( var setIdx
= this.layout_
.datasets
.length
- 1 ; setIdx
>= 0 ; --setIdx
) {
1730 var points
= this.layout_
.points
[setIdx
];
1731 for (var i
= 0; i
< points
.length
; ++i
) {
1732 var point
= points
[i
];
1733 if (!Dygraph
.isValidPoint(point
)) continue;
1734 dx
= point
.canvasx
- domX
;
1735 dy
= point
.canvasy
- domY
;
1736 dist
= dx
* dx
+ dy
* dy
;
1737 if (dist
< minDist
) {
1739 closestPoint
= point
;
1740 closestSeries
= setIdx
;
1745 var name
= this.layout_
.setNames
[closestSeries
];
1747 row
: idx
+ this.getLeftBoundary_(),
1754 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1756 * This first finds the X data point closest to the supplied DOM X coordinate,
1757 * then finds the series which puts the Y coordinate on top of its filled area,
1758 * using linear interpolation between adjacent point pairs.
1760 * @param {Number} domX graph-relative DOM X coordinate
1761 * @param {Number} domY graph-relative DOM Y coordinate
1762 * Returns: {row, seriesName, point}
1765 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1766 var row
= this.findClosestRow(domX
);
1767 var boundary
= this.getLeftBoundary_();
1768 var rowIdx
= row
- boundary
;
1769 var closestPoint
, closestSeries
;
1770 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
1771 var points
= this.layout_
.points
[setIdx
];
1772 if (rowIdx
>= points
.length
) continue;
1773 var p1
= points
[rowIdx
];
1774 if (!Dygraph
.isValidPoint(p1
)) continue;
1775 var py
= p1
.canvasy
;
1776 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < points
.length
) {
1777 // interpolate series Y value using next point
1778 var p2
= points
[rowIdx
+ 1];
1779 if (Dygraph
.isValidPoint(p2
)) {
1780 var dx
= p2
.canvasx
- p1
.canvasx
;
1782 var r
= (domX
- p1
.canvasx
) / dx
;
1783 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1786 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1787 // interpolate series Y value using previous point
1788 var p0
= points
[rowIdx
- 1];
1789 if (Dygraph
.isValidPoint(p0
)) {
1790 var dx
= p1
.canvasx
- p0
.canvasx
;
1792 var r
= (p1
.canvasx
- domX
) / dx
;
1793 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1797 // Stop if the point (domX, py) is above this series' upper edge
1798 if (setIdx
=== 0 || py
< domY
) {
1800 closestSeries
= setIdx
;
1803 var name
= this.layout_
.setNames
[closestSeries
];
1812 * When the mouse moves in the canvas, display information about a nearby data
1813 * point and draw dots over those points in the data series. This function
1814 * takes care of cleanup of previously-drawn dots.
1815 * @param {Object} event The mousemove event from the browser.
1818 Dygraph
.prototype.mouseMove_
= function(event
) {
1819 // This prevents JS errors when mousing over the canvas before data loads.
1820 var points
= this.layout_
.points
;
1821 if (points
=== undefined
|| points
=== null) return;
1823 var canvasCoords
= this.eventToDomCoords(event
);
1824 var canvasx
= canvasCoords
[0];
1825 var canvasy
= canvasCoords
[1];
1827 var highlightSeriesOpts
= this.attr_("highlightSeriesOpts");
1828 var selectionChanged
= false;
1829 if (highlightSeriesOpts
&& !this.isSeriesLocked()) {
1831 if (this.attr_("stackedGraph")) {
1832 closest
= this.findStackedPoint(canvasx
, canvasy
);
1834 closest
= this.findClosestPoint(canvasx
, canvasy
);
1836 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1838 var idx
= this.findClosestRow(canvasx
);
1839 selectionChanged
= this.setSelection(idx
);
1842 var callback
= this.attr_("highlightCallback");
1843 if (callback
&& selectionChanged
) {
1847 this.lastRow_
+ this.getLeftBoundary_(),
1848 this.highlightSet_
);
1853 * Fetch left offset from first defined boundaryIds record (see bug #236).
1856 Dygraph
.prototype.getLeftBoundary_
= function() {
1857 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1858 if (this.boundaryIds_
[i
] !== undefined
) {
1859 return this.boundaryIds_
[i
][0];
1866 * Transforms layout_.points index into data row number.
1867 * @param int layout_.points index
1868 * @return int row number, or -1 if none could be found.
1871 Dygraph
.prototype.idxToRow_
= function(setIdx
, rowIdx
) {
1872 if (rowIdx
< 0) return -1;
1874 var boundary
= this.getLeftBoundary_();
1875 return boundary
+ rowIdx
;
1876 // for (var setIdx = 0; setIdx < this.layout_.datasets.length; ++setIdx) {
1877 // var set = this.layout_.datasets[setIdx];
1878 // if (idx < set.length) {
1879 // return boundary + idx;
1881 // idx -= set.length;
1886 Dygraph
.prototype.animateSelection_
= function(direction
) {
1887 var totalSteps
= 10;
1889 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1890 if (this.animateId
=== undefined
) this.animateId
= 0;
1891 var start
= this.fadeLevel
;
1892 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1894 if (this.fadeLevel
) {
1895 this.updateSelection_(1.0);
1900 var thisId
= ++this.animateId
;
1902 Dygraph
.repeatAndCleanup(
1904 // ignore simultaneous animations
1905 if (that
.animateId
!= thisId
) return;
1907 that
.fadeLevel
+= direction
;
1908 if (that
.fadeLevel
=== 0) {
1909 that
.clearSelection();
1911 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1914 steps
, millis
, function() {});
1918 * Draw dots over the selectied points in the data series. This function
1919 * takes care of cleanup of previously-drawn dots.
1922 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1923 /*var defaultPrevented = */
1924 this.cascadeEvents_('select', {
1925 selectedX
: this.lastx_
,
1926 selectedPoints
: this.selPoints_
1928 // TODO(danvk): use defaultPrevented here?
1930 // Clear the previously drawn vertical, if there is one
1932 var ctx
= this.canvas_ctx_
;
1933 if (this.attr_('highlightSeriesOpts')) {
1934 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1935 var alpha
= 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
1937 // Activating background fade includes an animation effect for a gradual
1938 // fade. TODO(klausw): make this independently configurable if it causes
1939 // issues? Use a shared preference to control animations?
1940 var animateBackgroundFade
= true;
1941 if (animateBackgroundFade
) {
1942 if (opt_animFraction
=== undefined
) {
1943 // start a new animation
1944 this.animateSelection_(1);
1947 alpha
*= opt_animFraction
;
1949 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1950 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1953 // Redraw only the highlighted series in the interactive canvas (not the
1954 // static plot canvas, which is where series are usually drawn).
1955 this.plotter_
._renderLineChart(this.highlightSet_
, ctx
);
1956 } else if (this.previousVerticalX_
>= 0) {
1957 // Determine the maximum highlight circle size.
1958 var maxCircleSize
= 0;
1959 var labels
= this.attr_('labels');
1960 for (i
= 1; i
< labels
.length
; i
++) {
1961 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1962 if (r
> maxCircleSize
) maxCircleSize
= r
;
1964 var px
= this.previousVerticalX_
;
1965 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1966 2 * maxCircleSize
+ 2, this.height_
);
1969 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
1970 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
1973 if (this.selPoints_
.length
> 0) {
1974 // Draw colored circles over the center of each selected point
1975 var canvasx
= this.selPoints_
[0].canvasx
;
1977 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1978 var pt
= this.selPoints_
[i
];
1979 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1981 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1982 var callback
= this.attr_("drawHighlightPointCallback", pt
.name
);
1983 var color
= this.plotter_
.colors
[pt
.name
];
1985 callback
= Dygraph
.Circles
.DEFAULT
;
1987 ctx
.lineWidth
= this.attr_('strokeWidth', pt
.name
);
1988 ctx
.strokeStyle
= color
;
1989 ctx
.fillStyle
= color
;
1990 callback(this.g
, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1991 color
, circleSize
, pt
.idx
);
1995 this.previousVerticalX_
= canvasx
;
2000 * Manually set the selected points and display information about them in the
2001 * legend. The selection can be cleared using clearSelection() and queried
2002 * using getSelection().
2003 * @param { Integer } row number that should be highlighted (i.e. appear with
2004 * hover dots on the chart). Set to false to clear any selection.
2005 * @param { seriesName } optional series name to highlight that series with the
2006 * the highlightSeriesOpts setting.
2007 * @param { locked } optional If true, keep seriesName selected when mousing
2008 * over the graph, disabling closest-series highlighting. Call clearSelection()
2011 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
, opt_locked
) {
2012 // Extract the points we've selected
2013 this.selPoints_
= [];
2015 if (row
!== false) {
2016 row
-= this.getLeftBoundary_();
2019 var changed
= false;
2020 if (row
!== false && row
>= 0) {
2021 if (row
!= this.lastRow_
) changed
= true;
2022 this.lastRow_
= row
;
2023 for (var setIdx
= 0; setIdx
< this.layout_
.datasets
.length
; ++setIdx
) {
2024 var set
= this.layout_
.datasets
[setIdx
];
2025 if (row
< set
.length
) {
2026 var point
= this.layout_
.points
[setIdx
][row
];
2028 if (this.attr_("stackedGraph")) {
2029 point
= this.layout_
.unstackPointAtIndex(setIdx
, row
);
2032 if (point
.yval
!== null) this.selPoints_
.push(point
);
2036 if (this.lastRow_
>= 0) changed
= true;
2040 if (this.selPoints_
.length
) {
2041 this.lastx_
= this.selPoints_
[0].xval
;
2046 if (opt_seriesName
!== undefined
) {
2047 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
2048 this.highlightSet_
= opt_seriesName
;
2051 if (opt_locked
!== undefined
) {
2052 this.lockedSet_
= opt_locked
;
2056 this.updateSelection_(undefined
);
2062 * The mouse has left the canvas. Clear out whatever artifacts remain
2063 * @param {Object} event the mouseout event from the browser.
2066 Dygraph
.prototype.mouseOut_
= function(event
) {
2067 if (this.attr_("unhighlightCallback")) {
2068 this.attr_("unhighlightCallback")(event
);
2071 if (this.attr_("hideOverlayOnMouseOut") && !this.lockedSet_
) {
2072 this.clearSelection();
2077 * Clears the current selection (i.e. points that were highlighted by moving
2078 * the mouse over the chart).
2080 Dygraph
.prototype.clearSelection
= function() {
2081 this.cascadeEvents_('deselect', {});
2083 this.lockedSet_
= false;
2084 // Get rid of the overlay data
2085 if (this.fadeLevel
) {
2086 this.animateSelection_(-1);
2089 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
2091 this.selPoints_
= [];
2094 this.highlightSet_
= null;
2098 * Returns the number of the currently selected row. To get data for this row,
2099 * you can use the getValue method.
2100 * @return { Integer } row number, or -1 if nothing is selected
2102 Dygraph
.prototype.getSelection
= function() {
2103 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
2107 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; setIdx
++) {
2108 var points
= this.layout_
.points
[setIdx
];
2109 for (var row
= 0; row
< points
.length
; row
++) {
2110 if (points
[row
].x
== this.selPoints_
[0].x
) {
2111 return row
+ this.getLeftBoundary_();
2119 * Returns the name of the currently-highlighted series.
2120 * Only available when the highlightSeriesOpts option is in use.
2122 Dygraph
.prototype.getHighlightSeries
= function() {
2123 return this.highlightSet_
;
2127 * Returns true if the currently-highlighted series was locked
2128 * via setSelection(..., seriesName, true).
2130 Dygraph
.prototype.isSeriesLocked
= function() {
2131 return this.lockedSet_
;
2135 * Fires when there's data available to be graphed.
2136 * @param {String} data Raw CSV data to be plotted
2139 Dygraph
.prototype.loadedEvent_
= function(data
) {
2140 this.rawData_
= this.parseCSV_(data
);
2145 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2148 Dygraph
.prototype.addXTicks_
= function() {
2149 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2151 if (this.dateWindow_
) {
2152 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2154 range
= this.xAxisExtremes();
2157 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2158 var xTicks
= xAxisOptionsView('ticker')(
2161 this.width_
, // TODO(danvk): should be area.width
2164 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2165 // console.log(msg);
2166 this.layout_
.setXTicks(xTicks
);
2171 * Computes the range of the data series (including confidence intervals).
2172 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2173 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2174 * @return [low, high]
2176 Dygraph
.prototype.extremeValues_
= function(series
) {
2177 var minY
= null, maxY
= null, j
, y
;
2179 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2181 // With custom bars, maxY is the max of the high values.
2182 for (j
= 0; j
< series
.length
; j
++) {
2183 y
= series
[j
][1][0];
2184 if (y
=== null || isNaN(y
)) continue;
2185 var low
= y
- series
[j
][1][1];
2186 var high
= y
+ series
[j
][1][2];
2187 if (low
> y
) low
= y
; // this can happen with custom bars,
2188 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2189 if (maxY
=== null || high
> maxY
) {
2192 if (minY
=== null || low
< minY
) {
2197 for (j
= 0; j
< series
.length
; j
++) {
2199 if (y
=== null || isNaN(y
)) continue;
2200 if (maxY
=== null || y
> maxY
) {
2203 if (minY
=== null || y
< minY
) {
2209 return [minY
, maxY
];
2214 * This function is called once when the chart's data is changed or the options
2215 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2216 * idea is that values derived from the chart's data can be computed here,
2217 * rather than every time the chart is drawn. This includes things like the
2218 * number of axes, rolling averages, etc.
2220 Dygraph
.prototype.predraw_
= function() {
2221 var start
= new Date();
2223 this.layout_
.computePlotArea();
2225 // TODO(danvk): move more computations out of drawGraph_ and into here.
2226 this.computeYAxes_();
2228 // Create a new plotter.
2229 if (this.plotter_
) {
2230 this.cascadeEvents_('clearChart');
2231 this.plotter_
.clear();
2233 this.plotter_
= new DygraphCanvasRenderer(this,
2238 // The roller sits in the bottom left corner of the chart. We don't know where
2239 // this will be until the options are available, so it's positioned here.
2240 this.createRollInterface_();
2242 this.cascadeEvents_('predraw');
2244 // Convert the raw data (a 2D array) into the internal format and compute
2245 // rolling averages.
2246 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2247 for (var i
= 1; i
< this.numColumns(); i
++) {
2248 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too
.
2249 var logScale
= this.attr_('logscale');
2250 var series
= this.extractSeries_(this.rawData_
, i
, logScale
);
2251 series
= this.rollingAverage(series
, this.rollPeriod_
);
2252 this.rolledSeries_
.push(series
);
2255 // If the data or options have changed, then we'd better redraw.
2258 // This is used to determine whether to do various animations.
2259 var end
= new Date();
2260 this.drawingTimeMs_
= (end
- start
);
2264 * Loop over all fields and create datasets, calculating extreme y-values for
2265 * each series and extreme x-indices as we go.
2267 * dateWindow is passed in as an explicit parameter so that we can compute
2268 * extreme values "speculatively", i.e. without actually setting state on the
2271 * TODO(danvk): make this more of a true function
2272 * @return [ datasets, seriesExtremes, boundaryIds ]
2275 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2276 var boundaryIds
= [];
2277 var cumulative_y
= []; // For stacked series.
2279 var extremes
= {}; // series name -> [low, high]
2282 // Loop over the fields (series). Go from the last to the first,
2283 // because if they're stacked that's how we accumulate the values.
2284 var num_series
= rolledSeries
.length
- 1;
2285 for (i
= num_series
; i
>= 1; i
--) {
2286 if (!this.visibility()[i
- 1]) continue;
2288 // Note: this copy _is_ necessary at the moment.
2289 // If you remove it, it breaks zooming with error bars on.
2290 // TODO(danvk): investigate further & write a test for this.
2292 for (j
= 0; j
< rolledSeries
[i
].length
; j
++) {
2293 series
.push(rolledSeries
[i
][j
]);
2296 // Prune down to the desired range, if necessary (for zooming)
2297 // Because there can be lines going to points outside of the visible area,
2298 // we actually prune to visible points, plus one on either side.
2299 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2301 var low
= dateWindow
[0];
2302 var high
= dateWindow
[1];
2304 // TODO(danvk): do binary search instead of linear search.
2305 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2306 var firstIdx
= null, lastIdx
= null;
2307 for (k
= 0; k
< series
.length
; k
++) {
2308 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2311 if (series
[k
][0] <= high
) {
2315 if (firstIdx
=== null) firstIdx
= 0;
2316 var correctedFirstIdx
= firstIdx
;
2317 if (correctedFirstIdx
> 0) correctedFirstIdx
--;
2318 while(series
[correctedFirstIdx
][1] === null && correctedFirstIdx
> 0){
2319 correctedFirstIdx
--;
2323 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2324 var correctedLastIdx
= lastIdx
;
2325 if (correctedLastIdx
< series
.length
- 1) correctedLastIdx
++;
2326 while(series
[correctedLastIdx
][1] === null && correctedLastIdx
< series
.length
- 1){
2330 boundaryIds
[i
-1] = [(firstIdx
> 0) ? firstIdx
- 1 : firstIdx
, (lastIdx
< series
.length
- 1) ? lastIdx
+ 1 : lastIdx
];
2332 if(correctedFirstIdx
!==firstIdx
)
2333 pruned
.push(series
[correctedFirstIdx
]);
2334 for (k
= firstIdx
; k
<= lastIdx
; k
++) {
2335 pruned
.push(series
[k
]);
2337 if(correctedLastIdx
!== lastIdx
)
2338 pruned
.push(series
[correctedLastIdx
]);
2342 boundaryIds
[i
-1] = [0, series
.length
-1];
2345 var seriesExtremes
= this.extremeValues_(series
);
2348 for (j
=0; j
<series
.length
; j
++) {
2349 series
[j
] = [series
[j
][0],
2354 } else if (this.attr_("stackedGraph")) {
2355 // Need to clear last_x explicitly as javascript's locals are
2356 // local to function, not to a block of statements
2357 var actual_y
, last_x
= null;
2358 for (j
= 0; j
< series
.length
; j
++) {
2359 // If one data set has a NaN, let all subsequent stacked
2360 // sets inherit the NaN -- only start at 0 for the first set.
2361 var x
= series
[j
][0];
2362 if (cumulative_y
[x
] === undefined
) {
2363 cumulative_y
[x
] = 0;
2366 actual_y
= series
[j
][1];
2367 if (actual_y
=== null) {
2368 series
[j
] = [x
, null];
2373 cumulative_y
[x
] += actual_y
;
2374 // If an x-value is repeated, we ignore the duplicates.
2378 series
[j
] = [x
, cumulative_y
[x
]];
2380 if (cumulative_y
[x
] > seriesExtremes
[1]) {
2381 seriesExtremes
[1] = cumulative_y
[x
];
2383 if (cumulative_y
[x
] < seriesExtremes
[0]) {
2384 seriesExtremes
[0] = cumulative_y
[x
];
2389 var seriesName
= this.attr_("labels")[i
];
2390 extremes
[seriesName
] = seriesExtremes
;
2391 datasets
[i
] = series
;
2394 // For stacked graphs, a NaN value for any point in the sum should create a
2395 // clean gap in the graph. Back-propagate NaNs to all points at this X value.
2396 if (this.attr_("stackedGraph")) {
2397 for (k
= datasets
.length
- 1; k
>= 0; --k
) {
2398 // Use the first nonempty dataset to get X values.
2399 if (!datasets
[k
]) continue;
2400 for (j
= 0; j
< datasets
[k
].length
; j
++) {
2401 var x
= datasets
[k
][j
][0];
2402 if (isNaN(cumulative_y
[x
])) {
2403 // Set all Y values to NaN at that X value.
2404 for (i
= datasets
.length
- 1; i
>= 0; i
--) {
2405 if (!datasets
[i
]) continue;
2406 datasets
[i
][j
][1] = NaN
;
2414 return [ datasets
, extremes
, boundaryIds
];
2418 * Update the graph with new data. This method is called when the viewing area
2419 * has changed. If the underlying data or options have changed, predraw_ will
2420 * be called before drawGraph_ is called.
2424 Dygraph
.prototype.drawGraph_
= function() {
2425 var start
= new Date();
2427 // This is used to set the second parameter to drawCallback, below.
2428 var is_initial_draw
= this.is_initial_draw_
;
2429 this.is_initial_draw_
= false;
2431 this.layout_
.removeAllDatasets();
2433 this.attrs_
.pointSize
= 0.5 * this.attr_('highlightCircleSize');
2435 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2436 var datasets
= packed
[0];
2437 var extremes
= packed
[1];
2438 this.boundaryIds_
= packed
[2];
2440 this.setIndexByName_
= {};
2441 var labels
= this.attr_("labels");
2442 if (labels
.length
> 0) {
2443 this.setIndexByName_
[labels
[0]] = 0;
2446 for (var i
= 1; i
< datasets
.length
; i
++) {
2447 this.setIndexByName_
[labels
[i
]] = i
;
2448 if (!this.visibility()[i
- 1]) continue;
2449 this.layout_
.addDataset(labels
[i
], datasets
[i
]);
2450 this.datasetIndex_
[i
] = dataIdx
++;
2453 this.computeYAxisRanges_(extremes
);
2454 this.layout_
.setYAxes(this.axes_
);
2458 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2459 var tmp_zoomed_x
= this.zoomed_x_
;
2460 // Tell PlotKit to use this new data and render itself
2461 this.layout_
.setDateWindow(this.dateWindow_
);
2462 this.zoomed_x_
= tmp_zoomed_x
;
2463 this.layout_
.evaluateWithError();
2464 this.renderGraph_(is_initial_draw
);
2466 if (this.attr_("timingName")) {
2467 var end
= new Date();
2468 Dygraph
.info(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2473 * This does the work of drawing the chart. It assumes that the layout and axis
2474 * scales have already been set (e.g. by predraw_).
2478 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2479 this.cascadeEvents_('clearChart');
2480 this.plotter_
.clear();
2482 if (this.attr_('underlayCallback')) {
2483 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2484 // users who expect a deprecated form of this callback.
2485 this.attr_('underlayCallback')(
2486 this.hidden_ctx_
, this.layout_
.getPlotArea(), this, this);
2490 canvas
: this.hidden_
,
2491 drawingContext
: this.hidden_ctx_
2493 this.cascadeEvents_('willDrawChart', e
);
2494 this.plotter_
.render();
2495 this.cascadeEvents_('didDrawChart', e
);
2496 this.lastRow_
= -1; // because plugins/legend.js clears the legend
2498 // TODO(danvk): is this a performance bottleneck when panning?
2499 // The interaction canvas should already be empty in that situation.
2500 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2501 this.canvas_
.height
);
2503 if (this.attr_("drawCallback") !== null) {
2504 this.attr_("drawCallback")(this, is_initial_draw
);
2510 * Determine properties of the y-axes which are independent of the data
2511 * currently being displayed. This includes things like the number of axes and
2512 * the style of the axes. It does not include the range of each axis and its
2514 * This fills in this.axes_.
2515 * axes_ = [ { options } ]
2516 * indices are into the axes_ array.
2518 Dygraph
.prototype.computeYAxes_
= function() {
2519 // Preserve valueWindow settings if they exist, and if the user hasn't
2520 // specified a new valueRange.
2521 var valueWindows
, axis
, index
, opts
, v
;
2522 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2524 for (index
= 0; index
< this.axes_
.length
; index
++) {
2525 valueWindows
.push(this.axes_
[index
].valueWindow
);
2529 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2530 // data computation as well as options storage.
2531 // Go through once and add all the axes.
2534 for (axis
= 0; axis
< this.attributes_
.numAxes(); axis
++) {
2535 // Add a new axis, making a copy of its per-axis options.
2536 opts
= { g
: this };
2537 Dygraph
.update(opts
, this.attributes_
.axisOptions(axis
));
2538 this.axes_
[axis
] = opts
;
2542 // Copy global valueRange option over to the first axis.
2543 // NOTE(konigsberg): Are these two statements necessary?
2544 // I tried removing it. The automated tests pass, and manually
2545 // messing with tests/zoom
.html showed no trouble
.
2546 v
= this.attr_('valueRange');
2547 if (v
) this.axes_
[0].valueRange
= v
;
2549 if (valueWindows
!== undefined
) {
2550 // Restore valueWindow settings.
2552 // When going from two axes back to one, we only restore
2554 var idxCount
= Math
.min(valueWindows
.length
, this.axes_
.length
);
2556 for (index
= 0; index
< idxCount
; index
++) {
2557 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2561 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2563 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2564 v
= opts("valueRange");
2565 if (v
) this.axes_
[axis
].valueRange
= v
;
2566 } else { // To keep old behavior
2567 var axes
= this.user_attrs_
.axes
;
2568 if (axes
&& axes
.y2
) {
2569 v
= axes
.y2
.valueRange
;
2570 if (v
) this.axes_
[axis
].valueRange
= v
;
2577 * Returns the number of y-axes on the chart.
2578 * @return {Number} the number of axes.
2580 Dygraph
.prototype.numAxes
= function() {
2581 return this.attributes_
.numAxes();
2586 * Returns axis properties for the given series.
2587 * @param { String } setName The name of the series for which to get axis
2588 * properties, e.g. 'Y1'.
2589 * @return { Object } The axis properties.
2591 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2592 // TODO(danvk): handle errors.
2593 return this.axes_
[this.attributes_
.axisForSeries(series
)];
2598 * Determine the value range and tick marks for each axis.
2599 * @param {Object} extremes A mapping from seriesName -> [low, high]
2600 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2602 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2603 var isNullUndefinedOrNaN
= function(num
) {
2604 return isNaN(parseFloat(num
));
2606 var numAxes
= this.attributes_
.numAxes();
2607 var ypadCompat
, span
, series
, ypad
;
2609 // Compute extreme values, a span and tick marks for each axis.
2610 for (var i
= 0; i
< numAxes
; i
++) {
2611 var axis
= this.axes_
[i
];
2612 var logscale
= this.attributes_
.getForAxis("logscale", i
);
2613 var includeZero
= this.attributes_
.getForAxis("includeZero", i
);
2614 series
= this.attributes_
.seriesForAxis(i
);
2616 // Add some padding. This supports two Y padding operation modes:
2618 // - backwards compatible (yRangePad not set):
2619 // 10% padding for automatic Y ranges, but not for user-supplied
2620 // ranges, and move a close-to-zero edge to zero except if
2621 // avoidMinZero is set, since drawing at the edge results in
2622 // invisible lines. Unfortunately lines drawn at the edge of a
2623 // user-supplied range will still be invisible. If logscale is
2624 // set, add a variable amount of padding at the top but
2625 // none at the bottom.
2627 // - new-style (yRangePad set by the user):
2628 // always add the specified Y padding.
2631 ypad
= 0.1; // add 10%
2632 if (this.attr_('yRangePad') !== null) {
2634 // Convert pixel padding to ratio
2635 ypad
= this.attr_('yRangePad') / this.plotter_
.area
.h
;
2638 if (series
.length
=== 0) {
2639 // If no series are defined or visible then use a reasonable default
2640 axis
.extremeRange
= [0, 1];
2642 // Calculate the extremes of extremes.
2643 var minY
= Infinity
; // extremes[series[0]][0];
2644 var maxY
= -Infinity
; // extremes[series[0]][1];
2645 var extremeMinY
, extremeMaxY
;
2647 for (var j
= 0; j
< series
.length
; j
++) {
2648 // this skips invisible series
2649 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2651 // Only use valid extremes to stop null data series' from corrupting the scale.
2652 extremeMinY
= extremes
[series
[j
]][0];
2653 if (extremeMinY
!== null) {
2654 minY
= Math
.min(extremeMinY
, minY
);
2656 extremeMaxY
= extremes
[series
[j
]][1];
2657 if (extremeMaxY
!== null) {
2658 maxY
= Math
.max(extremeMaxY
, maxY
);
2662 // Include zero if requested by the user.
2663 if (includeZero
&& !logscale
) {
2664 if (minY
> 0) minY
= 0;
2665 if (maxY
< 0) maxY
= 0;
2668 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2669 if (minY
== Infinity
) minY
= 0;
2670 if (maxY
== -Infinity
) maxY
= 1;
2673 // special case: if we have no sense of scale, center on the sole value.
2676 span
= Math
.abs(maxY
);
2678 // ... and if the sole value is zero, use range 0-1.
2684 var maxAxisY
, minAxisY
;
2687 maxAxisY
= maxY
+ ypad
* span
;
2690 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2691 maxAxisY
= maxY
* logpad
;
2692 minAxisY
= minY
/ logpad
;
2695 maxAxisY
= maxY
+ ypad
* span
;
2696 minAxisY
= minY
- ypad
* span
;
2698 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2699 // close to zero, but not if avoidMinZero is set.
2700 if (ypadCompat
&& !this.attr_("avoidMinZero")) {
2701 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2702 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2705 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2707 if (axis
.valueWindow
) {
2708 // This is only set if the user has zoomed on the y-axis. It is never set
2709 // by a user. It takes precedence over axis.valueRange because, if you set
2710 // valueRange, you'd still expect to be able to pan.
2711 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2712 } else if (axis
.valueRange
) {
2713 // This is a user-set value range for this axis.
2714 var y0
= isNullUndefinedOrNaN(axis
.valueRange
[0]) ? axis
.extremeRange
[0] : axis
.valueRange
[0];
2715 var y1
= isNullUndefinedOrNaN(axis
.valueRange
[1]) ? axis
.extremeRange
[1] : axis
.valueRange
[1];
2717 if (axis
.logscale
) {
2718 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2727 axis
.computedValueRange
= [y0
, y1
];
2729 axis
.computedValueRange
= axis
.extremeRange
;
2732 // Add ticks. By default, all axes inherit the tick positions of the
2733 // primary axis. However, if an axis is specifically marked as having
2734 // independent ticks, then that is permissible as well.
2735 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2736 var ticker
= opts('ticker');
2737 if (i
=== 0 || axis
.independentTicks
) {
2738 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2739 axis
.computedValueRange
[1],
2740 this.height_
, // TODO(danvk): should be area.height
2744 var p_axis
= this.axes_
[0];
2745 var p_ticks
= p_axis
.ticks
;
2746 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2747 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2748 var tick_values
= [];
2749 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2750 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2751 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2752 tick_values
.push(y_val
);
2755 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2756 axis
.computedValueRange
[1],
2757 this.height_
, // TODO(danvk): should be area.height
2766 * Extracts one series from the raw data (a 2D array) into an array of (date,
2769 * This is where undesirable points (i.e. negative values on log scales and
2770 * missing values through which we wish to connect lines) are dropped.
2771 * TODO(danvk): the "missing values" bit above doesn't seem right.
2775 Dygraph
.prototype.extractSeries_
= function(rawData
, i
, logScale
) {
2776 // TODO(danvk): pre-allocate series here.
2778 for (var j
= 0; j
< rawData
.length
; j
++) {
2779 var x
= rawData
[j
][0];
2780 var point
= rawData
[j
][i
];
2782 // On the log scale, points less than zero do not exist.
2783 // This will create a gap in the chart.
2788 series
.push([x
, point
]);
2795 * Calculates the rolling average of a data set.
2796 * If originalData is [label, val], rolls the average of those.
2797 * If originalData is [label, [, it's interpreted as [value, stddev]
2798 * and the roll is returned in the same form, with appropriately reduced
2799 * stddev for each value.
2800 * Note that this is where fractional input (i.e. '5/10') is converted into
2802 * @param {Array} originalData The data in the appropriate format (see above)
2803 * @param {Number} rollPeriod The number of points over which to average the
2806 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2807 rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2808 var rollingData
= [];
2809 var sigma
= this.attr_("sigma");
2811 var low
, high
, i
, j
, y
, sum
, num_ok
, stddev
;
2812 if (this.fractions_
) {
2814 var den
= 0; // numerator/denominator
2816 for (i
= 0; i
< originalData
.length
; i
++) {
2817 num
+= originalData
[i
][1][0];
2818 den
+= originalData
[i
][1][1];
2819 if (i
- rollPeriod
>= 0) {
2820 num
-= originalData
[i
- rollPeriod
][1][0];
2821 den
-= originalData
[i
- rollPeriod
][1][1];
2824 var date
= originalData
[i
][0];
2825 var value
= den
? num
/ den
: 0.0;
2826 if (this.attr_("errorBars")) {
2827 if (this.attr_("wilsonInterval")) {
2828 // For more details on this confidence interval, see:
2829 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2831 var p
= value
< 0 ? 0 : value
, n
= den
;
2832 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2833 var denom
= 1 + sigma
* sigma
/ den
;
2834 low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2835 high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2836 rollingData
[i
] = [date
,
2837 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2839 rollingData
[i
] = [date
, [0, 0, 0]];
2842 stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2843 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2846 rollingData
[i
] = [date
, mult
* value
];
2849 } else if (this.attr_("customBars")) {
2854 for (i
= 0; i
< originalData
.length
; i
++) {
2855 var data
= originalData
[i
][1];
2857 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
2859 if (y
!== null && !isNaN(y
)) {
2865 if (i
- rollPeriod
>= 0) {
2866 var prev
= originalData
[i
- rollPeriod
];
2867 if (prev
[1][1] !== null && !isNaN(prev
[1][1])) {
2875 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
2876 1.0 * (mid
- low
) / count
,
2877 1.0 * (high
- mid
) / count
]];
2879 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
2883 // Calculate the rolling average for the first rollPeriod - 1 points where
2884 // there is not enough data to roll over the full number of points
2885 if (!this.attr_("errorBars")){
2886 if (rollPeriod
== 1) {
2887 return originalData
;
2890 for (i
= 0; i
< originalData
.length
; i
++) {
2893 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2894 y
= originalData
[j
][1];
2895 if (y
=== null || isNaN(y
)) continue;
2897 sum
+= originalData
[j
][1];
2900 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
2902 rollingData
[i
] = [originalData
[i
][0], null];
2907 for (i
= 0; i
< originalData
.length
; i
++) {
2911 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
2912 y
= originalData
[j
][1][0];
2913 if (y
=== null || isNaN(y
)) continue;
2915 sum
+= originalData
[j
][1][0];
2916 variance
+= Math
.pow(originalData
[j
][1][1], 2);
2919 stddev
= Math
.sqrt(variance
) / num_ok
;
2920 rollingData
[i
] = [originalData
[i
][0],
2921 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
2923 // This explicitly preserves NaNs to aid with "independent series".
2924 // See testRollingAveragePreservesNaNs.
2925 var v
= (rollPeriod
== 1) ? originalData
[i
][1][0] : null;
2926 rollingData
[i
] = [originalData
[i
][0], [v
, v
, v
]];
2936 * Detects the type of the str (date or numeric) and sets the various
2937 * formatting attributes in this.attrs_ based on this type.
2938 * @param {String} str An x value.
2941 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2943 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2944 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
2945 str
.indexOf('/') >= 0 ||
2946 isNaN(parseFloat(str
))) {
2948 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2949 // TODO(danvk): remove support for this format.
2953 this.setXAxisOptions_(isDate
);
2956 Dygraph
.prototype.setXAxisOptions_
= function(isDate
) {
2958 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2959 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
2960 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2961 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
2963 /** @private (shut up, jsdoc!) */
2964 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2965 // TODO(danvk): use Dygraph.numberValueFormatter here?
2966 /** @private (shut up, jsdoc!) */
2967 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2968 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
2969 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2974 * Parses the value as a floating point number. This is like the parseFloat()
2975 * built-in, but with a few differences:
2976 * - the empty string is parsed as null, rather than NaN.
2977 * - if the string cannot be parsed at all, an error is logged.
2978 * If the string can't be parsed, this method returns null.
2979 * @param {String} x The string to be parsed
2980 * @param {Number} opt_line_no The line number from which the string comes.
2981 * @param {String} opt_line The text of the line from which the string comes.
2985 // Parse the x as a float or return null if it's not a number.
2986 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
2987 var val
= parseFloat(x
);
2988 if (!isNaN(val
)) return val
;
2990 // Try to figure out what happeend.
2991 // If the value is the empty string, parse it as null.
2992 if (/^ *$/.test(x
)) return null;
2994 // If it was actually "NaN", return it as NaN.
2995 if (/^ *nan *$/i.test(x
)) return NaN
;
2997 // Looks like a parsing error.
2998 var msg
= "Unable to parse '" + x
+ "' as a number";
2999 if (opt_line
!== null && opt_line_no
!== null) {
3000 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
3009 * Parses a string in a special csv format. We expect a csv file where each
3010 * line is a date point, and the first field in each line is the date string.
3011 * We also expect that all remaining fields represent series.
3012 * if the errorBars attribute is set, then interpret the fields as:
3013 * date, series1, stddev1, series2, stddev2, ...
3014 * @param {[Object]} data See above.
3016 * @return [Object] An array with one entry for each row. These entries
3017 * are an array of cells in that row. The first entry is the parsed x-value for
3018 * the row. The second, third, etc. are the y-values. These can take on one of
3019 * three forms, depending on the CSV and constructor parameters:
3021 * 2. [ value, stddev ]
3022 * 3. [ low value, center value, high value ]
3024 Dygraph
.prototype.parseCSV_
= function(data
) {
3026 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3027 var lines
= data
.split(line_delimiter
|| "\n");
3030 // Use the default delimiter or fall back to a tab if that makes sense.
3031 var delim
= this.attr_('delimiter');
3032 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
3037 if (!('labels' in this.user_attrs_
)) {
3038 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3040 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
3041 this.attributes_
.reparseSeries();
3046 var defaultParserSet
= false; // attempt to auto-detect x value type
3047 var expectedCols
= this.attr_("labels").length
;
3048 var outOfOrder
= false;
3049 for (var i
= start
; i
< lines
.length
; i
++) {
3050 var line
= lines
[i
];
3052 if (line
.length
=== 0) continue; // skip blank lines
3053 if (line
[0] == '#') continue; // skip comment lines
3054 var inFields
= line
.split(delim
);
3055 if (inFields
.length
< 2) continue;
3058 if (!defaultParserSet
) {
3059 this.detectTypeFromString_(inFields
[0]);
3060 xParser
= this.attr_("xValueParser");
3061 defaultParserSet
= true;
3063 fields
[0] = xParser(inFields
[0], this);
3065 // If fractions are expected, parse the numbers as "A/B
"
3066 if (this.fractions_) {
3067 for (j = 1; j < inFields.length; j++) {
3068 // TODO(danvk): figure out an appropriate way to flag parse errors.
3069 vals = inFields[j].split("/");
3070 if (vals.length != 2) {
3071 this.error('Expected fractional "num
/den
" values in CSV data ' +
3072 "but found a value
'" + inFields[j] + "' on line
" +
3073 (1 + i) + " ('" + line + "') which is not of
this form
.");
3076 fields[j] = [this.parseFloat_(vals[0], i, line),
3077 this.parseFloat_(vals[1], i, line)];
3080 } else if (this.attr_("errorBars
")) {
3081 // If there are error bars, values are (value, stddev) pairs
3082 if (inFields.length % 2 != 1) {
3083 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3084 'but line ' + (1 + i) + ' has an odd number of values (' +
3085 (inFields.length - 1) + "): '" + line + "'");
3087 for (j = 1; j < inFields.length; j += 2) {
3088 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3089 this.parseFloat_(inFields[j + 1], i, line)];
3091 } else if (this.attr_("customBars
")) {
3092 // Bars are a low;center;high tuple
3093 for (j = 1; j < inFields.length; j++) {
3094 var val = inFields[j];
3095 if (/^ *$/.test(val)) {
3096 fields[j] = [null, null, null];
3098 vals = val.split(";");
3099 if (vals.length == 3) {
3100 fields[j] = [ this.parseFloat_(vals[0], i, line),
3101 this.parseFloat_(vals[1], i, line),
3102 this.parseFloat_(vals[2], i, line) ];
3104 this.warn('When using customBars, values must be either blank ' +
3105 'or "low
;center
;high
" tuples (got "' + val +
3106 '" on line ' + (1+i));
3111 // Values are just numbers
3112 for (j = 1; j < inFields.length; j++) {
3113 fields[j] = this.parseFloat_(inFields[j], i, line);
3116 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3120 if (fields.length != expectedCols) {
3121 this.error("Number of columns
in line
" + i + " (" + fields.length +
3122 ") does not agree
with number of
labels (" + expectedCols +
3126 // If the user specified the 'labels' option and none of the cells of the
3127 // first row parsed correctly, then they probably double-specified the
3128 // labels. We go with the values set in the option, discard this row and
3129 // log a warning to the JS console.
3130 if (i === 0 && this.attr_('labels')) {
3131 var all_null = true;
3132 for (j = 0; all_null && j < fields.length; j++) {
3133 if (fields[j]) all_null = false;
3136 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
3137 "CSV
data ('" + line + "') appears to also contain labels
. " +
3138 "Will drop the CSV labels and
use the option labels
.");
3146 this.warn("CSV is out of order
; order it correctly to speed loading
.");
3147 ret.sort(function(a,b) { return a[0] - b[0]; });
3155 * The user has provided their data as a pre-packaged JS array. If the x values
3156 * are numeric, this is the same as dygraphs' internal format. If the x values
3157 * are dates, we need to convert them from Date objects to ms since epoch.
3158 * @param {[Object]} data
3159 * @return {[Object]} data with numeric x values.
3161 Dygraph.prototype.parseArray_ = function(data) {
3162 // Peek at the first x value to see if it's numeric.
3163 if (data.length === 0) {
3164 this.error("Can
't plot empty data set");
3167 if (data[0].length === 0) {
3168 this.error("Data set cannot contain an empty row");
3173 if (this.attr_("labels") === null) {
3174 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3175 "in the options parameter");
3176 this.attrs_.labels = [ "X" ];
3177 for (i = 1; i < data[0].length; i++) {
3178 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
3180 this.attributes_.reparseSeries();
3182 var num_labels = this.attr_("labels");
3183 if (num_labels.length != data[0].length) {
3184 this.error("Mismatch between number of labels (" + num_labels +
3185 ") and number of columns in array (" + data[0].length + ")");
3190 if (Dygraph.isDateLike(data[0][0])) {
3191 // Some intelligent defaults for a date x-axis.
3192 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3193 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3194 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3196 // Assume they're all dates
.
3197 var parsedData
= Dygraph
.clone(data
);
3198 for (i
= 0; i
< data
.length
; i
++) {
3199 if (parsedData
[i
].length
=== 0) {
3200 this.error("Row " + (1 + i
) + " of data is empty");
3203 if (parsedData
[i
][0] === null ||
3204 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3205 isNaN(parsedData
[i
][0].getTime())) {
3206 this.error("x value in row " + (1 + i
) + " is not a Date");
3209 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3213 // Some intelligent defaults for a numeric x-axis.
3214 /** @private (shut up, jsdoc!) */
3215 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3216 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3217 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3223 * Parses a DataTable object from gviz.
3224 * The data is expected to have a first column that is either a date or a
3225 * number. All subsequent columns must be numbers. If there is a clear mismatch
3226 * between this.xValueParser_ and the type of the first column, it will be
3227 * fixed. Fills out rawData_.
3228 * @param {[Object]} data See above.
3231 Dygraph
.prototype.parseDataTable_
= function(data
) {
3232 var shortTextForAnnotationNum
= function(num
) {
3233 // converts [0-9]+ [A-Z][a-z]*
3234 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3235 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3236 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3237 num
= Math
.floor(num
/ 26);
3239 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3240 num
= Math
.floor((num
- 1) / 26);
3245 var cols
= data
.getNumberOfColumns();
3246 var rows
= data
.getNumberOfRows();
3248 var indepType
= data
.getColumnType(0);
3249 if (indepType
== 'date' || indepType
== 'datetime') {
3250 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3251 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3252 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3253 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3254 } else if (indepType
== 'number') {
3255 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3256 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3257 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3258 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3260 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3261 "column 1 of DataTable input (Got '" + indepType
+ "')");
3265 // Array of the column indices which contain data (and not annotations).
3267 var annotationCols
= {}; // data index -> [annotation cols]
3268 var hasAnnotations
= false;
3270 for (i
= 1; i
< cols
; i
++) {
3271 var type
= data
.getColumnType(i
);
3272 if (type
== 'number') {
3274 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3275 // This is OK -- it's an annotation column.
3276 var dataIdx
= colIdx
[colIdx
.length
- 1];
3277 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3278 annotationCols
[dataIdx
] = [i
];
3280 annotationCols
[dataIdx
].push(i
);
3282 hasAnnotations
= true;
3284 this.error("Only 'number' is supported as a dependent type with Gviz." +
3285 " 'string' is only supported if displayAnnotations is true");
3289 // Read column labels
3290 // TODO(danvk): add support back for errorBars
3291 var labels
= [data
.getColumnLabel(0)];
3292 for (i
= 0; i
< colIdx
.length
; i
++) {
3293 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3294 if (this.attr_("errorBars")) i
+= 1;
3296 this.attrs_
.labels
= labels
;
3297 cols
= labels
.length
;
3300 var outOfOrder
= false;
3301 var annotations
= [];
3302 for (i
= 0; i
< rows
; i
++) {
3304 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3305 data
.getValue(i
, 0) === null) {
3306 this.warn("Ignoring row " + i
+
3307 " of DataTable because of undefined or null first column.");
3311 if (indepType
== 'date' || indepType
== 'datetime') {
3312 row
.push(data
.getValue(i
, 0).getTime());
3314 row
.push(data
.getValue(i
, 0));
3316 if (!this.attr_("errorBars")) {
3317 for (j
= 0; j
< colIdx
.length
; j
++) {
3318 var col
= colIdx
[j
];
3319 row
.push(data
.getValue(i
, col
));
3320 if (hasAnnotations
&&
3321 annotationCols
.hasOwnProperty(col
) &&
3322 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3324 ann
.series
= data
.getColumnLabel(col
);
3326 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3328 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3329 if (k
) ann
.text
+= "\n";
3330 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3332 annotations
.push(ann
);
3336 // Strip out infinities, which give dygraphs problems later on.
3337 for (j
= 0; j
< row
.length
; j
++) {
3338 if (!isFinite(row
[j
])) row
[j
] = null;
3341 for (j
= 0; j
< cols
- 1; j
++) {
3342 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3345 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3352 this.warn("DataTable is out of order; order it correctly to speed loading.");
3353 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3355 this.rawData_
= ret
;
3357 if (annotations
.length
> 0) {
3358 this.setAnnotations(annotations
, true);
3360 this.attributes_
.reparseSeries();
3364 * Get the CSV data. If it's in a function, call that function. If it's in a
3365 * file, do an XMLHttpRequest to get it.
3368 Dygraph
.prototype.start_
= function() {
3369 var data
= this.file_
;
3371 // Functions can return references of all other types.
3372 if (typeof data
== 'function') {
3376 if (Dygraph
.isArrayLike(data
)) {
3377 this.rawData_
= this.parseArray_(data
);
3379 } else if (typeof data
== 'object' &&
3380 typeof data
.getColumnRange
== 'function') {
3381 // must be a DataTable from gviz.
3382 this.parseDataTable_(data
);
3384 } else if (typeof data
== 'string') {
3385 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3386 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3387 if (line_delimiter
) {
3388 this.loadedEvent_(data
);
3390 var req
= new XMLHttpRequest();
3392 req
.onreadystatechange
= function () {
3393 if (req
.readyState
== 4) {
3394 if (req
.status
=== 200 || // Normal http
3395 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3396 caller
.loadedEvent_(req
.responseText
);
3401 req
.open("GET", data
, true);
3405 this.error("Unknown data format: " + (typeof data
));
3410 * Changes various properties of the graph. These can include:
3412 * <li>file: changes the source data for the graph</li>
3413 * <li>errorBars: changes whether the data contains stddev</li>
3416 * There's a huge variety of options that can be passed to this method. For a
3417 * full list, see http://dygraphs.com/options.html.
3419 * @param {Object} attrs The new properties and values
3420 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3421 * call to updateOptions(). If you know better, you can pass true to explicitly
3422 * block the redraw. This can be useful for chaining updateOptions() calls,
3423 * avoiding the occasional infinite loop and preventing redraws when it's not
3424 * necessary (e.g. when updating a callback).
3426 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3427 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3429 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3430 var file
= input_attrs
.file
;
3431 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3433 // TODO(danvk): this is a mess. Move these options into attr_.
3434 if ('rollPeriod' in attrs
) {
3435 this.rollPeriod_
= attrs
.rollPeriod
;
3437 if ('dateWindow' in attrs
) {
3438 this.dateWindow_
= attrs
.dateWindow
;
3439 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3440 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3443 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3444 this.zoomed_y_
= (attrs
.valueRange
!== null);
3447 // TODO(danvk): validate per-series options.
3452 // highlightCircleSize
3454 // Check if this set options will require new points.
3455 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3457 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3459 this.attributes_
.reparseSeries();
3463 if (!block_redraw
) this.start_();
3465 if (!block_redraw
) {
3466 if (requiresNewPoints
) {
3469 this.renderGraph_(false);
3476 * Returns a copy of the options with deprecated names converted into current
3477 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3478 * interested in that, they should save a copy before calling this.
3481 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3483 for (var k
in attrs
) {
3484 if (k
== 'file') continue;
3485 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3488 var set
= function(axis
, opt
, value
) {
3489 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3490 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3491 my_attrs
.axes
[axis
][opt
] = value
;
3493 var map
= function(opt
, axis
, new_opt
) {
3494 if (typeof(attrs
[opt
]) != 'undefined') {
3495 Dygraph
.warn("Option " + opt
+ " is deprecated. Use the " +
3496 new_opt
+ " option for the " + axis
+ " axis instead. " +
3497 "(e.g. { axes : { " + axis
+ " : { " + new_opt
+ " : ... } } } " +
3498 "(see http://dygraphs.com/per-axis.html for more information.");
3499 set(axis
, new_opt
, attrs
[opt
]);
3500 delete my_attrs
[opt
];
3504 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3505 map('xValueFormatter', 'x', 'valueFormatter');
3506 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3507 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3508 map('xTicker', 'x', 'ticker');
3509 map('yValueFormatter', 'y', 'valueFormatter');
3510 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3511 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3512 map('yTicker', 'y', 'ticker');
3517 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3518 * containing div (which has presumably changed size since the dygraph was
3519 * instantiated. If the width/height are specified, the div will be resized.
3521 * This is far more efficient than destroying and re-instantiating a
3522 * Dygraph, since it doesn't have to reparse the underlying data.
3524 * @param {Number} [width] Width (in pixels)
3525 * @param {Number} [height] Height (in pixels)
3527 Dygraph
.prototype.resize
= function(width
, height
) {
3528 if (this.resize_lock
) {
3531 this.resize_lock
= true;
3533 if ((width
=== null) != (height
=== null)) {
3534 this.warn("Dygraph.resize() should be called with zero parameters or " +
3535 "two non-NULL parameters. Pretending it was zero.");
3536 width
= height
= null;
3539 var old_width
= this.width_
;
3540 var old_height
= this.height_
;
3543 this.maindiv_
.style
.width
= width
+ "px";
3544 this.maindiv_
.style
.height
= height
+ "px";
3545 this.width_
= width
;
3546 this.height_
= height
;
3548 this.width_
= this.maindiv_
.clientWidth
;
3549 this.height_
= this.maindiv_
.clientHeight
;
3552 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3553 // TODO(danvk): there should be a clear() method.
3554 this.maindiv_
.innerHTML
= "";
3555 this.roller_
= null;
3556 this.attrs_
.labelsDiv
= null;
3557 this.createInterface_();
3558 if (this.annotations_
.length
) {
3559 // createInterface_ reset the layout, so we need to do this.
3560 this.layout_
.setAnnotations(this.annotations_
);
3562 this.createDragInterface_();
3566 this.resize_lock
= false;
3570 * Adjusts the number of points in the rolling average. Updates the graph to
3571 * reflect the new averaging period.
3572 * @param {Number} length Number of points over which to average the data.
3574 Dygraph
.prototype.adjustRoll
= function(length
) {
3575 this.rollPeriod_
= length
;
3580 * Returns a boolean array of visibility statuses.
3582 Dygraph
.prototype.visibility
= function() {
3583 // Do lazy-initialization, so that this happens after we know the number of
3585 if (!this.attr_("visibility")) {
3586 this.attrs_
.visibility
= [];
3588 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3589 while (this.attr_("visibility").length
< this.numColumns() - 1) {
3590 this.attrs_
.visibility
.push(true);
3592 return this.attr_("visibility");
3596 * Changes the visiblity of a series.
3598 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3599 var x
= this.visibility();
3600 if (num
< 0 || num
>= x
.length
) {
3601 this.warn("invalid series number in setVisibility: " + num
);
3609 * How large of an area will the dygraph render itself in?
3610 * This is used for testing.
3611 * @return A {width: w, height: h} object.
3614 Dygraph
.prototype.size
= function() {
3615 return { width
: this.width_
, height
: this.height_
};
3619 * Update the list of annotations and redraw the chart.
3620 * See dygraphs.com/annotations.html for more info on how to use annotations.
3621 * @param ann {Array} An array of annotation objects.
3622 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3624 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3625 // Only add the annotation CSS rule once we know it will be used.
3626 Dygraph
.addAnnotationRule();
3627 this.annotations_
= ann
;
3628 if (!this.layout_
) {
3629 this.warn("Tried to setAnnotations before dygraph was ready. " +
3630 "Try setting them in a drawCallback. See " +
3631 "dygraphs.com/tests/annotation.html");
3635 this.layout_
.setAnnotations(this.annotations_
);
3636 if (!suppressDraw
) {
3642 * Return the list of annotations.
3644 Dygraph
.prototype.annotations
= function() {
3645 return this.annotations_
;
3649 * Get the list of label names for this graph. The first column is the
3650 * x-axis, so the data series names start at index 1.
3652 * Returns null when labels have not yet been defined.
3654 Dygraph
.prototype.getLabels
= function() {
3655 var labels
= this.attr_("labels");
3656 return labels
? labels
.slice() : null;
3660 * Get the index of a series (column) given its name. The first column is the
3661 * x-axis, so the data series start with index 1.
3663 Dygraph
.prototype.indexFromSetName
= function(name
) {
3664 return this.setIndexByName_
[name
];
3668 * Get the internal dataset index given its name. These are numbered starting from 0,
3669 * and only count visible sets.
3672 Dygraph
.prototype.datasetIndexFromSetName_
= function(name
) {
3673 return this.datasetIndex_
[this.indexFromSetName(name
)];
3678 * Adds a default style for the annotation CSS classes to the document. This is
3679 * only executed when annotations are actually used. It is designed to only be
3680 * called once -- all calls after the first will return immediately.
3682 Dygraph
.addAnnotationRule
= function() {
3683 // TODO(danvk): move this function into plugins/annotations.js
?
3684 if (Dygraph
.addedAnnotationCSS
) return;
3686 var rule
= "border: 1px solid black; " +
3687 "background-color: white; " +
3688 "text-align: center;";
3690 var styleSheetElement
= document
.createElement("style");
3691 styleSheetElement
.type
= "text/css";
3692 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3694 // Find the first style sheet that we can access.
3695 // We may not add a rule to a style sheet from another domain for security
3696 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3697 // adds its own style sheets from google.com.
3698 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3699 if (document
.styleSheets
[i
].disabled
) continue;
3700 var mysheet
= document
.styleSheets
[i
];
3702 if (mysheet
.insertRule
) { // Firefox
3703 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3704 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3705 } else if (mysheet
.addRule
) { // IE
3706 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3708 Dygraph
.addedAnnotationCSS
= true;
3711 // Was likely a security exception.
3715 this.warn("Unable to add default annotation CSS rule; display may be off.");
3718 // Older pages may still use this name.
3719 var DateGraph
= Dygraph
;