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 stackedGraphNaNFill
: 'all',
295 hideOverlayOnMouseOut
: true,
297 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
298 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
304 drawAxesAtZero
: false,
306 // Sizes of the various chart labels.
313 axisLineColor
: "black",
316 axisLabelColor
: "black",
317 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
321 gridLineColor
: "rgb(128,128,128)",
323 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
324 animatedZooms
: false, // (for now)
326 // Range selector options
327 showRangeSelector
: false,
328 rangeSelectorHeight
: 40,
329 rangeSelectorPlotStrokeColor
: "#808FAB",
330 rangeSelectorPlotFillColor
: "#A7B1C4",
332 // The ordering here ensures that central lines always appear above any
333 // fill bars/error bars
.
335 Dygraph
.Plotters
.fillPlotter
,
336 Dygraph
.Plotters
.errorPlotter
,
337 Dygraph
.Plotters
.linePlotter
346 axisLabelFormatter
: Dygraph
.dateAxisFormatter
,
347 valueFormatter
: Dygraph
.dateString_
,
349 independentTicks
: true,
350 ticker
: null // will be set in dygraph-tickers.js
354 valueFormatter
: Dygraph
.numberValueFormatter
,
355 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
357 independentTicks
: true,
358 ticker
: null // will be set in dygraph-tickers.js
362 valueFormatter
: Dygraph
.numberValueFormatter
,
363 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
365 independentTicks
: false,
366 ticker
: null // will be set in dygraph-tickers.js
371 // Directions for panning and zooming. Use bit operations when combined
372 // values are possible.
373 Dygraph
.HORIZONTAL
= 1;
374 Dygraph
.VERTICAL
= 2;
376 // Installed plugins, in order of precedence (most-general to most-specific).
377 // Plugins are installed after they are defined, in plugins/install.js
.
381 // Used for initializing annotation CSS rules only once.
382 Dygraph
.addedAnnotationCSS
= false;
384 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
385 // Labels is no longer a constructor parameter, since it's typically set
386 // directly from the data source. It also conains a name for the x-axis,
387 // which the previous constructor form did not.
388 if (labels
!== null) {
389 var new_labels
= ["Date"];
390 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
391 Dygraph
.update(attrs
, { 'labels': new_labels
});
393 this.__init__(div
, file
, attrs
);
397 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
398 * and context <canvas> inside of it. See the constructor for details.
400 * @param {Element} div the Element to render the graph into.
401 * @param {String | Function} file Source data
402 * @param {Object} attrs Miscellaneous other options
405 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
406 // Hack for IE: if we're using excanvas and the document hasn't finished
407 // loading yet (and hence may not have initialized whatever it needs to
408 // initialize), then keep calling this routine periodically until it has.
409 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
410 typeof(G_vmlCanvasManager
) != 'undefined' &&
411 document
.readyState
!= 'complete') {
413 setTimeout(function() { self
.__init__(div
, file
, attrs
); }, 100);
417 // Support two-argument constructor
418 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
420 attrs
= Dygraph
.mapLegacyOptions_(attrs
);
422 if (typeof(div
) == 'string') {
423 div
= document
.getElementById(div
);
427 Dygraph
.error("Constructing dygraph with a non-existent div!");
431 this.isUsingExcanvas_
= typeof(G_vmlCanvasManager
) != 'undefined';
433 // Copy the important bits into the object
434 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
437 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
438 this.previousVerticalX_
= -1;
439 this.fractions_
= attrs
.fractions
|| false;
440 this.dateWindow_
= attrs
.dateWindow
|| null;
442 this.is_initial_draw_
= true;
443 this.annotations_
= [];
445 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
446 this.zoomed_x_
= false;
447 this.zoomed_y_
= false;
449 // Clear the div. This ensure that, if multiple dygraphs are passed the same
450 // div, then only one will be drawn.
453 // For historical reasons, the 'width' and 'height' options trump all CSS
454 // rules _except_ for an explicit 'width' or 'height' on the div.
455 // As an added convenience, if the div has zero height (like <div></div> does
456 // without any styles), then we use a default height/width
.
457 if (div
.style
.width
=== '' && attrs
.width
) {
458 div
.style
.width
= attrs
.width
+ "px";
460 if (div
.style
.height
=== '' && attrs
.height
) {
461 div
.style
.height
= attrs
.height
+ "px";
463 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
464 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
465 if (div
.style
.width
=== '') {
466 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
469 // these will be zero if the dygraph's div is hidden.
470 this.width_
= div
.clientWidth
;
471 this.height_
= div
.clientHeight
;
473 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
474 if (attrs
.stackedGraph
) {
475 attrs
.fillGraph
= true;
476 // TODO(nikhilk): Add any other stackedGraph checks here.
479 // DEPRECATION WARNING: All option processing should be moved from
480 // attrs_ and user_attrs_ to options_, which holds all this information.
482 // Dygraphs has many options, some of which interact with one another.
483 // To keep track of everything, we maintain two sets of options:
485 // this.user_attrs_ only options explicitly set by the user.
486 // this.attrs_ defaults, options derived from user_attrs_, data.
488 // Options are then accessed this.attr_('attr'), which first looks at
489 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
490 // defaults without overriding behavior that the user specifically asks for.
491 this.user_attrs_
= {};
492 Dygraph
.update(this.user_attrs_
, attrs
);
494 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
496 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
498 this.boundaryIds_
= [];
499 this.setIndexByName_
= {};
500 this.datasetIndex_
= [];
502 this.registeredEvents_
= [];
503 this.eventListeners_
= {};
505 this.attributes_
= new DygraphOptions(this);
507 // Create the containing DIV and other interactive elements
508 this.createInterface_();
512 var plugins
= Dygraph
.PLUGINS
.concat(this.getOption('plugins'));
513 for (var i
= 0; i
< plugins
.length
; i
++) {
514 var Plugin
= plugins
[i
];
515 var pluginInstance
= new Plugin();
517 plugin
: pluginInstance
,
523 var handlers
= pluginInstance
.activate(this);
524 for (var eventName
in handlers
) {
525 // TODO(danvk): validate eventName.
526 pluginDict
.events
[eventName
] = handlers
[eventName
];
529 this.plugins_
.push(pluginDict
);
532 // At this point, plugins can no longer register event handlers.
533 // Construct a map from event -> ordered list of [callback, plugin].
534 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
535 var plugin_dict
= this.plugins_
[i
];
536 for (var eventName
in plugin_dict
.events
) {
537 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
538 var callback
= plugin_dict
.events
[eventName
];
540 var pair
= [plugin_dict
.plugin
, callback
];
541 if (!(eventName
in this.eventListeners_
)) {
542 this.eventListeners_
[eventName
] = [pair
];
544 this.eventListeners_
[eventName
].push(pair
);
549 this.createDragInterface_();
555 * Triggers a cascade of events to the various plugins which are interested in them.
556 * Returns true if the "default behavior" should be performed, i.e. if none of
557 * the event listeners called event.preventDefault().
560 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
561 if (!(name
in this.eventListeners_
)) return true;
563 // QUESTION: can we use objects & prototypes to speed this up?
567 defaultPrevented
: false,
568 preventDefault
: function() {
569 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
570 e
.defaultPrevented
= true;
572 propagationStopped
: false,
573 stopPropagation
: function() {
574 e
.propagationStopped
= true;
577 Dygraph
.update(e
, extra_props
);
579 var callback_plugin_pairs
= this.eventListeners_
[name
];
580 if (callback_plugin_pairs
) {
581 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
582 var plugin
= callback_plugin_pairs
[i
][0];
583 var callback
= callback_plugin_pairs
[i
][1];
584 callback
.call(plugin
, e
);
585 if (e
.propagationStopped
) break;
588 return e
.defaultPrevented
;
592 * Returns the zoomed status of the chart for one or both axes.
594 * Axis is an optional parameter. Can be set to 'x' or 'y'.
596 * The zoomed status for an axis is set whenever a user zooms using the mouse
597 * or when the dateWindow or valueRange are updated (unless the
598 * isZoomedIgnoreProgrammaticZoom option is also specified).
600 Dygraph
.prototype.isZoomed
= function(axis
) {
601 if (axis
=== null || axis
=== undefined
) {
602 return this.zoomed_x_
|| this.zoomed_y_
;
604 if (axis
=== 'x') return this.zoomed_x_
;
605 if (axis
=== 'y') return this.zoomed_y_
;
606 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
610 * Returns information about the Dygraph object, including its containing ID.
612 Dygraph
.prototype.toString
= function() {
613 var maindiv
= this.maindiv_
;
614 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
615 return "[Dygraph " + id
+ "]";
620 * Returns the value of an option. This may be set by the user (either in the
621 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
623 * @param { String } name The name of the option, e.g. 'rollPeriod'.
624 * @param { String } [seriesName] The name of the series to which the option
625 * will be applied. If no per-series value of this option is available, then
626 * the global value is returned. This is optional.
627 * @return { ... } The value of the option.
629 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
630 // <REMOVE_FOR_COMBINED>
631 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
632 this.error('Must include options reference JS for testing');
633 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
634 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
635 'in the Dygraphs.OPTIONS_REFERENCE listing.');
636 // Only log this error once.
637 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
639 // </REMOVE_FOR_COMBINED
>
640 return seriesName
? this.attributes_
.getForSeries(name
, seriesName
) : this.attributes_
.get(name
);
644 * Returns the current value for an option, as set in the constructor or via
645 * updateOptions. You may pass in an (optional) series name to get per-series
646 * values for the option.
648 * All values returned by this method should be considered immutable. If you
649 * modify them, there is no guarantee that the changes will be honored or that
650 * dygraphs will remain in a consistent state. If you want to modify an option,
651 * use updateOptions() instead.
653 * @param { String } name The name of the option (e.g. 'strokeWidth')
654 * @param { String } [opt_seriesName] Series name to get per-series values.
655 * @return { ... } The value of the option.
657 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
658 return this.attr_(name
, opt_seriesName
);
661 Dygraph
.prototype.getOptionForAxis
= function(name
, axis
) {
662 return this.attributes_
.getForAxis(name
, axis
);
667 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
668 * @return { ... } A function mapping string -> option value
670 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
672 return function(opt
) {
673 var axis_opts
= self
.user_attrs_
.axes
;
674 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
675 return axis_opts
[axis
][opt
];
677 // user-specified attributes always trump defaults, even if they're less
679 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
680 return self
.user_attrs_
[opt
];
683 axis_opts
= self
.attrs_
.axes
;
684 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
685 return axis_opts
[axis
][opt
];
687 // check old-style axis options
688 // TODO(danvk): add a deprecation warning if either of these match.
689 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
690 return self
.axes_
[0][opt
];
691 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
692 return self
.axes_
[1][opt
];
694 return self
.attr_(opt
);
699 * Returns the current rolling period, as set by the user or an option.
700 * @return {Number} The number of points in the rolling window
702 Dygraph
.prototype.rollPeriod
= function() {
703 return this.rollPeriod_
;
707 * Returns the currently-visible x-range. This can be affected by zooming,
708 * panning or a call to updateOptions.
709 * Returns a two-element array: [left, right].
710 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
712 Dygraph
.prototype.xAxisRange
= function() {
713 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
717 * Returns the lower- and upper-bound x-axis values of the
720 Dygraph
.prototype.xAxisExtremes
= function() {
721 var pad
= this.attr_('xRangePad') / this.plotter_
.area
.w
;
722 if (this.numRows() === 0) {
723 return [0 - pad
, 1 + pad
];
725 var left
= this.rawData_
[0][0];
726 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
728 // Must keep this in sync with dygraph-layout _evaluateLimits()
729 var range
= right
- left
;
731 right
+= range
* pad
;
733 return [left
, right
];
737 * Returns the currently-visible y-range for an axis. This can be affected by
738 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
739 * called with no arguments, returns the range of the first axis.
740 * Returns a two-element array: [bottom, top].
742 Dygraph
.prototype.yAxisRange
= function(idx
) {
743 if (typeof(idx
) == "undefined") idx
= 0;
744 if (idx
< 0 || idx
>= this.axes_
.length
) {
747 var axis
= this.axes_
[idx
];
748 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
752 * Returns the currently-visible y-ranges for each axis. This can be affected by
753 * zooming, panning, calls to updateOptions, etc.
754 * Returns an array of [bottom, top] pairs, one for each y-axis.
756 Dygraph
.prototype.yAxisRanges
= function() {
758 for (var i
= 0; i
< this.axes_
.length
; i
++) {
759 ret
.push(this.yAxisRange(i
));
764 // TODO(danvk): use these functions throughout dygraphs.
766 * Convert from data coordinates to canvas/div X/Y coordinates.
767 * If specified, do this conversion for the coordinate system of a particular
768 * axis. Uses the first axis by default.
769 * Returns a two-element array: [X, Y]
771 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
772 * instead of toDomCoords(null, y, axis).
774 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
775 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
779 * Convert from data x coordinates to canvas/div X coordinate.
780 * If specified, do this conversion for the coordinate system of a particular
782 * Returns a single value or null if x is null.
784 Dygraph
.prototype.toDomXCoord
= function(x
) {
789 var area
= this.plotter_
.area
;
790 var xRange
= this.xAxisRange();
791 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
795 * Convert from data x coordinates to canvas/div Y coordinate and optional
796 * axis. Uses the first axis by default.
798 * returns a single value or null if y is null.
800 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
801 var pct
= this.toPercentYCoord(y
, axis
);
806 var area
= this.plotter_
.area
;
807 return area
.y
+ pct
* area
.h
;
811 * Convert from canvas/div coords to data coordinates.
812 * If specified, do this conversion for the coordinate system of a particular
813 * axis. Uses the first axis by default.
814 * Returns a two-element array: [X, Y].
816 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
817 * instead of toDataCoords(null, y, axis).
819 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
820 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
824 * Convert from canvas/div x coordinate to data coordinate.
826 * If x is null, this returns null.
828 Dygraph
.prototype.toDataXCoord
= function(x
) {
833 var area
= this.plotter_
.area
;
834 var xRange
= this.xAxisRange();
835 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
839 * Convert from canvas/div y coord to value.
841 * If y is null, this returns null.
842 * if axis is null, this uses the first axis.
844 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
849 var area
= this.plotter_
.area
;
850 var yRange
= this.yAxisRange(axis
);
852 if (typeof(axis
) == "undefined") axis
= 0;
853 if (!this.axes_
[axis
].logscale
) {
854 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
856 // Computing the inverse of toDomCoord.
857 var pct
= (y
- area
.y
) / area
.h
;
859 // Computing the inverse of toPercentYCoord. The function was arrived at with
860 // the following steps:
862 // Original calcuation:
863 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
865 // Move denominator to both sides:
866 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
868 // subtract logr1, and take the negative value.
869 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
871 // Swap both sides of the equation, and we can compute the log of the
872 // return value. Which means we just need to use that as the exponent in
874 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
876 var logr1
= Dygraph
.log10(yRange
[1]);
877 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
878 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
884 * Converts a y for an axis to a percentage from the top to the
885 * bottom of the drawing area.
887 * If the coordinate represents a value visible on the canvas, then
888 * the value will be between 0 and 1, where 0 is the top of the canvas.
889 * However, this method will return values outside the range, as
890 * values can fall outside the canvas.
892 * If y is null, this returns null.
893 * if axis is null, this uses the first axis.
895 * @param { Number } y The data y-coordinate.
896 * @param { Number } [axis] The axis number on which the data coordinate lives.
897 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
899 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
903 if (typeof(axis
) == "undefined") axis
= 0;
905 var yRange
= this.yAxisRange(axis
);
908 var logscale
= this.attributes_
.getForAxis("logscale", axis
);
910 // yRange[1] - y is unit distance from the bottom.
911 // yRange[1] - yRange[0] is the scale of the range.
912 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
913 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
915 var logr1
= Dygraph
.log10(yRange
[1]);
916 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
922 * Converts an x value to a percentage from the left to the right of
925 * If the coordinate represents a value visible on the canvas, then
926 * the value will be between 0 and 1, where 0 is the left of the canvas.
927 * However, this method will return values outside the range, as
928 * values can fall outside the canvas.
930 * If x is null, this returns null.
931 * @param { Number } x The data x-coordinate.
932 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
934 Dygraph
.prototype.toPercentXCoord
= function(x
) {
939 var xRange
= this.xAxisRange();
940 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
944 * Returns the number of columns (including the independent variable).
945 * @return { Integer } The number of columns.
947 Dygraph
.prototype.numColumns
= function() {
948 if (!this.rawData_
) return 0;
949 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
953 * Returns the number of rows (excluding any header/label row).
954 * @return { Integer } The number of rows, less any header.
956 Dygraph
.prototype.numRows
= function() {
957 if (!this.rawData_
) return 0;
958 return this.rawData_
.length
;
962 * Returns the value in the given row and column. If the row and column exceed
963 * the bounds on the data, returns null. Also returns null if the value is
965 * @param { Number} row The row number of the data (0-based). Row 0 is the
966 * first row of data, not a header row.
967 * @param { Number} col The column number of the data (0-based)
968 * @return { Number } The value in the specified cell or null if the row/col
971 Dygraph
.prototype.getValue
= function(row
, col
) {
972 if (row
< 0 || row
> this.rawData_
.length
) return null;
973 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
975 return this.rawData_
[row
][col
];
979 * Generates interface elements for the Dygraph: a containing div, a div to
980 * display the current point, and a textbox to adjust the rolling average
981 * period. Also creates the Renderer/Layout elements.
984 Dygraph
.prototype.createInterface_
= function() {
985 // Create the all-enclosing graph div
986 var enclosing
= this.maindiv_
;
988 this.graphDiv
= document
.createElement("div");
990 // TODO(danvk): any other styles that are useful to set here?
991 this.graphDiv
.style
.textAlign
= 'left'; // This is a CSS "reset"
992 enclosing
.appendChild(this.graphDiv
);
994 // Create the canvas for interactive parts of the chart.
995 this.canvas_
= Dygraph
.createCanvas();
996 this.canvas_
.style
.position
= "absolute";
998 this.resizeElements_();
1000 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
1002 // ... and for static parts of the chart.
1003 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
1004 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
1006 // The interactive parts of the graph are drawn on top of the chart.
1007 this.graphDiv
.appendChild(this.hidden_
);
1008 this.graphDiv
.appendChild(this.canvas_
);
1009 this.mouseEventElement_
= this.createMouseEventElement_();
1011 // Create the grapher
1012 this.layout_
= new DygraphLayout(this);
1016 this.mouseMoveHandler_
= function(e
) {
1017 dygraph
.mouseMove_(e
);
1020 this.mouseOutHandler_
= function(e
) {
1021 // The mouse has left the chart if:
1022 // 1. e.target is inside the chart
1023 // 2. e.relatedTarget is outside the chart
1024 var target
= e
.target
|| e
.fromElement
;
1025 var relatedTarget
= e
.relatedTarget
|| e
.toElement
;
1026 if (Dygraph
.isNodeContainedBy(target
, dygraph
.graphDiv
) &&
1027 !Dygraph
.isNodeContainedBy(relatedTarget
, dygraph
.graphDiv
)) {
1028 dygraph
.mouseOut_(e
);
1032 this.addAndTrackEvent(window
, 'mouseout', this.mouseOutHandler_
);
1033 this.addAndTrackEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1035 // Don't recreate and register the resize handler on subsequent calls.
1036 // This happens when the graph is resized.
1037 if (!this.resizeHandler_
) {
1038 this.resizeHandler_
= function(e
) {
1042 // Update when the window is resized.
1043 // TODO(danvk): drop frames depending on complexity of the chart.
1044 this.addAndTrackEvent(window
, 'resize', this.resizeHandler_
);
1048 Dygraph
.prototype.resizeElements_
= function() {
1049 this.graphDiv
.style
.width
= this.width_
+ "px";
1050 this.graphDiv
.style
.height
= this.height_
+ "px";
1051 this.canvas_
.width
= this.width_
;
1052 this.canvas_
.height
= this.height_
;
1053 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
1054 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
1058 * Detach DOM elements in the dygraph and null out all data references.
1059 * Calling this when you're done with a dygraph can dramatically reduce memory
1060 * usage. See, e.g., the tests/perf.html example.
1062 Dygraph
.prototype.destroy
= function() {
1063 this.canvas_ctx_
.restore();
1064 this.hidden_ctx_
.restore();
1066 var removeRecursive
= function(node
) {
1067 while (node
.hasChildNodes()) {
1068 removeRecursive(node
.firstChild
);
1069 node
.removeChild(node
.firstChild
);
1073 this.removeTrackedEvents_();
1075 // remove mouse event handlers (This may not be necessary anymore)
1076 Dygraph
.removeEvent(window
, 'mouseout', this.mouseOutHandler_
);
1077 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1079 // remove window handlers
1080 Dygraph
.removeEvent(window
,'resize',this.resizeHandler_
);
1081 this.resizeHandler_
= null;
1083 removeRecursive(this.maindiv_
);
1085 var nullOut
= function(obj
) {
1086 for (var n
in obj
) {
1087 if (typeof(obj
[n
]) === 'object') {
1092 // These may not all be necessary, but it can't hurt...
1093 nullOut(this.layout_
);
1094 nullOut(this.plotter_
);
1099 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1100 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1101 * or the zoom rectangles) is done on this.canvas_.
1102 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1103 * @return {Object} The newly-created canvas
1106 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1107 var h
= Dygraph
.createCanvas();
1108 h
.style
.position
= "absolute";
1109 // TODO(danvk): h should be offset from canvas. canvas needs to include
1110 // some extra area to make it easier to zoom in on the far left and far
1111 // right. h needs to be precisely the plot area, so that clipping occurs.
1112 h
.style
.top
= canvas
.style
.top
;
1113 h
.style
.left
= canvas
.style
.left
;
1114 h
.width
= this.width_
;
1115 h
.height
= this.height_
;
1116 h
.style
.width
= this.width_
+ "px"; // for IE
1117 h
.style
.height
= this.height_
+ "px"; // for IE
1122 * Creates an overlay element used to handle mouse events.
1123 * @return {Object} The mouse event element.
1126 Dygraph
.prototype.createMouseEventElement_
= function() {
1127 if (this.isUsingExcanvas_
) {
1128 var elem
= document
.createElement("div");
1129 elem
.style
.position
= 'absolute';
1130 elem
.style
.backgroundColor
= 'white';
1131 elem
.style
.filter
= 'alpha(opacity=0)';
1132 elem
.style
.width
= this.width_
+ "px";
1133 elem
.style
.height
= this.height_
+ "px";
1134 this.graphDiv
.appendChild(elem
);
1137 return this.canvas_
;
1142 * Generate a set of distinct colors for the data series. This is done with a
1143 * color wheel. Saturation/Value are customizable, and the hue is
1144 * equally-spaced around the color wheel. If a custom set of colors is
1145 * specified, that is used instead.
1148 Dygraph
.prototype.setColors_
= function() {
1149 var labels
= this.getLabels();
1150 var num
= labels
.length
- 1;
1152 this.colorsMap_
= {};
1153 var colors
= this.attr_('colors');
1156 var sat
= this.attr_('colorSaturation') || 1.0;
1157 var val
= this.attr_('colorValue') || 0.5;
1158 var half
= Math
.ceil(num
/ 2);
1159 for (i
= 1; i
<= num
; i
++) {
1160 if (!this.visibility()[i
-1]) continue;
1161 // alternate colors for high contrast.
1162 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
1163 var hue
= (1.0 * idx
/ (1 + num
));
1164 var colorStr
= Dygraph
.hsvToRGB(hue
, sat
, val
);
1165 this.colors_
.push(colorStr
);
1166 this.colorsMap_
[labels
[i
]] = colorStr
;
1169 for (i
= 0; i
< num
; i
++) {
1170 if (!this.visibility()[i
]) continue;
1171 var colorStr
= colors
[i
% colors
.length
];
1172 this.colors_
.push(colorStr
);
1173 this.colorsMap_
[labels
[1 + i
]] = colorStr
;
1179 * Return the list of colors. This is either the list of colors passed in the
1180 * attributes or the autogenerated list of rgb(r,g,b) strings.
1181 * This does not return colors for invisible series.
1182 * @return {Array<string>} The list of colors.
1184 Dygraph
.prototype.getColors
= function() {
1185 return this.colors_
;
1189 * Returns a few attributes of a series, i.e. its color, its visibility, which
1190 * axis it's assigned to, and its column in the original data.
1191 * Returns null if the series does not exist.
1192 * Otherwise, returns an object with column, visibility, color and axis properties.
1193 * The "axis" property will be set to 1 for y1 and 2 for y2.
1194 * The "column" property can be fed back into getValue(row, column) to get
1195 * values for this series.
1197 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1199 var labels
= this.getLabels();
1200 for (var i
= 1; i
< labels
.length
; i
++) {
1201 if (labels
[i
] == series_name
) {
1206 if (idx
== -1) return null;
1211 visible
: this.visibility()[idx
- 1],
1212 color
: this.colorsMap_
[series_name
],
1213 axis
: 1 + this.attributes_
.axisForSeries(series_name
)
1218 * Create the text box to adjust the averaging period
1221 Dygraph
.prototype.createRollInterface_
= function() {
1222 // Create a roller if one doesn't exist already.
1223 if (!this.roller_
) {
1224 this.roller_
= document
.createElement("input");
1225 this.roller_
.type
= "text";
1226 this.roller_
.style
.display
= "none";
1227 this.graphDiv
.appendChild(this.roller_
);
1230 var display
= this.attr_('showRoller') ? 'block' : 'none';
1232 var area
= this.plotter_
.area
;
1233 var textAttr
= { "position": "absolute",
1235 "top": (area
.y
+ area
.h
- 25) + "px",
1236 "left": (area
.x
+ 1) + "px",
1239 this.roller_
.size
= "2";
1240 this.roller_
.value
= this.rollPeriod_
;
1241 for (var name
in textAttr
) {
1242 if (textAttr
.hasOwnProperty(name
)) {
1243 this.roller_
.style
[name
] = textAttr
[name
];
1248 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1253 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1254 * canvas (i.e. DOM Coords).
1256 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1257 return Dygraph
.pageX(e
) - context
.px
;
1262 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1263 * canvas (i.e. DOM Coords).
1265 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1266 return Dygraph
.pageY(e
) - context
.py
;
1270 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1274 Dygraph
.prototype.createDragInterface_
= function() {
1276 // Tracks whether the mouse is down right now
1278 isPanning
: false, // is this drag part of a pan?
1279 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1280 dragStartX
: null, // pixel coordinates
1281 dragStartY
: null, // pixel coordinates
1282 dragEndX
: null, // pixel coordinates
1283 dragEndY
: null, // pixel coordinates
1284 dragDirection
: null,
1285 prevEndX
: null, // pixel coordinates
1286 prevEndY
: null, // pixel coordinates
1287 prevDragDirection
: null,
1288 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1290 // The value on the left side of the graph when a pan operation starts.
1291 initialLeftmostDate
: null,
1293 // The number of units each pixel spans. (This won't be valid for log
1295 xUnitsPerPixel
: null,
1297 // TODO(danvk): update this comment
1298 // The range in second/value units that the viewport encompasses during a
1299 // panning operation.
1302 // Top-left corner of the canvas, in DOM coords
1303 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1307 // Values for use with panEdgeFraction, which limit how far outside the
1308 // graph's data boundaries it can be panned.
1309 boundedDates
: null, // [minDate, maxDate]
1310 boundedValues
: null, // [[minValue, maxValue] ...]
1312 // We cover iframes during mouse interactions. See comments in
1313 // dygraph-utils.js for more info on why this is a good idea.
1314 tarp
: new Dygraph
.IFrameTarp(),
1316 // contextB is the same thing as this context object but renamed.
1317 initializeMouseDown
: function(event
, g
, contextB
) {
1318 // prevents mouse drags from selecting page text.
1319 if (event
.preventDefault
) {
1320 event
.preventDefault(); // Firefox, Chrome, etc.
1322 event
.returnValue
= false; // IE
1323 event
.cancelBubble
= true;
1326 contextB
.px
= Dygraph
.findPosX(g
.canvas_
);
1327 contextB
.py
= Dygraph
.findPosY(g
.canvas_
);
1328 contextB
.dragStartX
= g
.dragGetX_(event
, contextB
);
1329 contextB
.dragStartY
= g
.dragGetY_(event
, contextB
);
1330 contextB
.cancelNextDblclick
= false;
1331 contextB
.tarp
.cover();
1335 var interactionModel
= this.attr_("interactionModel");
1337 // Self is the graph.
1340 // Function that binds the graph and context to the handler.
1341 var bindHandler
= function(handler
) {
1342 return function(event
) {
1343 handler(event
, self
, context
);
1347 for (var eventName
in interactionModel
) {
1348 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1349 this.addAndTrackEvent(this.mouseEventElement_
, eventName
,
1350 bindHandler(interactionModel
[eventName
]));
1353 // If the user releases the mouse button during a drag, but not over the
1354 // canvas, then it doesn't count as a zooming action.
1355 var mouseUpHandler
= function(event
) {
1356 if (context
.isZooming
|| context
.isPanning
) {
1357 context
.isZooming
= false;
1358 context
.dragStartX
= null;
1359 context
.dragStartY
= null;
1362 if (context
.isPanning
) {
1363 context
.isPanning
= false;
1364 context
.draggingDate
= null;
1365 context
.dateRange
= null;
1366 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1367 delete self
.axes_
[i
].draggingValue
;
1368 delete self
.axes_
[i
].dragValueRange
;
1372 context
.tarp
.uncover();
1375 this.addAndTrackEvent(document
, 'mouseup', mouseUpHandler
);
1379 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1380 * up any previous zoom rectangles that were drawn. This could be optimized to
1381 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1384 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1385 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1386 * @param {Number} startX The X position where the drag started, in canvas
1388 * @param {Number} endX The current X position of the drag, in canvas coords.
1389 * @param {Number} startY The Y position where the drag started, in canvas
1391 * @param {Number} endY The current Y position of the drag, in canvas coords.
1392 * @param {Number} prevDirection the value of direction on the previous call to
1393 * this function. Used to avoid excess redrawing
1394 * @param {Number} prevEndX The value of endX on the previous call to this
1395 * function. Used to avoid excess redrawing
1396 * @param {Number} prevEndY The value of endY on the previous call to this
1397 * function. Used to avoid excess redrawing
1400 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1401 endY
, prevDirection
, prevEndX
,
1403 var ctx
= this.canvas_ctx_
;
1405 // Clean up from the previous rect if necessary
1406 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1407 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1408 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1409 } else if (prevDirection
== Dygraph
.VERTICAL
){
1410 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1411 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1414 // Draw a light-grey rectangle to show the new viewing area
1415 if (direction
== Dygraph
.HORIZONTAL
) {
1416 if (endX
&& startX
) {
1417 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1418 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1419 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1421 } else if (direction
== Dygraph
.VERTICAL
) {
1422 if (endY
&& startY
) {
1423 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1424 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1425 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1429 if (this.isUsingExcanvas_
) {
1430 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1435 * Clear the zoom rectangle (and perform no zoom).
1438 Dygraph
.prototype.clearZoomRect_
= function() {
1439 this.currentZoomRectArgs_
= null;
1440 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1444 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1445 * the canvas. The exact zoom window may be slightly larger if there are no data
1446 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1447 * which accepts dates that match the raw data. This function redraws the graph.
1449 * @param {Number} lowX The leftmost pixel value that should be visible.
1450 * @param {Number} highX The rightmost pixel value that should be visible.
1453 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1454 this.currentZoomRectArgs_
= null;
1455 // Find the earliest and latest dates contained in this canvasx range.
1456 // Convert the call to date ranges of the raw data.
1457 var minDate
= this.toDataXCoord(lowX
);
1458 var maxDate
= this.toDataXCoord(highX
);
1459 this.doZoomXDates_(minDate
, maxDate
);
1463 * Transition function to use in animations. Returns values between 0.0
1464 * (totally old values) and 1.0 (totally new values) for each frame.
1467 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1469 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1473 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1474 * method with doZoomX which accepts pixel coordinates. This function redraws
1477 * @param {Number} minDate The minimum date that should be visible.
1478 * @param {Number} maxDate The maximum date that should be visible.
1481 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1482 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1483 // can produce strange effects. Rather than the y-axis transitioning slowly
1484 // between values, it can jerk around.)
1485 var old_window
= this.xAxisRange();
1486 var new_window
= [minDate
, maxDate
];
1487 this.zoomed_x_
= true;
1489 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1490 if (that
.attr_("zoomCallback")) {
1491 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1497 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1498 * the canvas. This function redraws the graph.
1500 * @param {Number} lowY The topmost pixel value that should be visible.
1501 * @param {Number} highY The lowest pixel value that should be visible.
1504 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1505 this.currentZoomRectArgs_
= null;
1506 // Find the highest and lowest values in pixel range for each axis.
1507 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1508 // This is because pixels increase as you go down on the screen, whereas data
1509 // coordinates increase as you go up the screen.
1510 var oldValueRanges
= this.yAxisRanges();
1511 var newValueRanges
= [];
1512 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1513 var hi
= this.toDataYCoord(lowY
, i
);
1514 var low
= this.toDataYCoord(highY
, i
);
1515 newValueRanges
.push([low
, hi
]);
1518 this.zoomed_y_
= true;
1520 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1521 if (that
.attr_("zoomCallback")) {
1522 var xRange
= that
.xAxisRange();
1523 that
.attr_("zoomCallback")(xRange
[0], xRange
[1], that
.yAxisRanges());
1529 * Reset the zoom to the original view coordinates. This is the same as
1530 * double-clicking on the graph.
1532 Dygraph
.prototype.resetZoom
= function() {
1533 var dirty
= false, dirtyX
= false, dirtyY
= false;
1534 if (this.dateWindow_
!== null) {
1539 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1540 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1546 // Clear any selection, since it's likely to be drawn in the wrong place.
1547 this.clearSelection();
1550 this.zoomed_x_
= false;
1551 this.zoomed_y_
= false;
1553 var minDate
= this.rawData_
[0][0];
1554 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1556 // With only one frame, don't bother calculating extreme ranges.
1557 // TODO(danvk): merge this block w/ the code below
.
1558 if (!this.attr_("animatedZooms")) {
1559 this.dateWindow_
= null;
1560 for (i
= 0; i
< this.axes_
.length
; i
++) {
1561 if (this.axes_
[i
].valueWindow
!== null) {
1562 delete this.axes_
[i
].valueWindow
;
1566 if (this.attr_("zoomCallback")) {
1567 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1572 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1574 oldWindow
= this.xAxisRange();
1575 newWindow
= [minDate
, maxDate
];
1579 oldValueRanges
= this.yAxisRanges();
1580 // TODO(danvk): this is pretty inefficient
1581 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1582 var extremes
= packed
.extremes
;
1584 // this has the side-effect of modifying this.axes_.
1585 // this doesn't make much sense in this context, but it's convenient (we
1586 // need this.axes_[*].extremeValues) and not harmful since we'll be
1587 // calling drawGraph_ shortly, which clobbers these values.
1588 this.computeYAxisRanges_(extremes
);
1590 newValueRanges
= [];
1591 for (i
= 0; i
< this.axes_
.length
; i
++) {
1592 var axis
= this.axes_
[i
];
1593 newValueRanges
.push((axis
.valueRange
!== null &&
1594 axis
.valueRange
!== undefined
) ?
1595 axis
.valueRange
: axis
.extremeRange
);
1600 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1602 that
.dateWindow_
= null;
1603 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1604 if (that
.axes_
[i
].valueWindow
!== null) {
1605 delete that
.axes_
[i
].valueWindow
;
1608 if (that
.attr_("zoomCallback")) {
1609 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1616 * Combined animation logic for all zoom functions.
1617 * either the x parameters or y parameters may be null.
1620 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1621 var steps
= this.attr_("animatedZooms") ? Dygraph
.ANIMATION_STEPS
: 1;
1624 var valueRanges
= [];
1627 if (oldXRange
!== null && newXRange
!== null) {
1628 for (step
= 1; step
<= steps
; step
++) {
1629 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1630 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1631 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1635 if (oldYRanges
!== null && newYRanges
!== null) {
1636 for (step
= 1; step
<= steps
; step
++) {
1637 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1639 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1640 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1641 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1643 valueRanges
[step
-1] = thisRange
;
1648 Dygraph
.repeatAndCleanup(function(step
) {
1649 if (valueRanges
.length
) {
1650 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1651 var w
= valueRanges
[step
][i
];
1652 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1655 if (windows
.length
) {
1656 that
.dateWindow_
= windows
[step
];
1659 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1663 * Get the current graph's area object.
1665 * Returns: {x, y, w, h}
1667 Dygraph
.prototype.getArea
= function() {
1668 return this.plotter_
.area
;
1672 * Convert a mouse event to DOM coordinates relative to the graph origin.
1674 * Returns a two-element array: [X, Y].
1676 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1677 if (event
.offsetX
&& event
.offsetY
) {
1678 return [ event
.offsetX
, event
.offsetY
];
1680 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1681 var canvasy
= Dygraph
.pageY(event
) - Dygraph
.findPosY(this.mouseEventElement_
);
1682 return [canvasx
, canvasy
];
1687 * Given a canvas X coordinate, find the closest row.
1688 * @param {Number} domX graph-relative DOM X coordinate
1689 * Returns: row number, integer
1692 Dygraph
.prototype.findClosestRow
= function(domX
) {
1693 var minDistX
= Infinity
;
1694 var pointIdx
= -1, setIdx
= -1;
1695 var sets
= this.layout_
.points
;
1696 for (var i
= 0; i
< sets
.length
; i
++) {
1697 var points
= sets
[i
];
1698 var len
= points
.length
;
1699 for (var j
= 0; j
< len
; j
++) {
1700 var point
= points
[j
];
1701 if (!Dygraph
.isValidPoint(point
, true)) continue;
1702 var dist
= Math
.abs(point
.canvasx
- domX
);
1703 if (dist
< minDistX
) {
1711 // TODO(danvk): remove this function; it's trivial and has only one use.
1712 return this.idxToRow_(setIdx
, pointIdx
);
1716 * Given canvas X,Y coordinates, find the closest point.
1718 * This finds the individual data point across all visible series
1719 * that's closest to the supplied DOM coordinates using the standard
1720 * Euclidean X,Y distance.
1722 * @param {Number} domX graph-relative DOM X coordinate
1723 * @param {Number} domY graph-relative DOM Y coordinate
1724 * Returns: {row, seriesName, point}
1727 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1728 var minDist
= Infinity
;
1730 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
;
1731 for ( var setIdx
= this.layout_
.points
.length
- 1 ; setIdx
>= 0 ; --setIdx
) {
1732 var points
= this.layout_
.points
[setIdx
];
1733 for (var i
= 0; i
< points
.length
; ++i
) {
1734 var point
= points
[i
];
1735 if (!Dygraph
.isValidPoint(point
)) continue;
1736 dx
= point
.canvasx
- domX
;
1737 dy
= point
.canvasy
- domY
;
1738 dist
= dx
* dx
+ dy
* dy
;
1739 if (dist
< minDist
) {
1741 closestPoint
= point
;
1742 closestSeries
= setIdx
;
1747 var name
= this.layout_
.setNames
[closestSeries
];
1749 row
: idx
+ this.getLeftBoundary_(),
1756 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1758 * This first finds the X data point closest to the supplied DOM X coordinate,
1759 * then finds the series which puts the Y coordinate on top of its filled area,
1760 * using linear interpolation between adjacent point pairs.
1762 * @param {Number} domX graph-relative DOM X coordinate
1763 * @param {Number} domY graph-relative DOM Y coordinate
1764 * Returns: {row, seriesName, point}
1767 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1768 var row
= this.findClosestRow(domX
);
1769 var boundary
= this.getLeftBoundary_();
1770 var rowIdx
= row
- boundary
;
1771 var closestPoint
, closestSeries
;
1772 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
1773 var points
= this.layout_
.points
[setIdx
];
1774 if (rowIdx
>= points
.length
) continue;
1775 var p1
= points
[rowIdx
];
1776 if (!Dygraph
.isValidPoint(p1
)) continue;
1777 var py
= p1
.canvasy
;
1778 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < points
.length
) {
1779 // interpolate series Y value using next point
1780 var p2
= points
[rowIdx
+ 1];
1781 if (Dygraph
.isValidPoint(p2
)) {
1782 var dx
= p2
.canvasx
- p1
.canvasx
;
1784 var r
= (domX
- p1
.canvasx
) / dx
;
1785 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1788 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1789 // interpolate series Y value using previous point
1790 var p0
= points
[rowIdx
- 1];
1791 if (Dygraph
.isValidPoint(p0
)) {
1792 var dx
= p1
.canvasx
- p0
.canvasx
;
1794 var r
= (p1
.canvasx
- domX
) / dx
;
1795 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1799 // Stop if the point (domX, py) is above this series' upper edge
1800 if (setIdx
=== 0 || py
< domY
) {
1802 closestSeries
= setIdx
;
1805 var name
= this.layout_
.setNames
[closestSeries
];
1814 * When the mouse moves in the canvas, display information about a nearby data
1815 * point and draw dots over those points in the data series. This function
1816 * takes care of cleanup of previously-drawn dots.
1817 * @param {Object} event The mousemove event from the browser.
1820 Dygraph
.prototype.mouseMove_
= function(event
) {
1821 // This prevents JS errors when mousing over the canvas before data loads.
1822 var points
= this.layout_
.points
;
1823 if (points
=== undefined
|| points
=== null) return;
1825 var canvasCoords
= this.eventToDomCoords(event
);
1826 var canvasx
= canvasCoords
[0];
1827 var canvasy
= canvasCoords
[1];
1829 var highlightSeriesOpts
= this.attr_("highlightSeriesOpts");
1830 var selectionChanged
= false;
1831 if (highlightSeriesOpts
&& !this.isSeriesLocked()) {
1833 if (this.attr_("stackedGraph")) {
1834 closest
= this.findStackedPoint(canvasx
, canvasy
);
1836 closest
= this.findClosestPoint(canvasx
, canvasy
);
1838 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1840 var idx
= this.findClosestRow(canvasx
);
1841 selectionChanged
= this.setSelection(idx
);
1844 var callback
= this.attr_("highlightCallback");
1845 if (callback
&& selectionChanged
) {
1849 this.lastRow_
+ this.getLeftBoundary_(),
1850 this.highlightSet_
);
1855 * Fetch left offset from first defined boundaryIds record (see bug #236).
1858 Dygraph
.prototype.getLeftBoundary_
= function() {
1859 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1860 if (this.boundaryIds_
[i
] !== undefined
) {
1861 return this.boundaryIds_
[i
][0];
1868 * Transforms layout_.points index into data row number.
1869 * @param int layout_.points index
1870 * @return int row number, or -1 if none could be found.
1873 Dygraph
.prototype.idxToRow_
= function(setIdx
, rowIdx
) {
1874 if (rowIdx
< 0) return -1;
1876 var boundary
= this.getLeftBoundary_();
1877 return boundary
+ rowIdx
;
1880 Dygraph
.prototype.animateSelection_
= function(direction
) {
1881 var totalSteps
= 10;
1883 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1884 if (this.animateId
=== undefined
) this.animateId
= 0;
1885 var start
= this.fadeLevel
;
1886 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1888 if (this.fadeLevel
) {
1889 this.updateSelection_(1.0);
1894 var thisId
= ++this.animateId
;
1896 Dygraph
.repeatAndCleanup(
1898 // ignore simultaneous animations
1899 if (that
.animateId
!= thisId
) return;
1901 that
.fadeLevel
+= direction
;
1902 if (that
.fadeLevel
=== 0) {
1903 that
.clearSelection();
1905 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1908 steps
, millis
, function() {});
1912 * Draw dots over the selectied points in the data series. This function
1913 * takes care of cleanup of previously-drawn dots.
1916 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1917 /*var defaultPrevented = */
1918 this.cascadeEvents_('select', {
1919 selectedX
: this.lastx_
,
1920 selectedPoints
: this.selPoints_
1922 // TODO(danvk): use defaultPrevented here?
1924 // Clear the previously drawn vertical, if there is one
1926 var ctx
= this.canvas_ctx_
;
1927 if (this.attr_('highlightSeriesOpts')) {
1928 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1929 var alpha
= 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
1931 // Activating background fade includes an animation effect for a gradual
1932 // fade. TODO(klausw): make this independently configurable if it causes
1933 // issues? Use a shared preference to control animations?
1934 var animateBackgroundFade
= true;
1935 if (animateBackgroundFade
) {
1936 if (opt_animFraction
=== undefined
) {
1937 // start a new animation
1938 this.animateSelection_(1);
1941 alpha
*= opt_animFraction
;
1943 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1944 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1947 // Redraw only the highlighted series in the interactive canvas (not the
1948 // static plot canvas, which is where series are usually drawn).
1949 this.plotter_
._renderLineChart(this.highlightSet_
, ctx
);
1950 } else if (this.previousVerticalX_
>= 0) {
1951 // Determine the maximum highlight circle size.
1952 var maxCircleSize
= 0;
1953 var labels
= this.attr_('labels');
1954 for (i
= 1; i
< labels
.length
; i
++) {
1955 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1956 if (r
> maxCircleSize
) maxCircleSize
= r
;
1958 var px
= this.previousVerticalX_
;
1959 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1960 2 * maxCircleSize
+ 2, this.height_
);
1963 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
1964 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
1967 if (this.selPoints_
.length
> 0) {
1968 // Draw colored circles over the center of each selected point
1969 var canvasx
= this.selPoints_
[0].canvasx
;
1971 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1972 var pt
= this.selPoints_
[i
];
1973 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1975 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1976 var callback
= this.attr_("drawHighlightPointCallback", pt
.name
);
1977 var color
= this.plotter_
.colors
[pt
.name
];
1979 callback
= Dygraph
.Circles
.DEFAULT
;
1981 ctx
.lineWidth
= this.attr_('strokeWidth', pt
.name
);
1982 ctx
.strokeStyle
= color
;
1983 ctx
.fillStyle
= color
;
1984 callback(this.g
, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1985 color
, circleSize
, pt
.idx
);
1989 this.previousVerticalX_
= canvasx
;
1994 * Manually set the selected points and display information about them in the
1995 * legend. The selection can be cleared using clearSelection() and queried
1996 * using getSelection().
1997 * @param { Integer } row number that should be highlighted (i.e. appear with
1998 * hover dots on the chart). Set to false to clear any selection.
1999 * @param { seriesName } optional series name to highlight that series with the
2000 * the highlightSeriesOpts setting.
2001 * @param { locked } optional If true, keep seriesName selected when mousing
2002 * over the graph, disabling closest-series highlighting. Call clearSelection()
2005 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
, opt_locked
) {
2006 // Extract the points we've selected
2007 this.selPoints_
= [];
2009 if (row
!== false) {
2010 row
-= this.getLeftBoundary_();
2013 var changed
= false;
2014 if (row
!== false && row
>= 0) {
2015 if (row
!= this.lastRow_
) changed
= true;
2016 this.lastRow_
= row
;
2017 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
2018 var points
= this.layout_
.points
[setIdx
];
2019 if (row
< points
.length
) {
2020 var point
= points
[row
];
2021 if (point
.yval
!== null) this.selPoints_
.push(point
);
2025 if (this.lastRow_
>= 0) changed
= true;
2029 if (this.selPoints_
.length
) {
2030 this.lastx_
= this.selPoints_
[0].xval
;
2035 if (opt_seriesName
!== undefined
) {
2036 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
2037 this.highlightSet_
= opt_seriesName
;
2040 if (opt_locked
!== undefined
) {
2041 this.lockedSet_
= opt_locked
;
2045 this.updateSelection_(undefined
);
2051 * The mouse has left the canvas. Clear out whatever artifacts remain
2052 * @param {Object} event the mouseout event from the browser.
2055 Dygraph
.prototype.mouseOut_
= function(event
) {
2056 if (this.attr_("unhighlightCallback")) {
2057 this.attr_("unhighlightCallback")(event
);
2060 if (this.attr_("hideOverlayOnMouseOut") && !this.lockedSet_
) {
2061 this.clearSelection();
2066 * Clears the current selection (i.e. points that were highlighted by moving
2067 * the mouse over the chart).
2069 Dygraph
.prototype.clearSelection
= function() {
2070 this.cascadeEvents_('deselect', {});
2072 this.lockedSet_
= false;
2073 // Get rid of the overlay data
2074 if (this.fadeLevel
) {
2075 this.animateSelection_(-1);
2078 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
2080 this.selPoints_
= [];
2083 this.highlightSet_
= null;
2087 * Returns the number of the currently selected row. To get data for this row,
2088 * you can use the getValue method.
2089 * @return { Integer } row number, or -1 if nothing is selected
2091 Dygraph
.prototype.getSelection
= function() {
2092 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
2096 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; setIdx
++) {
2097 var points
= this.layout_
.points
[setIdx
];
2098 for (var row
= 0; row
< points
.length
; row
++) {
2099 if (points
[row
].x
== this.selPoints_
[0].x
) {
2100 return row
+ this.getLeftBoundary_();
2108 * Returns the name of the currently-highlighted series.
2109 * Only available when the highlightSeriesOpts option is in use.
2111 Dygraph
.prototype.getHighlightSeries
= function() {
2112 return this.highlightSet_
;
2116 * Returns true if the currently-highlighted series was locked
2117 * via setSelection(..., seriesName, true).
2119 Dygraph
.prototype.isSeriesLocked
= function() {
2120 return this.lockedSet_
;
2124 * Fires when there's data available to be graphed.
2125 * @param {String} data Raw CSV data to be plotted
2128 Dygraph
.prototype.loadedEvent_
= function(data
) {
2129 this.rawData_
= this.parseCSV_(data
);
2134 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2137 Dygraph
.prototype.addXTicks_
= function() {
2138 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2140 if (this.dateWindow_
) {
2141 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2143 range
= this.xAxisExtremes();
2146 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2147 var xTicks
= xAxisOptionsView('ticker')(
2150 this.width_
, // TODO(danvk): should be area.width
2153 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2154 // console.log(msg);
2155 this.layout_
.setXTicks(xTicks
);
2160 * Computes the range of the data series (including confidence intervals).
2161 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2162 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2163 * @return [low, high]
2165 Dygraph
.prototype.extremeValues_
= function(series
) {
2166 var minY
= null, maxY
= null, j
, y
;
2168 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2170 // With custom bars, maxY is the max of the high values.
2171 for (j
= 0; j
< series
.length
; j
++) {
2172 y
= series
[j
][1][0];
2173 if (y
=== null || isNaN(y
)) continue;
2174 var low
= y
- series
[j
][1][1];
2175 var high
= y
+ series
[j
][1][2];
2176 if (low
> y
) low
= y
; // this can happen with custom bars,
2177 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2178 if (maxY
=== null || high
> maxY
) {
2181 if (minY
=== null || low
< minY
) {
2186 for (j
= 0; j
< series
.length
; j
++) {
2188 if (y
=== null || isNaN(y
)) continue;
2189 if (maxY
=== null || y
> maxY
) {
2192 if (minY
=== null || y
< minY
) {
2198 return [minY
, maxY
];
2203 * This function is called once when the chart's data is changed or the options
2204 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2205 * idea is that values derived from the chart's data can be computed here,
2206 * rather than every time the chart is drawn. This includes things like the
2207 * number of axes, rolling averages, etc.
2209 Dygraph
.prototype.predraw_
= function() {
2210 var start
= new Date();
2212 this.layout_
.computePlotArea();
2214 // TODO(danvk): move more computations out of drawGraph_ and into here.
2215 this.computeYAxes_();
2217 // Create a new plotter.
2218 if (this.plotter_
) {
2219 this.cascadeEvents_('clearChart');
2220 this.plotter_
.clear();
2223 if(!this.is_initial_draw_
) {
2224 this.canvas_ctx_
.restore();
2225 this.hidden_ctx_
.restore();
2228 this.canvas_ctx_
.save();
2229 this.hidden_ctx_
.save();
2231 this.plotter_
= new DygraphCanvasRenderer(this,
2236 // The roller sits in the bottom left corner of the chart. We don't know where
2237 // this will be until the options are available, so it's positioned here.
2238 this.createRollInterface_();
2240 this.cascadeEvents_('predraw');
2242 // Convert the raw data (a 2D array) into the internal format and compute
2243 // rolling averages.
2244 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2245 for (var i
= 1; i
< this.numColumns(); i
++) {
2246 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too
.
2247 var logScale
= this.attr_('logscale');
2248 var series
= this.extractSeries_(this.rawData_
, i
, logScale
);
2249 series
= this.rollingAverage(series
, this.rollPeriod_
);
2250 this.rolledSeries_
.push(series
);
2253 // If the data or options have changed, then we'd better redraw.
2256 // This is used to determine whether to do various animations.
2257 var end
= new Date();
2258 this.drawingTimeMs_
= (end
- start
);
2264 * xval_* and yval_* are the original unscaled data values,
2265 * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
2266 * yval_stacked is the cumulative Y value used for stacking graphs,
2267 * and bottom/top/minus/plus are used for error bar graphs.
2274 * y_bottom: ?number,
2276 * y_stacked: ?number,
2278 * yval_minus: ?number,
2280 * yval_plus: ?number,
2286 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
2287 // on chrome+linux, they are 6 times more expensive than iterating through the
2288 // points and drawing the lines. The brunt of the cost comes from allocating
2289 // the |point| structures.
2291 * Converts a series to a Point array.
2293 * @param {Array.<Array.<(?number|Array<?number>)>} series Array where
2294 * series[row] = [x,y] or [x, [y, err]] or [x, [y, yplus, yminus]].
2295 * @param {boolean} bars True if error bars or custom bars are being drawn.
2296 * @param {string} setName Name of the series.
2297 * @param {number} boundaryIdStart Index offset of the first point, equal to
2298 * the number of skipped points left of the date window minimum (if any).
2299 * @return {Array.<Dygraph.PointType>} List of points for this series.
2301 Dygraph
.seriesToPoints_
= function(series
, bars
, setName
, boundaryIdStart
) {
2303 for (var i
= 0; i
< series
.length
; ++i
) {
2304 var item
= series
[i
];
2305 var yraw
= bars
? item
[1][0] : item
[1];
2306 var yval
= yraw
=== null ? null : DygraphLayout
.parseFloat_(yraw
);
2310 xval
: DygraphLayout
.parseFloat_(item
[0]),
2312 name
: setName
, // TODO(danvk): is this really necessary?
2313 idx
: i
+ boundaryIdStart
2318 point
.y_bottom
= NaN
,
2319 point
.yval_minus
= DygraphLayout
.parseFloat_(item
[1][1]);
2320 point
.yval_plus
= DygraphLayout
.parseFloat_(item
[1][2]);
2329 * Calculates point stacking for stackedGraph=true.
2331 * For stacking purposes, interpolate or extend neighboring data across
2332 * NaN values based on stackedGraphNaNFill settings. This is for display
2333 * only, the underlying data value as shown in the legend remains NaN.
2335 * @param {Array.<Dygraph.PointType>} points Point array for a single series.
2336 * Updates each Point's yval_stacked property.
2337 * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
2338 * values for the series seen so far. Index is the row number. Updated
2339 * based on the current series's values.
2340 * @param {Array.<number>} seriesExtremes Min and max values, updated
2341 * to reflect the stacked values.
2342 * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
2345 Dygraph
.stackPoints_
= function(
2346 points
, cumulativeYval
, seriesExtremes
, fillMethod
) {
2347 var lastXval
= null;
2348 var prevPoint
= null;
2349 var nextPoint
= null;
2350 var nextPointIdx
= -1;
2352 // Find the next stackable point starting from the given index.
2353 function updateNextPoint(idx
) {
2354 // If we've previously found a non-NaN point and haven't gone past it yet,
2356 if (nextPointIdx
>= idx
) return;
2358 // We haven't found a non-NaN point yet or have moved past it,
2359 // look towards the right to find a non-NaN point.
2360 for (var j
= idx
; j
< points
.length
; ++j
) {
2361 // Clear out a previously-found point (if any) since it's no longer
2362 // valid, we shouldn't use it for interpolation anymore.
2364 if (!isNaN(points
[j
].yval
) && points
[j
].yval
!== null) {
2366 nextPoint
= points
[j
];
2372 for (var i
= 0; i
< points
.length
; ++i
) {
2373 var point
= points
[i
];
2374 var xval
= point
.xval
;
2375 if (cumulativeYval
[xval
] === undefined
) {
2376 cumulativeYval
[xval
] = 0;
2379 var actualYval
= point
.yval
;
2380 if (isNaN(actualYval
) || actualYval
=== null) {
2381 // Interpolate/extend
for stacking purposes
if possible
.
2383 if (prevPoint
&& nextPoint
&& fillMethod
!= 'none') {
2384 // Use linear interpolation between prevPoint and nextPoint.
2385 actualYval
= prevPoint
.yval
+ (nextPoint
.yval
- prevPoint
.yval
) *
2386 ((xval
- prevPoint
.xval
) / (nextPoint
.xval
- prevPoint
.xval
));
2387 } else if (prevPoint
&& fillMethod
== 'all') {
2388 actualYval
= prevPoint
.yval
;
2389 } else if (nextPoint
&& fillMethod
== 'all') {
2390 actualYval
= nextPoint
.yval
;
2398 var stackedYval
= cumulativeYval
[xval
];
2399 if (lastXval
!= xval
) {
2400 // If an x-value is repeated, we ignore the duplicates.
2401 stackedYval
+= actualYval
;
2402 cumulativeYval
[xval
] = stackedYval
;
2406 point
.yval_stacked
= stackedYval
;
2408 if (stackedYval
> seriesExtremes
[1]) {
2409 seriesExtremes
[1] = stackedYval
;
2411 if (stackedYval
< seriesExtremes
[0]) {
2412 seriesExtremes
[0] = stackedYval
;
2419 * Loop over all fields and create datasets, calculating extreme y-values for
2420 * each series and extreme x-indices as we go.
2422 * dateWindow is passed in as an explicit parameter so that we can compute
2423 * extreme values "speculatively", i.e. without actually setting state on the
2426 * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
2427 * rolledSeries[seriesIndex][row] = raw point, where
2428 * seriesIndex is the column number starting with 1, and
2429 * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
2430 * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
2432 * points: Array.<Array.<Dygraph.PointType>>,
2433 * seriesExtremes: Array.<Array.<number>>,
2434 * boundaryIds: Array.<number>}}
2437 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2438 var boundaryIds
= [];
2440 var cumulativeYval
= []; // For stacked series.
2441 var extremes
= {}; // series name -> [low, high]
2443 var errorBars
= this.attr_("errorBars");
2444 var customBars
= this.attr_("customBars");
2445 var bars
= errorBars
|| customBars
;
2446 var isValueNull
= function(sample
) {
2448 return sample
[1] === null;
2450 return customBars
? sample
[1][1] === null :
2451 errorBars
? sample
[1][0] === null : false;
2455 // Loop over the fields (series). Go from the last to the first,
2456 // because if they're stacked that's how we accumulate the values.
2457 var num_series
= rolledSeries
.length
- 1;
2458 for (i
= num_series
; i
>= 1; i
--) {
2459 if (!this.visibility()[i
- 1]) continue;
2461 // Prune down to the desired range, if necessary (for zooming)
2462 // Because there can be lines going to points outside of the visible area,
2463 // we actually prune to visible points, plus one on either side.
2465 var series
= rolledSeries
[i
];
2466 var low
= dateWindow
[0];
2467 var high
= dateWindow
[1];
2469 // TODO(danvk): do binary search instead of linear search.
2470 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2471 var firstIdx
= null, lastIdx
= null;
2472 for (k
= 0; k
< series
.length
; k
++) {
2473 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2476 if (series
[k
][0] <= high
) {
2481 if (firstIdx
=== null) firstIdx
= 0;
2482 var correctedFirstIdx
= firstIdx
;
2483 var isInvalidValue
= true;
2484 while (isInvalidValue
&& correctedFirstIdx
> 0) {
2485 correctedFirstIdx
--;
2486 isInvalidValue
= isValueNull(series
[correctedFirstIdx
]);
2489 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2490 var correctedLastIdx
= lastIdx
;
2491 isInvalidValue
= true;
2492 while (isInvalidValue
&& correctedLastIdx
< series
.length
- 1) {
2494 isInvalidValue
= isValueNull(series
[correctedLastIdx
]);
2497 boundaryIds
[i
-1] = [(firstIdx
> 0) ? firstIdx
- 1 : firstIdx
,
2498 (lastIdx
< series
.length
- 1) ? lastIdx
+ 1 : lastIdx
];
2500 if (correctedFirstIdx
!==firstIdx
) {
2501 firstIdx
= correctedFirstIdx
;
2503 if (correctedLastIdx
!== lastIdx
) {
2504 lastIdx
= correctedLastIdx
;
2506 // .slice's end is exclusive, we want to include lastIdx.
2507 series
= series
.slice(firstIdx
, lastIdx
+ 1);
2509 series
= rolledSeries
[i
];
2510 boundaryIds
[i
-1] = [0, series
.length
-1];
2513 var seriesName
= this.attr_("labels")[i
];
2514 var seriesExtremes
= this.extremeValues_(series
);
2516 var seriesPoints
= Dygraph
.seriesToPoints_(
2517 series
, bars
, seriesName
, boundaryIds
[i
-1][0]);
2519 if (this.attr_("stackedGraph")) {
2520 Dygraph
.stackPoints_(seriesPoints
, cumulativeYval
, seriesExtremes
,
2521 this.attr_("stackedGraphNaNFill"));
2524 extremes
[seriesName
] = seriesExtremes
;
2525 points
[i
] = seriesPoints
;
2528 return { points
: points
, extremes
: extremes
, boundaryIds
: boundaryIds
};
2532 * Update the graph with new data. This method is called when the viewing area
2533 * has changed. If the underlying data or options have changed, predraw_ will
2534 * be called before drawGraph_ is called.
2538 Dygraph
.prototype.drawGraph_
= function() {
2539 var start
= new Date();
2541 // This is used to set the second parameter to drawCallback, below.
2542 var is_initial_draw
= this.is_initial_draw_
;
2543 this.is_initial_draw_
= false;
2545 this.layout_
.removeAllDatasets();
2547 this.attrs_
.pointSize
= 0.5 * this.attr_('highlightCircleSize');
2549 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2550 var points
= packed
.points
;
2551 var extremes
= packed
.extremes
;
2552 this.boundaryIds_
= packed
.boundaryIds
;
2554 this.setIndexByName_
= {};
2555 var labels
= this.attr_("labels");
2556 if (labels
.length
> 0) {
2557 this.setIndexByName_
[labels
[0]] = 0;
2560 for (var i
= 1; i
< points
.length
; i
++) {
2561 this.setIndexByName_
[labels
[i
]] = i
;
2562 if (!this.visibility()[i
- 1]) continue;
2563 this.layout_
.addDataset(labels
[i
], points
[i
]);
2564 this.datasetIndex_
[i
] = dataIdx
++;
2567 this.computeYAxisRanges_(extremes
);
2568 this.layout_
.setYAxes(this.axes_
);
2572 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2573 var tmp_zoomed_x
= this.zoomed_x_
;
2574 // Tell PlotKit to use this new data and render itself
2575 this.zoomed_x_
= tmp_zoomed_x
;
2576 this.layout_
.evaluate();
2577 this.renderGraph_(is_initial_draw
);
2579 if (this.attr_("timingName")) {
2580 var end
= new Date();
2581 Dygraph
.info(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2586 * This does the work of drawing the chart. It assumes that the layout and axis
2587 * scales have already been set (e.g. by predraw_).
2591 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2592 this.cascadeEvents_('clearChart');
2593 this.plotter_
.clear();
2595 if (this.attr_('underlayCallback')) {
2596 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2597 // users who expect a deprecated form of this callback.
2598 this.attr_('underlayCallback')(
2599 this.hidden_ctx_
, this.layout_
.getPlotArea(), this, this);
2603 canvas
: this.hidden_
,
2604 drawingContext
: this.hidden_ctx_
2606 this.cascadeEvents_('willDrawChart', e
);
2607 this.plotter_
.render();
2608 this.cascadeEvents_('didDrawChart', e
);
2609 this.lastRow_
= -1; // because plugins/legend.js clears the legend
2611 // TODO(danvk): is this a performance bottleneck when panning?
2612 // The interaction canvas should already be empty in that situation.
2613 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2614 this.canvas_
.height
);
2616 if (this.attr_("drawCallback") !== null) {
2617 this.attr_("drawCallback")(this, is_initial_draw
);
2623 * Determine properties of the y-axes which are independent of the data
2624 * currently being displayed. This includes things like the number of axes and
2625 * the style of the axes. It does not include the range of each axis and its
2627 * This fills in this.axes_.
2628 * axes_ = [ { options } ]
2629 * indices are into the axes_ array.
2631 Dygraph
.prototype.computeYAxes_
= function() {
2632 // Preserve valueWindow settings if they exist, and if the user hasn't
2633 // specified a new valueRange.
2634 var valueWindows
, axis
, index
, opts
, v
;
2635 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2637 for (index
= 0; index
< this.axes_
.length
; index
++) {
2638 valueWindows
.push(this.axes_
[index
].valueWindow
);
2642 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2643 // data computation as well as options storage.
2644 // Go through once and add all the axes.
2647 for (axis
= 0; axis
< this.attributes_
.numAxes(); axis
++) {
2648 // Add a new axis, making a copy of its per-axis options.
2649 opts
= { g
: this };
2650 Dygraph
.update(opts
, this.attributes_
.axisOptions(axis
));
2651 this.axes_
[axis
] = opts
;
2655 // Copy global valueRange option over to the first axis.
2656 // NOTE(konigsberg): Are these two statements necessary?
2657 // I tried removing it. The automated tests pass, and manually
2658 // messing with tests/zoom
.html showed no trouble
.
2659 v
= this.attr_('valueRange');
2660 if (v
) this.axes_
[0].valueRange
= v
;
2662 if (valueWindows
!== undefined
) {
2663 // Restore valueWindow settings.
2665 // When going from two axes back to one, we only restore
2667 var idxCount
= Math
.min(valueWindows
.length
, this.axes_
.length
);
2669 for (index
= 0; index
< idxCount
; index
++) {
2670 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2674 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2676 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2677 v
= opts("valueRange");
2678 if (v
) this.axes_
[axis
].valueRange
= v
;
2679 } else { // To keep old behavior
2680 var axes
= this.user_attrs_
.axes
;
2681 if (axes
&& axes
.y2
) {
2682 v
= axes
.y2
.valueRange
;
2683 if (v
) this.axes_
[axis
].valueRange
= v
;
2690 * Returns the number of y-axes on the chart.
2691 * @return {Number} the number of axes.
2693 Dygraph
.prototype.numAxes
= function() {
2694 return this.attributes_
.numAxes();
2699 * Returns axis properties for the given series.
2700 * @param { String } setName The name of the series for which to get axis
2701 * properties, e.g. 'Y1'.
2702 * @return { Object } The axis properties.
2704 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2705 // TODO(danvk): handle errors.
2706 return this.axes_
[this.attributes_
.axisForSeries(series
)];
2711 * Determine the value range and tick marks for each axis.
2712 * @param {Object} extremes A mapping from seriesName -> [low, high]
2713 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2715 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2716 var isNullUndefinedOrNaN
= function(num
) {
2717 return isNaN(parseFloat(num
));
2719 var numAxes
= this.attributes_
.numAxes();
2720 var ypadCompat
, span
, series
, ypad
;
2724 // Compute extreme values, a span and tick marks for each axis.
2725 for (var i
= 0; i
< numAxes
; i
++) {
2726 var axis
= this.axes_
[i
];
2727 var logscale
= this.attributes_
.getForAxis("logscale", i
);
2728 var includeZero
= this.attributes_
.getForAxis("includeZero", i
);
2729 var independentTicks
= this.attributes_
.getForAxis("independentTicks", i
);
2730 series
= this.attributes_
.seriesForAxis(i
);
2732 // Add some padding. This supports two Y padding operation modes:
2734 // - backwards compatible (yRangePad not set):
2735 // 10% padding for automatic Y ranges, but not for user-supplied
2736 // ranges, and move a close-to-zero edge to zero except if
2737 // avoidMinZero is set, since drawing at the edge results in
2738 // invisible lines. Unfortunately lines drawn at the edge of a
2739 // user-supplied range will still be invisible. If logscale is
2740 // set, add a variable amount of padding at the top but
2741 // none at the bottom.
2743 // - new-style (yRangePad set by the user):
2744 // always add the specified Y padding.
2747 ypad
= 0.1; // add 10%
2748 if (this.attr_('yRangePad') !== null) {
2750 // Convert pixel padding to ratio
2751 ypad
= this.attr_('yRangePad') / this.plotter_
.area
.h
;
2754 if (series
.length
=== 0) {
2755 // If no series are defined or visible then use a reasonable default
2756 axis
.extremeRange
= [0, 1];
2758 // Calculate the extremes of extremes.
2759 var minY
= Infinity
; // extremes[series[0]][0];
2760 var maxY
= -Infinity
; // extremes[series[0]][1];
2761 var extremeMinY
, extremeMaxY
;
2763 for (var j
= 0; j
< series
.length
; j
++) {
2764 // this skips invisible series
2765 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2767 // Only use valid extremes to stop null data series' from corrupting the scale.
2768 extremeMinY
= extremes
[series
[j
]][0];
2769 if (extremeMinY
!== null) {
2770 minY
= Math
.min(extremeMinY
, minY
);
2772 extremeMaxY
= extremes
[series
[j
]][1];
2773 if (extremeMaxY
!== null) {
2774 maxY
= Math
.max(extremeMaxY
, maxY
);
2778 // Include zero if requested by the user.
2779 if (includeZero
&& !logscale
) {
2780 if (minY
> 0) minY
= 0;
2781 if (maxY
< 0) maxY
= 0;
2784 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2785 if (minY
== Infinity
) minY
= 0;
2786 if (maxY
== -Infinity
) maxY
= 1;
2789 // special case: if we have no sense of scale, center on the sole value.
2792 span
= Math
.abs(maxY
);
2794 // ... and if the sole value is zero, use range 0-1.
2800 var maxAxisY
, minAxisY
;
2803 maxAxisY
= maxY
+ ypad
* span
;
2806 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2807 maxAxisY
= maxY
* logpad
;
2808 minAxisY
= minY
/ logpad
;
2811 maxAxisY
= maxY
+ ypad
* span
;
2812 minAxisY
= minY
- ypad
* span
;
2814 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2815 // close to zero, but not if avoidMinZero is set.
2816 if (ypadCompat
&& !this.attr_("avoidMinZero")) {
2817 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2818 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2821 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2823 if (axis
.valueWindow
) {
2824 // This is only set if the user has zoomed on the y-axis. It is never set
2825 // by a user. It takes precedence over axis.valueRange because, if you set
2826 // valueRange, you'd still expect to be able to pan.
2827 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2828 } else if (axis
.valueRange
) {
2829 // This is a user-set value range for this axis.
2830 var y0
= isNullUndefinedOrNaN(axis
.valueRange
[0]) ? axis
.extremeRange
[0] : axis
.valueRange
[0];
2831 var y1
= isNullUndefinedOrNaN(axis
.valueRange
[1]) ? axis
.extremeRange
[1] : axis
.valueRange
[1];
2833 if (axis
.logscale
) {
2834 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2843 axis
.computedValueRange
= [y0
, y1
];
2845 axis
.computedValueRange
= axis
.extremeRange
;
2849 if(independentTicks
) {
2850 axis
.independentTicks
= independentTicks
;
2851 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2852 var ticker
= opts('ticker');
2853 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2854 axis
.computedValueRange
[1],
2855 this.height_
, // TODO(danvk): should be area.height
2858 // Define the first independent axis as primary axis.
2859 if (!p_axis
) p_axis
= axis
;
2862 if (p_axis
=== undefined
) {
2863 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
2865 // Add ticks. By default, all axes inherit the tick positions of the
2866 // primary axis. However, if an axis is specifically marked as having
2867 // independent ticks, then that is permissible as well.
2868 for (var i
= 0; i
< numAxes
; i
++) {
2869 var axis
= this.axes_
[i
];
2871 if (!axis
.independentTicks
) {
2872 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2873 var ticker
= opts('ticker');
2874 var p_ticks
= p_axis
.ticks
;
2875 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2876 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2877 var tick_values
= [];
2878 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2879 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2880 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2881 tick_values
.push(y_val
);
2884 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2885 axis
.computedValueRange
[1],
2886 this.height_
, // TODO(danvk): should be area.height
2895 * Extracts one series from the raw data (a 2D array) into an array of (date,
2898 * This is where undesirable points (i.e. negative values on log scales and
2899 * missing values through which we wish to connect lines) are dropped.
2900 * TODO(danvk): the "missing values" bit above doesn't seem right.
2903 * @param {Array.<Array.<(number|Array<Number>)>>} rawData Input data. Rectangular
2904 * grid of points, where rawData[row][0] is the X value for the row,
2905 * and rawData[row][i] is the Y data for series #i.
2906 * @param {number} i Series index, starting from 1.
2907 * @param {boolean} logScale True if using logarithmic Y scale.
2908 * @return {Array.<Array.<(?number|Array<?number>)>} Series array, where
2909 * series[row] = [x,y] or [x, [y, err]] or [x, [y, yplus, yminus]].
2911 Dygraph
.prototype.extractSeries_
= function(rawData
, i
, logScale
) {
2912 // TODO(danvk): pre-allocate series here.
2914 var errorBars
= this.attr_("errorBars");
2915 var customBars
= this.attr_("customBars");
2916 for (var j
= 0; j
< rawData
.length
; j
++) {
2917 var x
= rawData
[j
][0];
2918 var point
= rawData
[j
][i
];
2920 // On the log scale, points less than zero do not exist.
2921 // This will create a gap in the chart.
2922 if (errorBars
|| customBars
) {
2923 // point.length is either 2 (errorBars) or 3 (customBars)
2924 for (var k
= 0; k
< point
.length
; k
++) {
2925 if (point
[k
] <= 0) {
2930 } else if (point
<= 0) {
2934 // Fix null points to fit the display type standard.
2935 if (point
!== null) {
2936 series
.push([x
, point
]);
2938 series
.push([x
, errorBars
? [null, null] : customBars
? [null, null, null] : point
]);
2946 * Calculates the rolling average of a data set.
2947 * If originalData is [label, val], rolls the average of those.
2948 * If originalData is [label, [, it's interpreted as [value, stddev]
2949 * and the roll is returned in the same form, with appropriately reduced
2950 * stddev for each value.
2951 * Note that this is where fractional input (i.e. '5/10') is converted into
2953 * @param {Array} originalData The data in the appropriate format (see above)
2954 * @param {Number} rollPeriod The number of points over which to average the
2957 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2958 rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2959 var rollingData
= [];
2960 var sigma
= this.attr_("sigma");
2962 var low
, high
, i
, j
, y
, sum
, num_ok
, stddev
;
2963 if (this.fractions_
) {
2965 var den
= 0; // numerator/denominator
2967 for (i
= 0; i
< originalData
.length
; i
++) {
2968 num
+= originalData
[i
][1][0];
2969 den
+= originalData
[i
][1][1];
2970 if (i
- rollPeriod
>= 0) {
2971 num
-= originalData
[i
- rollPeriod
][1][0];
2972 den
-= originalData
[i
- rollPeriod
][1][1];
2975 var date
= originalData
[i
][0];
2976 var value
= den
? num
/ den
: 0.0;
2977 if (this.attr_("errorBars")) {
2978 if (this.attr_("wilsonInterval")) {
2979 // For more details on this confidence interval, see:
2980 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2982 var p
= value
< 0 ? 0 : value
, n
= den
;
2983 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2984 var denom
= 1 + sigma
* sigma
/ den
;
2985 low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2986 high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2987 rollingData
[i
] = [date
,
2988 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2990 rollingData
[i
] = [date
, [0, 0, 0]];
2993 stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2994 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2997 rollingData
[i
] = [date
, mult
* value
];
3000 } else if (this.attr_("customBars")) {
3005 for (i
= 0; i
< originalData
.length
; i
++) {
3006 var data
= originalData
[i
][1];
3008 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
3010 if (y
!== null && !isNaN(y
)) {
3016 if (i
- rollPeriod
>= 0) {
3017 var prev
= originalData
[i
- rollPeriod
];
3018 if (prev
[1][1] !== null && !isNaN(prev
[1][1])) {
3026 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
3027 1.0 * (mid
- low
) / count
,
3028 1.0 * (high
- mid
) / count
]];
3030 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
3034 // Calculate the rolling average for the first rollPeriod - 1 points where
3035 // there is not enough data to roll over the full number of points
3036 if (!this.attr_("errorBars")){
3037 if (rollPeriod
== 1) {
3038 return originalData
;
3041 for (i
= 0; i
< originalData
.length
; i
++) {
3044 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
3045 y
= originalData
[j
][1];
3046 if (y
=== null || isNaN(y
)) continue;
3048 sum
+= originalData
[j
][1];
3051 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
3053 rollingData
[i
] = [originalData
[i
][0], null];
3058 for (i
= 0; i
< originalData
.length
; i
++) {
3062 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
3063 y
= originalData
[j
][1][0];
3064 if (y
=== null || isNaN(y
)) continue;
3066 sum
+= originalData
[j
][1][0];
3067 variance
+= Math
.pow(originalData
[j
][1][1], 2);
3070 stddev
= Math
.sqrt(variance
) / num_ok
;
3071 rollingData
[i
] = [originalData
[i
][0],
3072 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
3074 // This explicitly preserves NaNs to aid with "independent series".
3075 // See testRollingAveragePreservesNaNs.
3076 var v
= (rollPeriod
== 1) ? originalData
[i
][1][0] : null;
3077 rollingData
[i
] = [originalData
[i
][0], [v
, v
, v
]];
3087 * Detects the type of the str (date or numeric) and sets the various
3088 * formatting attributes in this.attrs_ based on this type.
3089 * @param {String} str An x value.
3092 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
3094 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
3095 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
3096 str
.indexOf('/') >= 0 ||
3097 isNaN(parseFloat(str
))) {
3099 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
3100 // TODO(danvk): remove support for this format.
3104 this.setXAxisOptions_(isDate
);
3107 Dygraph
.prototype.setXAxisOptions_
= function(isDate
) {
3109 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3110 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3111 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3112 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3114 /** @private (shut up, jsdoc!) */
3115 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3116 // TODO(danvk): use Dygraph.numberValueFormatter here?
3117 /** @private (shut up, jsdoc!) */
3118 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3119 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3120 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3125 * Parses the value as a floating point number. This is like the parseFloat()
3126 * built-in, but with a few differences:
3127 * - the empty string is parsed as null, rather than NaN.
3128 * - if the string cannot be parsed at all, an error is logged.
3129 * If the string can't be parsed, this method returns null.
3130 * @param {String} x The string to be parsed
3131 * @param {Number} opt_line_no The line number from which the string comes.
3132 * @param {String} opt_line The text of the line from which the string comes.
3136 // Parse the x as a float or return null if it's not a number.
3137 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
3138 var val
= parseFloat(x
);
3139 if (!isNaN(val
)) return val
;
3141 // Try to figure out what happeend.
3142 // If the value is the empty string, parse it as null.
3143 if (/^ *$/.test(x
)) return null;
3145 // If it was actually "NaN", return it as NaN.
3146 if (/^ *nan *$/i.test(x
)) return NaN
;
3148 // Looks like a parsing error.
3149 var msg
= "Unable to parse '" + x
+ "' as a number";
3150 if (opt_line
!== null && opt_line_no
!== null) {
3151 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
3160 * Parses a string in a special csv format. We expect a csv file where each
3161 * line is a date point, and the first field in each line is the date string.
3162 * We also expect that all remaining fields represent series.
3163 * if the errorBars attribute is set, then interpret the fields as:
3164 * date, series1, stddev1, series2, stddev2, ...
3165 * @param {[Object]} data See above.
3167 * @return [Object] An array with one entry for each row. These entries
3168 * are an array of cells in that row. The first entry is the parsed x-value for
3169 * the row. The second, third, etc. are the y-values. These can take on one of
3170 * three forms, depending on the CSV and constructor parameters:
3172 * 2. [ value, stddev ]
3173 * 3. [ low value, center value, high value ]
3175 Dygraph
.prototype.parseCSV_
= function(data
) {
3177 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3178 var lines
= data
.split(line_delimiter
|| "\n");
3181 // Use the default delimiter or fall back to a tab if that makes sense.
3182 var delim
= this.attr_('delimiter');
3183 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
3188 if (!('labels' in this.user_attrs_
)) {
3189 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3191 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
3192 this.attributes_
.reparseSeries();
3197 var defaultParserSet
= false; // attempt to auto-detect x value type
3198 var expectedCols
= this.attr_("labels").length
;
3199 var outOfOrder
= false;
3200 for (var i
= start
; i
< lines
.length
; i
++) {
3201 var line
= lines
[i
];
3203 if (line
.length
=== 0) continue; // skip blank lines
3204 if (line
[0] == '#') continue; // skip comment lines
3205 var inFields
= line
.split(delim
);
3206 if (inFields
.length
< 2) continue;
3209 if (!defaultParserSet
) {
3210 this.detectTypeFromString_(inFields
[0]);
3211 xParser
= this.attr_("xValueParser");
3212 defaultParserSet
= true;
3214 fields
[0] = xParser(inFields
[0], this);
3216 // If fractions are expected, parse the numbers as "A/B
"
3217 if (this.fractions_) {
3218 for (j = 1; j < inFields.length; j++) {
3219 // TODO(danvk): figure out an appropriate way to flag parse errors.
3220 vals = inFields[j].split("/");
3221 if (vals.length != 2) {
3222 this.error('Expected fractional "num
/den
" values in CSV data ' +
3223 "but found a value
'" + inFields[j] + "' on line
" +
3224 (1 + i) + " ('" + line + "') which is not of
this form
.");
3227 fields[j] = [this.parseFloat_(vals[0], i, line),
3228 this.parseFloat_(vals[1], i, line)];
3231 } else if (this.attr_("errorBars
")) {
3232 // If there are error bars, values are (value, stddev) pairs
3233 if (inFields.length % 2 != 1) {
3234 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3235 'but line ' + (1 + i) + ' has an odd number of values (' +
3236 (inFields.length - 1) + "): '" + line + "'");
3238 for (j = 1; j < inFields.length; j += 2) {
3239 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3240 this.parseFloat_(inFields[j + 1], i, line)];
3242 } else if (this.attr_("customBars
")) {
3243 // Bars are a low;center;high tuple
3244 for (j = 1; j < inFields.length; j++) {
3245 var val = inFields[j];
3246 if (/^ *$/.test(val)) {
3247 fields[j] = [null, null, null];
3249 vals = val.split(";");
3250 if (vals.length == 3) {
3251 fields[j] = [ this.parseFloat_(vals[0], i, line),
3252 this.parseFloat_(vals[1], i, line),
3253 this.parseFloat_(vals[2], i, line) ];
3255 this.warn('When using customBars, values must be either blank ' +
3256 'or "low
;center
;high
" tuples (got "' + val +
3257 '" on line ' + (1+i));
3262 // Values are just numbers
3263 for (j = 1; j < inFields.length; j++) {
3264 fields[j] = this.parseFloat_(inFields[j], i, line);
3267 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3271 if (fields.length != expectedCols) {
3272 this.error("Number of columns
in line
" + i + " (" + fields.length +
3273 ") does not agree
with number of
labels (" + expectedCols +
3277 // If the user specified the 'labels' option and none of the cells of the
3278 // first row parsed correctly, then they probably double-specified the
3279 // labels. We go with the values set in the option, discard this row and
3280 // log a warning to the JS console.
3281 if (i === 0 && this.attr_('labels')) {
3282 var all_null = true;
3283 for (j = 0; all_null && j < fields.length; j++) {
3284 if (fields[j]) all_null = false;
3287 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
3288 "CSV
data ('" + line + "') appears to also contain labels
. " +
3289 "Will drop the CSV labels and
use the option labels
.");
3297 this.warn("CSV is out of order
; order it correctly to speed loading
.");
3298 ret.sort(function(a,b) { return a[0] - b[0]; });
3306 * The user has provided their data as a pre-packaged JS array. If the x values
3307 * are numeric, this is the same as dygraphs' internal format. If the x values
3308 * are dates, we need to convert them from Date objects to ms since epoch.
3309 * @param {[Object]} data
3310 * @return {[Object]} data with numeric x values.
3312 Dygraph.prototype.parseArray_ = function(data) {
3313 // Peek at the first x value to see if it's numeric.
3314 if (data.length === 0) {
3315 this.error("Can
't plot empty data set");
3318 if (data[0].length === 0) {
3319 this.error("Data set cannot contain an empty row");
3324 if (this.attr_("labels") === null) {
3325 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3326 "in the options parameter");
3327 this.attrs_.labels = [ "X" ];
3328 for (i = 1; i < data[0].length; i++) {
3329 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
3331 this.attributes_.reparseSeries();
3333 var num_labels = this.attr_("labels");
3334 if (num_labels.length != data[0].length) {
3335 this.error("Mismatch between number of labels (" + num_labels +
3336 ") and number of columns in array (" + data[0].length + ")");
3341 if (Dygraph.isDateLike(data[0][0])) {
3342 // Some intelligent defaults for a date x-axis.
3343 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3344 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3345 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3347 // Assume they're all dates
.
3348 var parsedData
= Dygraph
.clone(data
);
3349 for (i
= 0; i
< data
.length
; i
++) {
3350 if (parsedData
[i
].length
=== 0) {
3351 this.error("Row " + (1 + i
) + " of data is empty");
3354 if (parsedData
[i
][0] === null ||
3355 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3356 isNaN(parsedData
[i
][0].getTime())) {
3357 this.error("x value in row " + (1 + i
) + " is not a Date");
3360 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3364 // Some intelligent defaults for a numeric x-axis.
3365 /** @private (shut up, jsdoc!) */
3366 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3367 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3368 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3374 * Parses a DataTable object from gviz.
3375 * The data is expected to have a first column that is either a date or a
3376 * number. All subsequent columns must be numbers. If there is a clear mismatch
3377 * between this.xValueParser_ and the type of the first column, it will be
3378 * fixed. Fills out rawData_.
3379 * @param {[Object]} data See above.
3382 Dygraph
.prototype.parseDataTable_
= function(data
) {
3383 var shortTextForAnnotationNum
= function(num
) {
3384 // converts [0-9]+ [A-Z][a-z]*
3385 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3386 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3387 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3388 num
= Math
.floor(num
/ 26);
3390 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3391 num
= Math
.floor((num
- 1) / 26);
3396 var cols
= data
.getNumberOfColumns();
3397 var rows
= data
.getNumberOfRows();
3399 var indepType
= data
.getColumnType(0);
3400 if (indepType
== 'date' || indepType
== 'datetime') {
3401 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3402 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3403 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3404 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3405 } else if (indepType
== 'number') {
3406 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3407 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3408 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3409 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3411 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3412 "column 1 of DataTable input (Got '" + indepType
+ "')");
3416 // Array of the column indices which contain data (and not annotations).
3418 var annotationCols
= {}; // data index -> [annotation cols]
3419 var hasAnnotations
= false;
3421 for (i
= 1; i
< cols
; i
++) {
3422 var type
= data
.getColumnType(i
);
3423 if (type
== 'number') {
3425 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3426 // This is OK -- it's an annotation column.
3427 var dataIdx
= colIdx
[colIdx
.length
- 1];
3428 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3429 annotationCols
[dataIdx
] = [i
];
3431 annotationCols
[dataIdx
].push(i
);
3433 hasAnnotations
= true;
3435 this.error("Only 'number' is supported as a dependent type with Gviz." +
3436 " 'string' is only supported if displayAnnotations is true");
3440 // Read column labels
3441 // TODO(danvk): add support back for errorBars
3442 var labels
= [data
.getColumnLabel(0)];
3443 for (i
= 0; i
< colIdx
.length
; i
++) {
3444 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3445 if (this.attr_("errorBars")) i
+= 1;
3447 this.attrs_
.labels
= labels
;
3448 cols
= labels
.length
;
3451 var outOfOrder
= false;
3452 var annotations
= [];
3453 for (i
= 0; i
< rows
; i
++) {
3455 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3456 data
.getValue(i
, 0) === null) {
3457 this.warn("Ignoring row " + i
+
3458 " of DataTable because of undefined or null first column.");
3462 if (indepType
== 'date' || indepType
== 'datetime') {
3463 row
.push(data
.getValue(i
, 0).getTime());
3465 row
.push(data
.getValue(i
, 0));
3467 if (!this.attr_("errorBars")) {
3468 for (j
= 0; j
< colIdx
.length
; j
++) {
3469 var col
= colIdx
[j
];
3470 row
.push(data
.getValue(i
, col
));
3471 if (hasAnnotations
&&
3472 annotationCols
.hasOwnProperty(col
) &&
3473 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3475 ann
.series
= data
.getColumnLabel(col
);
3477 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3479 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3480 if (k
) ann
.text
+= "\n";
3481 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3483 annotations
.push(ann
);
3487 // Strip out infinities, which give dygraphs problems later on.
3488 for (j
= 0; j
< row
.length
; j
++) {
3489 if (!isFinite(row
[j
])) row
[j
] = null;
3492 for (j
= 0; j
< cols
- 1; j
++) {
3493 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3496 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3503 this.warn("DataTable is out of order; order it correctly to speed loading.");
3504 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3506 this.rawData_
= ret
;
3508 if (annotations
.length
> 0) {
3509 this.setAnnotations(annotations
, true);
3511 this.attributes_
.reparseSeries();
3515 * Get the CSV data. If it's in a function, call that function. If it's in a
3516 * file, do an XMLHttpRequest to get it.
3519 Dygraph
.prototype.start_
= function() {
3520 var data
= this.file_
;
3522 // Functions can return references of all other types.
3523 if (typeof data
== 'function') {
3527 if (Dygraph
.isArrayLike(data
)) {
3528 this.rawData_
= this.parseArray_(data
);
3530 } else if (typeof data
== 'object' &&
3531 typeof data
.getColumnRange
== 'function') {
3532 // must be a DataTable from gviz.
3533 this.parseDataTable_(data
);
3535 } else if (typeof data
== 'string') {
3536 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3537 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3538 if (line_delimiter
) {
3539 this.loadedEvent_(data
);
3541 var req
= new XMLHttpRequest();
3543 req
.onreadystatechange
= function () {
3544 if (req
.readyState
== 4) {
3545 if (req
.status
=== 200 || // Normal http
3546 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3547 caller
.loadedEvent_(req
.responseText
);
3552 req
.open("GET", data
, true);
3556 this.error("Unknown data format: " + (typeof data
));
3561 * Changes various properties of the graph. These can include:
3563 * <li>file: changes the source data for the graph</li>
3564 * <li>errorBars: changes whether the data contains stddev</li>
3567 * There's a huge variety of options that can be passed to this method. For a
3568 * full list, see http://dygraphs.com/options.html.
3570 * @param {Object} attrs The new properties and values
3571 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3572 * call to updateOptions(). If you know better, you can pass true to explicitly
3573 * block the redraw. This can be useful for chaining updateOptions() calls,
3574 * avoiding the occasional infinite loop and preventing redraws when it's not
3575 * necessary (e.g. when updating a callback).
3577 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3578 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3580 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3581 var file
= input_attrs
.file
;
3582 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3584 // TODO(danvk): this is a mess. Move these options into attr_.
3585 if ('rollPeriod' in attrs
) {
3586 this.rollPeriod_
= attrs
.rollPeriod
;
3588 if ('dateWindow' in attrs
) {
3589 this.dateWindow_
= attrs
.dateWindow
;
3590 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3591 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3594 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3595 this.zoomed_y_
= (attrs
.valueRange
!== null);
3598 // TODO(danvk): validate per-series options.
3603 // highlightCircleSize
3605 // Check if this set options will require new points.
3606 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3608 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3610 this.attributes_
.reparseSeries();
3614 if (!block_redraw
) this.start_();
3616 if (!block_redraw
) {
3617 if (requiresNewPoints
) {
3620 this.renderGraph_(false);
3627 * Returns a copy of the options with deprecated names converted into current
3628 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3629 * interested in that, they should save a copy before calling this.
3632 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3634 for (var k
in attrs
) {
3635 if (k
== 'file') continue;
3636 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3639 var set
= function(axis
, opt
, value
) {
3640 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3641 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3642 my_attrs
.axes
[axis
][opt
] = value
;
3644 var map
= function(opt
, axis
, new_opt
) {
3645 if (typeof(attrs
[opt
]) != 'undefined') {
3646 Dygraph
.warn("Option " + opt
+ " is deprecated. Use the " +
3647 new_opt
+ " option for the " + axis
+ " axis instead. " +
3648 "(e.g. { axes : { " + axis
+ " : { " + new_opt
+ " : ... } } } " +
3649 "(see http://dygraphs.com/per-axis.html for more information.");
3650 set(axis
, new_opt
, attrs
[opt
]);
3651 delete my_attrs
[opt
];
3655 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3656 map('xValueFormatter', 'x', 'valueFormatter');
3657 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3658 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3659 map('xTicker', 'x', 'ticker');
3660 map('yValueFormatter', 'y', 'valueFormatter');
3661 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3662 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3663 map('yTicker', 'y', 'ticker');
3668 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3669 * containing div (which has presumably changed size since the dygraph was
3670 * instantiated. If the width/height are specified, the div will be resized.
3672 * This is far more efficient than destroying and re-instantiating a
3673 * Dygraph, since it doesn't have to reparse the underlying data.
3675 * @param {Number} [width] Width (in pixels)
3676 * @param {Number} [height] Height (in pixels)
3678 Dygraph
.prototype.resize
= function(width
, height
) {
3679 if (this.resize_lock
) {
3682 this.resize_lock
= true;
3684 if ((width
=== null) != (height
=== null)) {
3685 this.warn("Dygraph.resize() should be called with zero parameters or " +
3686 "two non-NULL parameters. Pretending it was zero.");
3687 width
= height
= null;
3690 var old_width
= this.width_
;
3691 var old_height
= this.height_
;
3694 this.maindiv_
.style
.width
= width
+ "px";
3695 this.maindiv_
.style
.height
= height
+ "px";
3696 this.width_
= width
;
3697 this.height_
= height
;
3699 this.width_
= this.maindiv_
.clientWidth
;
3700 this.height_
= this.maindiv_
.clientHeight
;
3703 this.resizeElements_();
3705 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3709 this.resize_lock
= false;
3713 * Adjusts the number of points in the rolling average. Updates the graph to
3714 * reflect the new averaging period.
3715 * @param {Number} length Number of points over which to average the data.
3717 Dygraph
.prototype.adjustRoll
= function(length
) {
3718 this.rollPeriod_
= length
;
3723 * Returns a boolean array of visibility statuses.
3725 Dygraph
.prototype.visibility
= function() {
3726 // Do lazy-initialization, so that this happens after we know the number of
3728 if (!this.attr_("visibility")) {
3729 this.attrs_
.visibility
= [];
3731 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3732 while (this.attr_("visibility").length
< this.numColumns() - 1) {
3733 this.attrs_
.visibility
.push(true);
3735 return this.attr_("visibility");
3739 * Changes the visiblity of a series.
3741 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3742 var x
= this.visibility();
3743 if (num
< 0 || num
>= x
.length
) {
3744 this.warn("invalid series number in setVisibility: " + num
);
3752 * How large of an area will the dygraph render itself in?
3753 * This is used for testing.
3754 * @return A {width: w, height: h} object.
3757 Dygraph
.prototype.size
= function() {
3758 return { width
: this.width_
, height
: this.height_
};
3762 * Update the list of annotations and redraw the chart.
3763 * See dygraphs.com/annotations.html for more info on how to use annotations.
3764 * @param ann {Array} An array of annotation objects.
3765 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3767 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3768 // Only add the annotation CSS rule once we know it will be used.
3769 Dygraph
.addAnnotationRule();
3770 this.annotations_
= ann
;
3771 if (!this.layout_
) {
3772 this.warn("Tried to setAnnotations before dygraph was ready. " +
3773 "Try setting them in a drawCallback. See " +
3774 "dygraphs.com/tests/annotation.html");
3778 this.layout_
.setAnnotations(this.annotations_
);
3779 if (!suppressDraw
) {
3785 * Return the list of annotations.
3787 Dygraph
.prototype.annotations
= function() {
3788 return this.annotations_
;
3792 * Get the list of label names for this graph. The first column is the
3793 * x-axis, so the data series names start at index 1.
3795 * Returns null when labels have not yet been defined.
3797 Dygraph
.prototype.getLabels
= function() {
3798 var labels
= this.attr_("labels");
3799 return labels
? labels
.slice() : null;
3803 * Get the index of a series (column) given its name. The first column is the
3804 * x-axis, so the data series start with index 1.
3806 Dygraph
.prototype.indexFromSetName
= function(name
) {
3807 return this.setIndexByName_
[name
];
3811 * Get the internal dataset index given its name. These are numbered starting from 0,
3812 * and only count visible sets.
3815 Dygraph
.prototype.datasetIndexFromSetName_
= function(name
) {
3816 return this.datasetIndex_
[this.indexFromSetName(name
)];
3821 * Adds a default style for the annotation CSS classes to the document. This is
3822 * only executed when annotations are actually used. It is designed to only be
3823 * called once -- all calls after the first will return immediately.
3825 Dygraph
.addAnnotationRule
= function() {
3826 // TODO(danvk): move this function into plugins/annotations.js
?
3827 if (Dygraph
.addedAnnotationCSS
) return;
3829 var rule
= "border: 1px solid black; " +
3830 "background-color: white; " +
3831 "text-align: center;";
3833 var styleSheetElement
= document
.createElement("style");
3834 styleSheetElement
.type
= "text/css";
3835 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3837 // Find the first style sheet that we can access.
3838 // We may not add a rule to a style sheet from another domain for security
3839 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3840 // adds its own style sheets from google.com.
3841 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3842 if (document
.styleSheets
[i
].disabled
) continue;
3843 var mysheet
= document
.styleSheets
[i
];
3845 if (mysheet
.insertRule
) { // Firefox
3846 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3847 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3848 } else if (mysheet
.addRule
) { // IE
3849 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3851 Dygraph
.addedAnnotationCSS
= true;
3854 // Was likely a security exception.
3858 this.warn("Unable to add default annotation CSS rule; display may be off.");
3861 // Older pages may still use this name.
3862 var DateGraph
= Dygraph
;