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. In that case,
470 // use the user-specified attributes if present. If not, use zero
471 // and assume the user will call resize to fix things later.
472 this.width_
= div
.clientWidth
|| attrs
.width
|| 0;
473 this.height_
= div
.clientHeight
|| attrs
.height
|| 0;
475 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
476 if (attrs
.stackedGraph
) {
477 attrs
.fillGraph
= true;
478 // TODO(nikhilk): Add any other stackedGraph checks here.
481 // DEPRECATION WARNING: All option processing should be moved from
482 // attrs_ and user_attrs_ to options_, which holds all this information.
484 // Dygraphs has many options, some of which interact with one another.
485 // To keep track of everything, we maintain two sets of options:
487 // this.user_attrs_ only options explicitly set by the user.
488 // this.attrs_ defaults, options derived from user_attrs_, data.
490 // Options are then accessed this.attr_('attr'), which first looks at
491 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
492 // defaults without overriding behavior that the user specifically asks for.
493 this.user_attrs_
= {};
494 Dygraph
.update(this.user_attrs_
, attrs
);
496 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
498 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
500 this.boundaryIds_
= [];
501 this.setIndexByName_
= {};
502 this.datasetIndex_
= [];
504 this.registeredEvents_
= [];
505 this.eventListeners_
= {};
507 this.attributes_
= new DygraphOptions(this);
509 // Create the containing DIV and other interactive elements
510 this.createInterface_();
514 var plugins
= Dygraph
.PLUGINS
.concat(this.getOption('plugins'));
515 for (var i
= 0; i
< plugins
.length
; i
++) {
516 var Plugin
= plugins
[i
];
517 var pluginInstance
= new Plugin();
519 plugin
: pluginInstance
,
525 var handlers
= pluginInstance
.activate(this);
526 for (var eventName
in handlers
) {
527 // TODO(danvk): validate eventName.
528 pluginDict
.events
[eventName
] = handlers
[eventName
];
531 this.plugins_
.push(pluginDict
);
534 // At this point, plugins can no longer register event handlers.
535 // Construct a map from event -> ordered list of [callback, plugin].
536 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
537 var plugin_dict
= this.plugins_
[i
];
538 for (var eventName
in plugin_dict
.events
) {
539 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
540 var callback
= plugin_dict
.events
[eventName
];
542 var pair
= [plugin_dict
.plugin
, callback
];
543 if (!(eventName
in this.eventListeners_
)) {
544 this.eventListeners_
[eventName
] = [pair
];
546 this.eventListeners_
[eventName
].push(pair
);
551 this.createDragInterface_();
557 * Triggers a cascade of events to the various plugins which are interested in them.
558 * Returns true if the "default behavior" should be performed, i.e. if none of
559 * the event listeners called event.preventDefault().
562 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
563 if (!(name
in this.eventListeners_
)) return true;
565 // QUESTION: can we use objects & prototypes to speed this up?
569 defaultPrevented
: false,
570 preventDefault
: function() {
571 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
572 e
.defaultPrevented
= true;
574 propagationStopped
: false,
575 stopPropagation
: function() {
576 e
.propagationStopped
= true;
579 Dygraph
.update(e
, extra_props
);
581 var callback_plugin_pairs
= this.eventListeners_
[name
];
582 if (callback_plugin_pairs
) {
583 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
584 var plugin
= callback_plugin_pairs
[i
][0];
585 var callback
= callback_plugin_pairs
[i
][1];
586 callback
.call(plugin
, e
);
587 if (e
.propagationStopped
) break;
590 return e
.defaultPrevented
;
594 * Returns the zoomed status of the chart for one or both axes.
596 * Axis is an optional parameter. Can be set to 'x' or 'y'.
598 * The zoomed status for an axis is set whenever a user zooms using the mouse
599 * or when the dateWindow or valueRange are updated (unless the
600 * isZoomedIgnoreProgrammaticZoom option is also specified).
602 Dygraph
.prototype.isZoomed
= function(axis
) {
603 if (axis
=== null || axis
=== undefined
) {
604 return this.zoomed_x_
|| this.zoomed_y_
;
606 if (axis
=== 'x') return this.zoomed_x_
;
607 if (axis
=== 'y') return this.zoomed_y_
;
608 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
612 * Returns information about the Dygraph object, including its containing ID.
614 Dygraph
.prototype.toString
= function() {
615 var maindiv
= this.maindiv_
;
616 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
617 return "[Dygraph " + id
+ "]";
622 * Returns the value of an option. This may be set by the user (either in the
623 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
625 * @param { String } name The name of the option, e.g. 'rollPeriod'.
626 * @param { String } [seriesName] The name of the series to which the option
627 * will be applied. If no per-series value of this option is available, then
628 * the global value is returned. This is optional.
629 * @return { ... } The value of the option.
631 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
632 // <REMOVE_FOR_COMBINED>
633 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
634 this.error('Must include options reference JS for testing');
635 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
636 this.error('Dygraphs is using property ' + name
+ ', which has no entry ' +
637 'in the Dygraphs.OPTIONS_REFERENCE listing.');
638 // Only log this error once.
639 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
641 // </REMOVE_FOR_COMBINED
>
642 return seriesName
? this.attributes_
.getForSeries(name
, seriesName
) : this.attributes_
.get(name
);
646 * Returns the current value for an option, as set in the constructor or via
647 * updateOptions. You may pass in an (optional) series name to get per-series
648 * values for the option.
650 * All values returned by this method should be considered immutable. If you
651 * modify them, there is no guarantee that the changes will be honored or that
652 * dygraphs will remain in a consistent state. If you want to modify an option,
653 * use updateOptions() instead.
655 * @param { String } name The name of the option (e.g. 'strokeWidth')
656 * @param { String } [opt_seriesName] Series name to get per-series values.
657 * @return { ... } The value of the option.
659 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
660 return this.attr_(name
, opt_seriesName
);
663 Dygraph
.prototype.getOptionForAxis
= function(name
, axis
) {
664 return this.attributes_
.getForAxis(name
, axis
);
669 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
670 * @return { ... } A function mapping string -> option value
672 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
674 return function(opt
) {
675 var axis_opts
= self
.user_attrs_
.axes
;
676 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
677 return axis_opts
[axis
][opt
];
679 // user-specified attributes always trump defaults, even if they're less
681 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
682 return self
.user_attrs_
[opt
];
685 axis_opts
= self
.attrs_
.axes
;
686 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
687 return axis_opts
[axis
][opt
];
689 // check old-style axis options
690 // TODO(danvk): add a deprecation warning if either of these match.
691 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
692 return self
.axes_
[0][opt
];
693 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
694 return self
.axes_
[1][opt
];
696 return self
.attr_(opt
);
701 * Returns the current rolling period, as set by the user or an option.
702 * @return {Number} The number of points in the rolling window
704 Dygraph
.prototype.rollPeriod
= function() {
705 return this.rollPeriod_
;
709 * Returns the currently-visible x-range. This can be affected by zooming,
710 * panning or a call to updateOptions.
711 * Returns a two-element array: [left, right].
712 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
714 Dygraph
.prototype.xAxisRange
= function() {
715 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
719 * Returns the lower- and upper-bound x-axis values of the
722 Dygraph
.prototype.xAxisExtremes
= function() {
723 var pad
= this.attr_('xRangePad') / this.plotter_
.area
.w
;
724 if (this.numRows() === 0) {
725 return [0 - pad
, 1 + pad
];
727 var left
= this.rawData_
[0][0];
728 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
730 // Must keep this in sync with dygraph-layout _evaluateLimits()
731 var range
= right
- left
;
733 right
+= range
* pad
;
735 return [left
, right
];
739 * Returns the currently-visible y-range for an axis. This can be affected by
740 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
741 * called with no arguments, returns the range of the first axis.
742 * Returns a two-element array: [bottom, top].
744 Dygraph
.prototype.yAxisRange
= function(idx
) {
745 if (typeof(idx
) == "undefined") idx
= 0;
746 if (idx
< 0 || idx
>= this.axes_
.length
) {
749 var axis
= this.axes_
[idx
];
750 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
754 * Returns the currently-visible y-ranges for each axis. This can be affected by
755 * zooming, panning, calls to updateOptions, etc.
756 * Returns an array of [bottom, top] pairs, one for each y-axis.
758 Dygraph
.prototype.yAxisRanges
= function() {
760 for (var i
= 0; i
< this.axes_
.length
; i
++) {
761 ret
.push(this.yAxisRange(i
));
766 // TODO(danvk): use these functions throughout dygraphs.
768 * Convert from data coordinates to canvas/div X/Y coordinates.
769 * If specified, do this conversion for the coordinate system of a particular
770 * axis. Uses the first axis by default.
771 * Returns a two-element array: [X, Y]
773 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
774 * instead of toDomCoords(null, y, axis).
776 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
777 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
781 * Convert from data x coordinates to canvas/div X coordinate.
782 * If specified, do this conversion for the coordinate system of a particular
784 * Returns a single value or null if x is null.
786 Dygraph
.prototype.toDomXCoord
= function(x
) {
791 var area
= this.plotter_
.area
;
792 var xRange
= this.xAxisRange();
793 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
797 * Convert from data x coordinates to canvas/div Y coordinate and optional
798 * axis. Uses the first axis by default.
800 * returns a single value or null if y is null.
802 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
803 var pct
= this.toPercentYCoord(y
, axis
);
808 var area
= this.plotter_
.area
;
809 return area
.y
+ pct
* area
.h
;
813 * Convert from canvas/div coords to data coordinates.
814 * If specified, do this conversion for the coordinate system of a particular
815 * axis. Uses the first axis by default.
816 * Returns a two-element array: [X, Y].
818 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
819 * instead of toDataCoords(null, y, axis).
821 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
822 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
826 * Convert from canvas/div x coordinate to data coordinate.
828 * If x is null, this returns null.
830 Dygraph
.prototype.toDataXCoord
= function(x
) {
835 var area
= this.plotter_
.area
;
836 var xRange
= this.xAxisRange();
837 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
841 * Convert from canvas/div y coord to value.
843 * If y is null, this returns null.
844 * if axis is null, this uses the first axis.
846 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
851 var area
= this.plotter_
.area
;
852 var yRange
= this.yAxisRange(axis
);
854 if (typeof(axis
) == "undefined") axis
= 0;
855 if (!this.axes_
[axis
].logscale
) {
856 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
858 // Computing the inverse of toDomCoord.
859 var pct
= (y
- area
.y
) / area
.h
;
861 // Computing the inverse of toPercentYCoord. The function was arrived at with
862 // the following steps:
864 // Original calcuation:
865 // pct = (logr1 - Dygraph.log10(y)) / (logr1
- Dygraph
.log10(yRange
[0]));
867 // Move denominator to both sides:
868 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
870 // subtract logr1, and take the negative value.
871 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
873 // Swap both sides of the equation, and we can compute the log of the
874 // return value. Which means we just need to use that as the exponent in
876 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
878 var logr1
= Dygraph
.log10(yRange
[1]);
879 var exponent
= logr1
- (pct
* (logr1
- Dygraph
.log10(yRange
[0])));
880 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
886 * Converts a y for an axis to a percentage from the top to the
887 * bottom of the drawing area.
889 * If the coordinate represents a value visible on the canvas, then
890 * the value will be between 0 and 1, where 0 is the top of the canvas.
891 * However, this method will return values outside the range, as
892 * values can fall outside the canvas.
894 * If y is null, this returns null.
895 * if axis is null, this uses the first axis.
897 * @param { Number } y The data y-coordinate.
898 * @param { Number } [axis] The axis number on which the data coordinate lives.
899 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
901 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
905 if (typeof(axis
) == "undefined") axis
= 0;
907 var yRange
= this.yAxisRange(axis
);
910 var logscale
= this.attributes_
.getForAxis("logscale", axis
);
912 // yRange[1] - y is unit distance from the bottom.
913 // yRange[1] - yRange[0] is the scale of the range.
914 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
915 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
917 var logr1
= Dygraph
.log10(yRange
[1]);
918 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- Dygraph
.log10(yRange
[0]));
924 * Converts an x value to a percentage from the left to the right of
927 * If the coordinate represents a value visible on the canvas, then
928 * the value will be between 0 and 1, where 0 is the left of the canvas.
929 * However, this method will return values outside the range, as
930 * values can fall outside the canvas.
932 * If x is null, this returns null.
933 * @param { Number } x The data x-coordinate.
934 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
936 Dygraph
.prototype.toPercentXCoord
= function(x
) {
941 var xRange
= this.xAxisRange();
942 return (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
946 * Returns the number of columns (including the independent variable).
947 * @return { Integer } The number of columns.
949 Dygraph
.prototype.numColumns
= function() {
950 if (!this.rawData_
) return 0;
951 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
955 * Returns the number of rows (excluding any header/label row).
956 * @return { Integer } The number of rows, less any header.
958 Dygraph
.prototype.numRows
= function() {
959 if (!this.rawData_
) return 0;
960 return this.rawData_
.length
;
964 * Returns the value in the given row and column. If the row and column exceed
965 * the bounds on the data, returns null. Also returns null if the value is
967 * @param { Number} row The row number of the data (0-based). Row 0 is the
968 * first row of data, not a header row.
969 * @param { Number} col The column number of the data (0-based)
970 * @return { Number } The value in the specified cell or null if the row/col
973 Dygraph
.prototype.getValue
= function(row
, col
) {
974 if (row
< 0 || row
> this.rawData_
.length
) return null;
975 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
977 return this.rawData_
[row
][col
];
981 * Generates interface elements for the Dygraph: a containing div, a div to
982 * display the current point, and a textbox to adjust the rolling average
983 * period. Also creates the Renderer/Layout elements.
986 Dygraph
.prototype.createInterface_
= function() {
987 // Create the all-enclosing graph div
988 var enclosing
= this.maindiv_
;
990 this.graphDiv
= document
.createElement("div");
992 // TODO(danvk): any other styles that are useful to set here?
993 this.graphDiv
.style
.textAlign
= 'left'; // This is a CSS "reset"
994 enclosing
.appendChild(this.graphDiv
);
996 // Create the canvas for interactive parts of the chart.
997 this.canvas_
= Dygraph
.createCanvas();
998 this.canvas_
.style
.position
= "absolute";
1000 // ... and for static parts of the chart.
1001 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
1003 this.resizeElements_();
1005 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
1006 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
1008 // The interactive parts of the graph are drawn on top of the chart.
1009 this.graphDiv
.appendChild(this.hidden_
);
1010 this.graphDiv
.appendChild(this.canvas_
);
1011 this.mouseEventElement_
= this.createMouseEventElement_();
1013 // Create the grapher
1014 this.layout_
= new DygraphLayout(this);
1018 this.mouseMoveHandler_
= function(e
) {
1019 dygraph
.mouseMove_(e
);
1022 this.mouseOutHandler_
= function(e
) {
1023 // The mouse has left the chart if:
1024 // 1. e.target is inside the chart
1025 // 2. e.relatedTarget is outside the chart
1026 var target
= e
.target
|| e
.fromElement
;
1027 var relatedTarget
= e
.relatedTarget
|| e
.toElement
;
1028 if (Dygraph
.isNodeContainedBy(target
, dygraph
.graphDiv
) &&
1029 !Dygraph
.isNodeContainedBy(relatedTarget
, dygraph
.graphDiv
)) {
1030 dygraph
.mouseOut_(e
);
1034 this.addAndTrackEvent(window
, 'mouseout', this.mouseOutHandler_
);
1035 this.addAndTrackEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1037 // Don't recreate and register the resize handler on subsequent calls.
1038 // This happens when the graph is resized.
1039 if (!this.resizeHandler_
) {
1040 this.resizeHandler_
= function(e
) {
1044 // Update when the window is resized.
1045 // TODO(danvk): drop frames depending on complexity of the chart.
1046 this.addAndTrackEvent(window
, 'resize', this.resizeHandler_
);
1050 Dygraph
.prototype.resizeElements_
= function() {
1051 this.graphDiv
.style
.width
= this.width_
+ "px";
1052 this.graphDiv
.style
.height
= this.height_
+ "px";
1053 this.canvas_
.width
= this.width_
;
1054 this.canvas_
.height
= this.height_
;
1055 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
1056 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
1057 this.hidden_
.width
= this.width_
;
1058 this.hidden_
.height
= this.height_
;
1059 this.hidden_
.style
.width
= this.width_
+ "px"; // for IE
1060 this.hidden_
.style
.height
= this.height_
+ "px"; // for IE
1064 * Detach DOM elements in the dygraph and null out all data references.
1065 * Calling this when you're done with a dygraph can dramatically reduce memory
1066 * usage. See, e.g., the tests/perf.html example.
1068 Dygraph
.prototype.destroy
= function() {
1069 this.canvas_ctx_
.restore();
1070 this.hidden_ctx_
.restore();
1072 var removeRecursive
= function(node
) {
1073 while (node
.hasChildNodes()) {
1074 removeRecursive(node
.firstChild
);
1075 node
.removeChild(node
.firstChild
);
1079 this.removeTrackedEvents_();
1081 // remove mouse event handlers (This may not be necessary anymore)
1082 Dygraph
.removeEvent(window
, 'mouseout', this.mouseOutHandler_
);
1083 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1085 // remove window handlers
1086 Dygraph
.removeEvent(window
,'resize',this.resizeHandler_
);
1087 this.resizeHandler_
= null;
1089 removeRecursive(this.maindiv_
);
1091 var nullOut
= function(obj
) {
1092 for (var n
in obj
) {
1093 if (typeof(obj
[n
]) === 'object') {
1098 // These may not all be necessary, but it can't hurt...
1099 nullOut(this.layout_
);
1100 nullOut(this.plotter_
);
1105 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1106 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1107 * or the zoom rectangles) is done on this.canvas_.
1108 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1109 * @return {Object} The newly-created canvas
1112 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1113 var h
= Dygraph
.createCanvas();
1114 h
.style
.position
= "absolute";
1115 // TODO(danvk): h should be offset from canvas. canvas needs to include
1116 // some extra area to make it easier to zoom in on the far left and far
1117 // right. h needs to be precisely the plot area, so that clipping occurs.
1118 h
.style
.top
= canvas
.style
.top
;
1119 h
.style
.left
= canvas
.style
.left
;
1120 h
.width
= this.width_
;
1121 h
.height
= this.height_
;
1122 h
.style
.width
= this.width_
+ "px"; // for IE
1123 h
.style
.height
= this.height_
+ "px"; // for IE
1128 * Creates an overlay element used to handle mouse events.
1129 * @return {Object} The mouse event element.
1132 Dygraph
.prototype.createMouseEventElement_
= function() {
1133 if (this.isUsingExcanvas_
) {
1134 var elem
= document
.createElement("div");
1135 elem
.style
.position
= 'absolute';
1136 elem
.style
.backgroundColor
= 'white';
1137 elem
.style
.filter
= 'alpha(opacity=0)';
1138 elem
.style
.width
= this.width_
+ "px";
1139 elem
.style
.height
= this.height_
+ "px";
1140 this.graphDiv
.appendChild(elem
);
1143 return this.canvas_
;
1148 * Generate a set of distinct colors for the data series. This is done with a
1149 * color wheel. Saturation/Value are customizable, and the hue is
1150 * equally-spaced around the color wheel. If a custom set of colors is
1151 * specified, that is used instead.
1154 Dygraph
.prototype.setColors_
= function() {
1155 var labels
= this.getLabels();
1156 var num
= labels
.length
- 1;
1158 this.colorsMap_
= {};
1159 var colors
= this.attr_('colors');
1162 var sat
= this.attr_('colorSaturation') || 1.0;
1163 var val
= this.attr_('colorValue') || 0.5;
1164 var half
= Math
.ceil(num
/ 2);
1165 for (i
= 1; i
<= num
; i
++) {
1166 if (!this.visibility()[i
-1]) continue;
1167 // alternate colors for high contrast.
1168 var idx
= i
% 2 ? Math
.ceil(i
/ 2) : (half + i / 2);
1169 var hue
= (1.0 * idx
/ (1 + num
));
1170 var colorStr
= Dygraph
.hsvToRGB(hue
, sat
, val
);
1171 this.colors_
.push(colorStr
);
1172 this.colorsMap_
[labels
[i
]] = colorStr
;
1175 for (i
= 0; i
< num
; i
++) {
1176 if (!this.visibility()[i
]) continue;
1177 var colorStr
= colors
[i
% colors
.length
];
1178 this.colors_
.push(colorStr
);
1179 this.colorsMap_
[labels
[1 + i
]] = colorStr
;
1185 * Return the list of colors. This is either the list of colors passed in the
1186 * attributes or the autogenerated list of rgb(r,g,b) strings.
1187 * This does not return colors for invisible series.
1188 * @return {Array<string>} The list of colors.
1190 Dygraph
.prototype.getColors
= function() {
1191 return this.colors_
;
1195 * Returns a few attributes of a series, i.e. its color, its visibility, which
1196 * axis it's assigned to, and its column in the original data.
1197 * Returns null if the series does not exist.
1198 * Otherwise, returns an object with column, visibility, color and axis properties.
1199 * The "axis" property will be set to 1 for y1 and 2 for y2.
1200 * The "column" property can be fed back into getValue(row, column) to get
1201 * values for this series.
1203 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1205 var labels
= this.getLabels();
1206 for (var i
= 1; i
< labels
.length
; i
++) {
1207 if (labels
[i
] == series_name
) {
1212 if (idx
== -1) return null;
1217 visible
: this.visibility()[idx
- 1],
1218 color
: this.colorsMap_
[series_name
],
1219 axis
: 1 + this.attributes_
.axisForSeries(series_name
)
1224 * Create the text box to adjust the averaging period
1227 Dygraph
.prototype.createRollInterface_
= function() {
1228 // Create a roller if one doesn't exist already.
1229 if (!this.roller_
) {
1230 this.roller_
= document
.createElement("input");
1231 this.roller_
.type
= "text";
1232 this.roller_
.style
.display
= "none";
1233 this.graphDiv
.appendChild(this.roller_
);
1236 var display
= this.attr_('showRoller') ? 'block' : 'none';
1238 var area
= this.plotter_
.area
;
1239 var textAttr
= { "position": "absolute",
1241 "top": (area
.y
+ area
.h
- 25) + "px",
1242 "left": (area
.x
+ 1) + "px",
1245 this.roller_
.size
= "2";
1246 this.roller_
.value
= this.rollPeriod_
;
1247 for (var name
in textAttr
) {
1248 if (textAttr
.hasOwnProperty(name
)) {
1249 this.roller_
.style
[name
] = textAttr
[name
];
1254 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1259 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1260 * canvas (i.e. DOM Coords).
1262 Dygraph
.prototype.dragGetX_
= function(e
, context
) {
1263 return Dygraph
.pageX(e
) - context
.px
;
1268 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1269 * canvas (i.e. DOM Coords).
1271 Dygraph
.prototype.dragGetY_
= function(e
, context
) {
1272 return Dygraph
.pageY(e
) - context
.py
;
1276 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1280 Dygraph
.prototype.createDragInterface_
= function() {
1282 // Tracks whether the mouse is down right now
1284 isPanning
: false, // is this drag part of a pan?
1285 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1286 dragStartX
: null, // pixel coordinates
1287 dragStartY
: null, // pixel coordinates
1288 dragEndX
: null, // pixel coordinates
1289 dragEndY
: null, // pixel coordinates
1290 dragDirection
: null,
1291 prevEndX
: null, // pixel coordinates
1292 prevEndY
: null, // pixel coordinates
1293 prevDragDirection
: null,
1294 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1296 // The value on the left side of the graph when a pan operation starts.
1297 initialLeftmostDate
: null,
1299 // The number of units each pixel spans. (This won't be valid for log
1301 xUnitsPerPixel
: null,
1303 // TODO(danvk): update this comment
1304 // The range in second/value units that the viewport encompasses during a
1305 // panning operation.
1308 // Top-left corner of the canvas, in DOM coords
1309 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1313 // Values for use with panEdgeFraction, which limit how far outside the
1314 // graph's data boundaries it can be panned.
1315 boundedDates
: null, // [minDate, maxDate]
1316 boundedValues
: null, // [[minValue, maxValue] ...]
1318 // We cover iframes during mouse interactions. See comments in
1319 // dygraph-utils.js for more info on why this is a good idea.
1320 tarp
: new Dygraph
.IFrameTarp(),
1322 // contextB is the same thing as this context object but renamed.
1323 initializeMouseDown
: function(event
, g
, contextB
) {
1324 // prevents mouse drags from selecting page text.
1325 if (event
.preventDefault
) {
1326 event
.preventDefault(); // Firefox, Chrome, etc.
1328 event
.returnValue
= false; // IE
1329 event
.cancelBubble
= true;
1332 contextB
.px
= Dygraph
.findPosX(g
.canvas_
);
1333 contextB
.py
= Dygraph
.findPosY(g
.canvas_
);
1334 contextB
.dragStartX
= g
.dragGetX_(event
, contextB
);
1335 contextB
.dragStartY
= g
.dragGetY_(event
, contextB
);
1336 contextB
.cancelNextDblclick
= false;
1337 contextB
.tarp
.cover();
1341 var interactionModel
= this.attr_("interactionModel");
1343 // Self is the graph.
1346 // Function that binds the graph and context to the handler.
1347 var bindHandler
= function(handler
) {
1348 return function(event
) {
1349 handler(event
, self
, context
);
1353 for (var eventName
in interactionModel
) {
1354 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1355 this.addAndTrackEvent(this.mouseEventElement_
, eventName
,
1356 bindHandler(interactionModel
[eventName
]));
1359 // If the user releases the mouse button during a drag, but not over the
1360 // canvas, then it doesn't count as a zooming action.
1361 var mouseUpHandler
= function(event
) {
1362 if (context
.isZooming
|| context
.isPanning
) {
1363 context
.isZooming
= false;
1364 context
.dragStartX
= null;
1365 context
.dragStartY
= null;
1368 if (context
.isPanning
) {
1369 context
.isPanning
= false;
1370 context
.draggingDate
= null;
1371 context
.dateRange
= null;
1372 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1373 delete self
.axes_
[i
].draggingValue
;
1374 delete self
.axes_
[i
].dragValueRange
;
1378 context
.tarp
.uncover();
1381 this.addAndTrackEvent(document
, 'mouseup', mouseUpHandler
);
1385 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1386 * up any previous zoom rectangles that were drawn. This could be optimized to
1387 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1390 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1391 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1392 * @param {Number} startX The X position where the drag started, in canvas
1394 * @param {Number} endX The current X position of the drag, in canvas coords.
1395 * @param {Number} startY The Y position where the drag started, in canvas
1397 * @param {Number} endY The current Y position of the drag, in canvas coords.
1398 * @param {Number} prevDirection the value of direction on the previous call to
1399 * this function. Used to avoid excess redrawing
1400 * @param {Number} prevEndX The value of endX on the previous call to this
1401 * function. Used to avoid excess redrawing
1402 * @param {Number} prevEndY The value of endY on the previous call to this
1403 * function. Used to avoid excess redrawing
1406 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1407 endY
, prevDirection
, prevEndX
,
1409 var ctx
= this.canvas_ctx_
;
1411 // Clean up from the previous rect if necessary
1412 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1413 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1414 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1415 } else if (prevDirection
== Dygraph
.VERTICAL
){
1416 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1417 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1420 // Draw a light-grey rectangle to show the new viewing area
1421 if (direction
== Dygraph
.HORIZONTAL
) {
1422 if (endX
&& startX
) {
1423 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1424 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1425 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1427 } else if (direction
== Dygraph
.VERTICAL
) {
1428 if (endY
&& startY
) {
1429 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1430 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1431 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1435 if (this.isUsingExcanvas_
) {
1436 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1441 * Clear the zoom rectangle (and perform no zoom).
1444 Dygraph
.prototype.clearZoomRect_
= function() {
1445 this.currentZoomRectArgs_
= null;
1446 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1450 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1451 * the canvas. The exact zoom window may be slightly larger if there are no data
1452 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1453 * which accepts dates that match the raw data. This function redraws the graph.
1455 * @param {Number} lowX The leftmost pixel value that should be visible.
1456 * @param {Number} highX The rightmost pixel value that should be visible.
1459 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1460 this.currentZoomRectArgs_
= null;
1461 // Find the earliest and latest dates contained in this canvasx range.
1462 // Convert the call to date ranges of the raw data.
1463 var minDate
= this.toDataXCoord(lowX
);
1464 var maxDate
= this.toDataXCoord(highX
);
1465 this.doZoomXDates_(minDate
, maxDate
);
1469 * Transition function to use in animations. Returns values between 0.0
1470 * (totally old values) and 1.0 (totally new values) for each frame.
1473 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1475 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1479 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1480 * method with doZoomX which accepts pixel coordinates. This function redraws
1483 * @param {Number} minDate The minimum date that should be visible.
1484 * @param {Number} maxDate The maximum date that should be visible.
1487 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1488 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1489 // can produce strange effects. Rather than the y-axis transitioning slowly
1490 // between values, it can jerk around.)
1491 var old_window
= this.xAxisRange();
1492 var new_window
= [minDate
, maxDate
];
1493 this.zoomed_x_
= true;
1495 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1496 if (that
.attr_("zoomCallback")) {
1497 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1503 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1504 * the canvas. This function redraws the graph.
1506 * @param {Number} lowY The topmost pixel value that should be visible.
1507 * @param {Number} highY The lowest pixel value that should be visible.
1510 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1511 this.currentZoomRectArgs_
= null;
1512 // Find the highest and lowest values in pixel range for each axis.
1513 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1514 // This is because pixels increase as you go down on the screen, whereas data
1515 // coordinates increase as you go up the screen.
1516 var oldValueRanges
= this.yAxisRanges();
1517 var newValueRanges
= [];
1518 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1519 var hi
= this.toDataYCoord(lowY
, i
);
1520 var low
= this.toDataYCoord(highY
, i
);
1521 newValueRanges
.push([low
, hi
]);
1524 this.zoomed_y_
= true;
1526 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1527 if (that
.attr_("zoomCallback")) {
1528 var xRange
= that
.xAxisRange();
1529 that
.attr_("zoomCallback")(xRange
[0], xRange
[1], that
.yAxisRanges());
1535 * Reset the zoom to the original view coordinates. This is the same as
1536 * double-clicking on the graph.
1538 Dygraph
.prototype.resetZoom
= function() {
1539 var dirty
= false, dirtyX
= false, dirtyY
= false;
1540 if (this.dateWindow_
!== null) {
1545 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1546 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1552 // Clear any selection, since it's likely to be drawn in the wrong place.
1553 this.clearSelection();
1556 this.zoomed_x_
= false;
1557 this.zoomed_y_
= false;
1559 var minDate
= this.rawData_
[0][0];
1560 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1562 // With only one frame, don't bother calculating extreme ranges.
1563 // TODO(danvk): merge this block w/ the code below
.
1564 if (!this.attr_("animatedZooms")) {
1565 this.dateWindow_
= null;
1566 for (i
= 0; i
< this.axes_
.length
; i
++) {
1567 if (this.axes_
[i
].valueWindow
!== null) {
1568 delete this.axes_
[i
].valueWindow
;
1572 if (this.attr_("zoomCallback")) {
1573 this.attr_("zoomCallback")(minDate
, maxDate
, this.yAxisRanges());
1578 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1580 oldWindow
= this.xAxisRange();
1581 newWindow
= [minDate
, maxDate
];
1585 oldValueRanges
= this.yAxisRanges();
1586 // TODO(danvk): this is pretty inefficient
1587 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1588 var extremes
= packed
.extremes
;
1590 // this has the side-effect of modifying this.axes_.
1591 // this doesn't make much sense in this context, but it's convenient (we
1592 // need this.axes_[*].extremeValues) and not harmful since we'll be
1593 // calling drawGraph_ shortly, which clobbers these values.
1594 this.computeYAxisRanges_(extremes
);
1596 newValueRanges
= [];
1597 for (i
= 0; i
< this.axes_
.length
; i
++) {
1598 var axis
= this.axes_
[i
];
1599 newValueRanges
.push((axis
.valueRange
!== null &&
1600 axis
.valueRange
!== undefined
) ?
1601 axis
.valueRange
: axis
.extremeRange
);
1606 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1608 that
.dateWindow_
= null;
1609 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1610 if (that
.axes_
[i
].valueWindow
!== null) {
1611 delete that
.axes_
[i
].valueWindow
;
1614 if (that
.attr_("zoomCallback")) {
1615 that
.attr_("zoomCallback")(minDate
, maxDate
, that
.yAxisRanges());
1622 * Combined animation logic for all zoom functions.
1623 * either the x parameters or y parameters may be null.
1626 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1627 var steps
= this.attr_("animatedZooms") ? Dygraph
.ANIMATION_STEPS
: 1;
1630 var valueRanges
= [];
1633 if (oldXRange
!== null && newXRange
!== null) {
1634 for (step
= 1; step
<= steps
; step
++) {
1635 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1636 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1637 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1641 if (oldYRanges
!== null && newYRanges
!== null) {
1642 for (step
= 1; step
<= steps
; step
++) {
1643 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1645 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1646 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1647 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1649 valueRanges
[step
-1] = thisRange
;
1654 Dygraph
.repeatAndCleanup(function(step
) {
1655 if (valueRanges
.length
) {
1656 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1657 var w
= valueRanges
[step
][i
];
1658 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1661 if (windows
.length
) {
1662 that
.dateWindow_
= windows
[step
];
1665 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1669 * Get the current graph's area object.
1671 * Returns: {x, y, w, h}
1673 Dygraph
.prototype.getArea
= function() {
1674 return this.plotter_
.area
;
1678 * Convert a mouse event to DOM coordinates relative to the graph origin.
1680 * Returns a two-element array: [X, Y].
1682 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1683 if (event
.offsetX
&& event
.offsetY
) {
1684 return [ event
.offsetX
, event
.offsetY
];
1686 var canvasx
= Dygraph
.pageX(event
) - Dygraph
.findPosX(this.mouseEventElement_
);
1687 var canvasy
= Dygraph
.pageY(event
) - Dygraph
.findPosY(this.mouseEventElement_
);
1688 return [canvasx
, canvasy
];
1693 * Given a canvas X coordinate, find the closest row.
1694 * @param {Number} domX graph-relative DOM X coordinate
1695 * Returns: row number, integer
1698 Dygraph
.prototype.findClosestRow
= function(domX
) {
1699 var minDistX
= Infinity
;
1700 var closestRow
= -1;
1701 var sets
= this.layout_
.points
;
1702 for (var i
= 0; i
< sets
.length
; i
++) {
1703 var points
= sets
[i
];
1704 var len
= points
.length
;
1705 for (var j
= 0; j
< len
; j
++) {
1706 var point
= points
[j
];
1707 if (!Dygraph
.isValidPoint(point
, true)) continue;
1708 var dist
= Math
.abs(point
.canvasx
- domX
);
1709 if (dist
< minDistX
) {
1711 closestRow
= point
.idx
;
1720 * Given canvas X,Y coordinates, find the closest point.
1722 * This finds the individual data point across all visible series
1723 * that's closest to the supplied DOM coordinates using the standard
1724 * Euclidean X,Y distance.
1726 * @param {Number} domX graph-relative DOM X coordinate
1727 * @param {Number} domY graph-relative DOM Y coordinate
1728 * Returns: {row, seriesName, point}
1731 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1732 var minDist
= Infinity
;
1733 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
, closestRow
;
1734 for ( var setIdx
= this.layout_
.points
.length
- 1 ; setIdx
>= 0 ; --setIdx
) {
1735 var points
= this.layout_
.points
[setIdx
];
1736 for (var i
= 0; i
< points
.length
; ++i
) {
1738 if (!Dygraph
.isValidPoint(point
)) continue;
1739 dx
= point
.canvasx
- domX
;
1740 dy
= point
.canvasy
- domY
;
1741 dist
= dx
* dx
+ dy
* dy
;
1742 if (dist
< minDist
) {
1744 closestPoint
= point
;
1745 closestSeries
= setIdx
;
1746 closestRow
= point
.idx
;
1750 var name
= this.layout_
.setNames
[closestSeries
];
1759 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1761 * This first finds the X data point closest to the supplied DOM X coordinate,
1762 * then finds the series which puts the Y coordinate on top of its filled area,
1763 * using linear interpolation between adjacent point pairs.
1765 * @param {Number} domX graph-relative DOM X coordinate
1766 * @param {Number} domY graph-relative DOM Y coordinate
1767 * Returns: {row, seriesName, point}
1770 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1771 var row
= this.findClosestRow(domX
);
1772 var closestPoint
, closestSeries
;
1773 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
1774 var boundary
= this.getLeftBoundary_(setIdx
);
1775 var rowIdx
= row
- boundary
;
1776 var points
= this.layout_
.points
[setIdx
];
1777 if (rowIdx
>= points
.length
) continue;
1778 var p1
= points
[rowIdx
];
1779 if (!Dygraph
.isValidPoint(p1
)) continue;
1780 var py
= p1
.canvasy
;
1781 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < points
.length
) {
1782 // interpolate series Y value using next point
1783 var p2
= points
[rowIdx
+ 1];
1784 if (Dygraph
.isValidPoint(p2
)) {
1785 var dx
= p2
.canvasx
- p1
.canvasx
;
1787 var r
= (domX
- p1
.canvasx
) / dx
;
1788 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1791 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1792 // interpolate series Y value using previous point
1793 var p0
= points
[rowIdx
- 1];
1794 if (Dygraph
.isValidPoint(p0
)) {
1795 var dx
= p1
.canvasx
- p0
.canvasx
;
1797 var r
= (p1
.canvasx
- domX
) / dx
;
1798 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1802 // Stop if the point (domX, py) is above this series' upper edge
1803 if (setIdx
=== 0 || py
< domY
) {
1805 closestSeries
= setIdx
;
1808 var name
= this.layout_
.setNames
[closestSeries
];
1817 * When the mouse moves in the canvas, display information about a nearby data
1818 * point and draw dots over those points in the data series. This function
1819 * takes care of cleanup of previously-drawn dots.
1820 * @param {Object} event The mousemove event from the browser.
1823 Dygraph
.prototype.mouseMove_
= function(event
) {
1824 // This prevents JS errors when mousing over the canvas before data loads.
1825 var points
= this.layout_
.points
;
1826 if (points
=== undefined
|| points
=== null) return;
1828 var canvasCoords
= this.eventToDomCoords(event
);
1829 var canvasx
= canvasCoords
[0];
1830 var canvasy
= canvasCoords
[1];
1832 var highlightSeriesOpts
= this.attr_("highlightSeriesOpts");
1833 var selectionChanged
= false;
1834 if (highlightSeriesOpts
&& !this.isSeriesLocked()) {
1836 if (this.attr_("stackedGraph")) {
1837 closest
= this.findStackedPoint(canvasx
, canvasy
);
1839 closest
= this.findClosestPoint(canvasx
, canvasy
);
1841 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1843 var idx
= this.findClosestRow(canvasx
);
1844 selectionChanged
= this.setSelection(idx
);
1847 var callback
= this.attr_("highlightCallback");
1848 if (callback
&& selectionChanged
) {
1853 this.highlightSet_
);
1858 * Fetch left offset from the specified set index or if not passed, the
1859 * first defined boundaryIds record (see bug #236).
1862 Dygraph
.prototype.getLeftBoundary_
= function(setIdx
) {
1863 if(this.boundaryIds_
[setIdx
]){
1864 return this.boundaryIds_
[setIdx
][0];
1866 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1867 if (this.boundaryIds_
[i
] !== undefined
) {
1868 return this.boundaryIds_
[i
][0];
1875 Dygraph
.prototype.animateSelection_
= function(direction
) {
1876 var totalSteps
= 10;
1878 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1879 if (this.animateId
=== undefined
) this.animateId
= 0;
1880 var start
= this.fadeLevel
;
1881 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1883 if (this.fadeLevel
) {
1884 this.updateSelection_(1.0);
1889 var thisId
= ++this.animateId
;
1891 Dygraph
.repeatAndCleanup(
1893 // ignore simultaneous animations
1894 if (that
.animateId
!= thisId
) return;
1896 that
.fadeLevel
+= direction
;
1897 if (that
.fadeLevel
=== 0) {
1898 that
.clearSelection();
1900 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
1903 steps
, millis
, function() {});
1907 * Draw dots over the selectied points in the data series. This function
1908 * takes care of cleanup of previously-drawn dots.
1911 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
1912 /*var defaultPrevented = */
1913 this.cascadeEvents_('select', {
1914 selectedX
: this.lastx_
,
1915 selectedPoints
: this.selPoints_
1917 // TODO(danvk): use defaultPrevented here?
1919 // Clear the previously drawn vertical, if there is one
1921 var ctx
= this.canvas_ctx_
;
1922 if (this.attr_('highlightSeriesOpts')) {
1923 ctx
.clearRect(0, 0, this.width_
, this.height_
);
1924 var alpha
= 1.0 - this.attr_('highlightSeriesBackgroundAlpha');
1926 // Activating background fade includes an animation effect for a gradual
1927 // fade. TODO(klausw): make this independently configurable if it causes
1928 // issues? Use a shared preference to control animations?
1929 var animateBackgroundFade
= true;
1930 if (animateBackgroundFade
) {
1931 if (opt_animFraction
=== undefined
) {
1932 // start a new animation
1933 this.animateSelection_(1);
1936 alpha
*= opt_animFraction
;
1938 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
1939 ctx
.fillRect(0, 0, this.width_
, this.height_
);
1942 // Redraw only the highlighted series in the interactive canvas (not the
1943 // static plot canvas, which is where series are usually drawn).
1944 this.plotter_
._renderLineChart(this.highlightSet_
, ctx
);
1945 } else if (this.previousVerticalX_
>= 0) {
1946 // Determine the maximum highlight circle size.
1947 var maxCircleSize
= 0;
1948 var labels
= this.attr_('labels');
1949 for (i
= 1; i
< labels
.length
; i
++) {
1950 var r
= this.attr_('highlightCircleSize', labels
[i
]);
1951 if (r
> maxCircleSize
) maxCircleSize
= r
;
1953 var px
= this.previousVerticalX_
;
1954 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
1955 2 * maxCircleSize
+ 2, this.height_
);
1958 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
1959 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
1962 if (this.selPoints_
.length
> 0) {
1963 // Draw colored circles over the center of each selected point
1964 var canvasx
= this.selPoints_
[0].canvasx
;
1966 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
1967 var pt
= this.selPoints_
[i
];
1968 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
1970 var circleSize
= this.attr_('highlightCircleSize', pt
.name
);
1971 var callback
= this.attr_("drawHighlightPointCallback", pt
.name
);
1972 var color
= this.plotter_
.colors
[pt
.name
];
1974 callback
= Dygraph
.Circles
.DEFAULT
;
1976 ctx
.lineWidth
= this.attr_('strokeWidth', pt
.name
);
1977 ctx
.strokeStyle
= color
;
1978 ctx
.fillStyle
= color
;
1979 callback(this.g
, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
1980 color
, circleSize
, pt
.idx
);
1984 this.previousVerticalX_
= canvasx
;
1989 * Manually set the selected points and display information about them in the
1990 * legend. The selection can be cleared using clearSelection() and queried
1991 * using getSelection().
1992 * @param { Integer } row number that should be highlighted (i.e. appear with
1993 * hover dots on the chart). Set to false to clear any selection.
1994 * @param { seriesName } optional series name to highlight that series with the
1995 * the highlightSeriesOpts setting.
1996 * @param { locked } optional If true, keep seriesName selected when mousing
1997 * over the graph, disabling closest-series highlighting. Call clearSelection()
2000 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
, opt_locked
) {
2001 // Extract the points we've selected
2002 this.selPoints_
= [];
2004 var changed
= false;
2005 if (row
!== false && row
>= 0) {
2006 if (row
!= this.lastRow_
) changed
= true;
2007 this.lastRow_
= row
;
2008 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
2009 var points
= this.layout_
.points
[setIdx
];
2010 var setRow
= row
- this.getLeftBoundary_(setIdx
);
2011 if (setRow
< points
.length
) {
2012 var point
= points
[setRow
];
2013 if (point
.yval
!== null) this.selPoints_
.push(point
);
2017 if (this.lastRow_
>= 0) changed
= true;
2021 if (this.selPoints_
.length
) {
2022 this.lastx_
= this.selPoints_
[0].xval
;
2027 if (opt_seriesName
!== undefined
) {
2028 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
2029 this.highlightSet_
= opt_seriesName
;
2032 if (opt_locked
!== undefined
) {
2033 this.lockedSet_
= opt_locked
;
2037 this.updateSelection_(undefined
);
2043 * The mouse has left the canvas. Clear out whatever artifacts remain
2044 * @param {Object} event the mouseout event from the browser.
2047 Dygraph
.prototype.mouseOut_
= function(event
) {
2048 if (this.attr_("unhighlightCallback")) {
2049 this.attr_("unhighlightCallback")(event
);
2052 if (this.attr_("hideOverlayOnMouseOut") && !this.lockedSet_
) {
2053 this.clearSelection();
2058 * Clears the current selection (i.e. points that were highlighted by moving
2059 * the mouse over the chart).
2061 Dygraph
.prototype.clearSelection
= function() {
2062 this.cascadeEvents_('deselect', {});
2064 this.lockedSet_
= false;
2065 // Get rid of the overlay data
2066 if (this.fadeLevel
) {
2067 this.animateSelection_(-1);
2070 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
2072 this.selPoints_
= [];
2075 this.highlightSet_
= null;
2079 * Returns the number of the currently selected row. To get data for this row,
2080 * you can use the getValue method.
2081 * @return { Integer } row number, or -1 if nothing is selected
2083 Dygraph
.prototype.getSelection
= function() {
2084 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
2088 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; setIdx
++) {
2089 var points
= this.layout_
.points
[setIdx
];
2090 for (var row
= 0; row
< points
.length
; row
++) {
2091 if (points
[row
].x
== this.selPoints_
[0].x
) {
2092 return points
[row
].idx
;
2100 * Returns the name of the currently-highlighted series.
2101 * Only available when the highlightSeriesOpts option is in use.
2103 Dygraph
.prototype.getHighlightSeries
= function() {
2104 return this.highlightSet_
;
2108 * Returns true if the currently-highlighted series was locked
2109 * via setSelection(..., seriesName, true).
2111 Dygraph
.prototype.isSeriesLocked
= function() {
2112 return this.lockedSet_
;
2116 * Fires when there's data available to be graphed.
2117 * @param {String} data Raw CSV data to be plotted
2120 Dygraph
.prototype.loadedEvent_
= function(data
) {
2121 this.rawData_
= this.parseCSV_(data
);
2126 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2129 Dygraph
.prototype.addXTicks_
= function() {
2130 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2132 if (this.dateWindow_
) {
2133 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2135 range
= this.xAxisExtremes();
2138 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2139 var xTicks
= xAxisOptionsView('ticker')(
2142 this.width_
, // TODO(danvk): should be area.width
2145 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2146 // console.log(msg);
2147 this.layout_
.setXTicks(xTicks
);
2152 * Computes the range of the data series (including confidence intervals).
2153 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
2154 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2155 * @return [low, high]
2157 Dygraph
.prototype.extremeValues_
= function(series
) {
2158 var minY
= null, maxY
= null, j
, y
;
2160 var bars
= this.attr_("errorBars") || this.attr_("customBars");
2162 // With custom bars, maxY is the max of the high values.
2163 for (j
= 0; j
< series
.length
; j
++) {
2164 y
= series
[j
][1][0];
2165 if (y
=== null || isNaN(y
)) continue;
2166 var low
= y
- series
[j
][1][1];
2167 var high
= y
+ series
[j
][1][2];
2168 if (low
> y
) low
= y
; // this can happen with custom bars,
2169 if (high
< y
) high
= y
; // e.g. in tests/custom-bars
.html
2170 if (maxY
=== null || high
> maxY
) {
2173 if (minY
=== null || low
< minY
) {
2178 for (j
= 0; j
< series
.length
; j
++) {
2180 if (y
=== null || isNaN(y
)) continue;
2181 if (maxY
=== null || y
> maxY
) {
2184 if (minY
=== null || y
< minY
) {
2190 return [minY
, maxY
];
2195 * This function is called once when the chart's data is changed or the options
2196 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2197 * idea is that values derived from the chart's data can be computed here,
2198 * rather than every time the chart is drawn. This includes things like the
2199 * number of axes, rolling averages, etc.
2201 Dygraph
.prototype.predraw_
= function() {
2202 var start
= new Date();
2204 this.layout_
.computePlotArea();
2206 // TODO(danvk): move more computations out of drawGraph_ and into here.
2207 this.computeYAxes_();
2209 // Create a new plotter.
2210 if (this.plotter_
) {
2211 this.cascadeEvents_('clearChart');
2212 this.plotter_
.clear();
2215 if(!this.is_initial_draw_
) {
2216 this.canvas_ctx_
.restore();
2217 this.hidden_ctx_
.restore();
2220 this.canvas_ctx_
.save();
2221 this.hidden_ctx_
.save();
2223 this.plotter_
= new DygraphCanvasRenderer(this,
2228 // The roller sits in the bottom left corner of the chart. We don't know where
2229 // this will be until the options are available, so it's positioned here.
2230 this.createRollInterface_();
2232 this.cascadeEvents_('predraw');
2234 // Convert the raw data (a 2D array) into the internal format and compute
2235 // rolling averages.
2236 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2237 for (var i
= 1; i
< this.numColumns(); i
++) {
2238 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too
.
2239 var logScale
= this.attr_('logscale');
2240 var series
= this.extractSeries_(this.rawData_
, i
, logScale
);
2241 series
= this.rollingAverage(series
, this.rollPeriod_
);
2242 this.rolledSeries_
.push(series
);
2245 // If the data or options have changed, then we'd better redraw.
2248 // This is used to determine whether to do various animations.
2249 var end
= new Date();
2250 this.drawingTimeMs_
= (end
- start
);
2256 * xval_* and yval_* are the original unscaled data values,
2257 * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
2258 * yval_stacked is the cumulative Y value used for stacking graphs,
2259 * and bottom/top/minus/plus are used for error bar graphs.
2266 * y_bottom: ?number,
2268 * y_stacked: ?number,
2270 * yval_minus: ?number,
2272 * yval_plus: ?number,
2276 Dygraph
.PointType
= undefined
;
2278 // TODO(bhs): these loops are a hot-spot for high-point-count charts. In fact,
2279 // on chrome+linux, they are 6 times more expensive than iterating through the
2280 // points and drawing the lines. The brunt of the cost comes from allocating
2281 // the |point| structures.
2283 * Converts a series to a Point array.
2285 * @param {Array.<Array.<(?number|Array<?number>)>} series Array where
2286 * series[row] = [x,y] or [x, [y, err]] or [x, [y, yplus, yminus]].
2287 * @param {boolean} bars True if error bars or custom bars are being drawn.
2288 * @param {string} setName Name of the series.
2289 * @param {number} boundaryIdStart Index offset of the first point, equal to
2290 * the number of skipped points left of the date window minimum (if any).
2291 * @return {Array.<Dygraph.PointType>} List of points for this series.
2293 Dygraph
.seriesToPoints_
= function(series
, bars
, setName
, boundaryIdStart
) {
2295 for (var i
= 0; i
< series
.length
; ++i
) {
2296 var item
= series
[i
];
2297 var yraw
= bars
? item
[1][0] : item
[1];
2298 var yval
= yraw
=== null ? null : DygraphLayout
.parseFloat_(yraw
);
2302 xval
: DygraphLayout
.parseFloat_(item
[0]),
2304 name
: setName
, // TODO(danvk): is this really necessary?
2305 idx
: i
+ boundaryIdStart
2310 point
.y_bottom
= NaN
;
2311 point
.yval_minus
= DygraphLayout
.parseFloat_(item
[1][1]);
2312 point
.yval_plus
= DygraphLayout
.parseFloat_(item
[1][2]);
2321 * Calculates point stacking for stackedGraph=true.
2323 * For stacking purposes, interpolate or extend neighboring data across
2324 * NaN values based on stackedGraphNaNFill settings. This is for display
2325 * only, the underlying data value as shown in the legend remains NaN.
2327 * @param {Array.<Dygraph.PointType>} points Point array for a single series.
2328 * Updates each Point's yval_stacked property.
2329 * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
2330 * values for the series seen so far. Index is the row number. Updated
2331 * based on the current series's values.
2332 * @param {Array.<number>} seriesExtremes Min and max values, updated
2333 * to reflect the stacked values.
2334 * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
2337 Dygraph
.stackPoints_
= function(
2338 points
, cumulativeYval
, seriesExtremes
, fillMethod
) {
2339 var lastXval
= null;
2340 var prevPoint
= null;
2341 var nextPoint
= null;
2342 var nextPointIdx
= -1;
2344 // Find the next stackable point starting from the given index.
2345 var updateNextPoint
= function(idx
) {
2346 // If we've previously found a non-NaN point and haven't gone past it yet,
2348 if (nextPointIdx
>= idx
) return;
2350 // We haven't found a non-NaN point yet or have moved past it,
2351 // look towards the right to find a non-NaN point.
2352 for (var j
= idx
; j
< points
.length
; ++j
) {
2353 // Clear out a previously-found point (if any) since it's no longer
2354 // valid, we shouldn't use it for interpolation anymore.
2356 if (!isNaN(points
[j
].yval
) && points
[j
].yval
!== null) {
2358 nextPoint
= points
[j
];
2364 for (var i
= 0; i
< points
.length
; ++i
) {
2365 var point
= points
[i
];
2366 var xval
= point
.xval
;
2367 if (cumulativeYval
[xval
] === undefined
) {
2368 cumulativeYval
[xval
] = 0;
2371 var actualYval
= point
.yval
;
2372 if (isNaN(actualYval
) || actualYval
=== null) {
2373 // Interpolate/extend
for stacking purposes
if possible
.
2375 if (prevPoint
&& nextPoint
&& fillMethod
!= 'none') {
2376 // Use linear interpolation between prevPoint and nextPoint.
2377 actualYval
= prevPoint
.yval
+ (nextPoint
.yval
- prevPoint
.yval
) *
2378 ((xval
- prevPoint
.xval
) / (nextPoint
.xval
- prevPoint
.xval
));
2379 } else if (prevPoint
&& fillMethod
== 'all') {
2380 actualYval
= prevPoint
.yval
;
2381 } else if (nextPoint
&& fillMethod
== 'all') {
2382 actualYval
= nextPoint
.yval
;
2390 var stackedYval
= cumulativeYval
[xval
];
2391 if (lastXval
!= xval
) {
2392 // If an x-value is repeated, we ignore the duplicates.
2393 stackedYval
+= actualYval
;
2394 cumulativeYval
[xval
] = stackedYval
;
2398 point
.yval_stacked
= stackedYval
;
2400 if (stackedYval
> seriesExtremes
[1]) {
2401 seriesExtremes
[1] = stackedYval
;
2403 if (stackedYval
< seriesExtremes
[0]) {
2404 seriesExtremes
[0] = stackedYval
;
2411 * Loop over all fields and create datasets, calculating extreme y-values for
2412 * each series and extreme x-indices as we go.
2414 * dateWindow is passed in as an explicit parameter so that we can compute
2415 * extreme values "speculatively", i.e. without actually setting state on the
2418 * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
2419 * rolledSeries[seriesIndex][row] = raw point, where
2420 * seriesIndex is the column number starting with 1, and
2421 * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
2422 * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
2424 * points: Array.<Array.<Dygraph.PointType>>,
2425 * seriesExtremes: Array.<Array.<number>>,
2426 * boundaryIds: Array.<number>}}
2429 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2430 var boundaryIds
= [];
2432 var cumulativeYval
= []; // For stacked series.
2433 var extremes
= {}; // series name -> [low, high]
2435 var errorBars
= this.attr_("errorBars");
2436 var customBars
= this.attr_("customBars");
2437 var bars
= errorBars
|| customBars
;
2438 var isValueNull
= function(sample
) {
2440 return sample
[1] === null;
2442 return customBars
? sample
[1][1] === null :
2443 errorBars
? sample
[1][0] === null : false;
2447 // Loop over the fields (series). Go from the last to the first,
2448 // because if they're stacked that's how we accumulate the values.
2449 var num_series
= rolledSeries
.length
- 1;
2451 for (i
= num_series
; i
>= 1; i
--) {
2452 if (!this.visibility()[i
- 1]) continue;
2454 // Prune down to the desired range, if necessary (for zooming)
2455 // Because there can be lines going to points outside of the visible area,
2456 // we actually prune to visible points, plus one on either side.
2458 series
= rolledSeries
[i
];
2459 var low
= dateWindow
[0];
2460 var high
= dateWindow
[1];
2462 // TODO(danvk): do binary search instead of linear search.
2463 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2464 var firstIdx
= null, lastIdx
= null;
2465 for (k
= 0; k
< series
.length
; k
++) {
2466 if (series
[k
][0] >= low
&& firstIdx
=== null) {
2469 if (series
[k
][0] <= high
) {
2474 if (firstIdx
=== null) firstIdx
= 0;
2475 var correctedFirstIdx
= firstIdx
;
2476 var isInvalidValue
= true;
2477 while (isInvalidValue
&& correctedFirstIdx
> 0) {
2478 correctedFirstIdx
--;
2479 isInvalidValue
= isValueNull(series
[correctedFirstIdx
]);
2482 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2483 var correctedLastIdx
= lastIdx
;
2484 isInvalidValue
= true;
2485 while (isInvalidValue
&& correctedLastIdx
< series
.length
- 1) {
2487 isInvalidValue
= isValueNull(series
[correctedLastIdx
]);
2491 if (correctedFirstIdx
!==firstIdx
) {
2492 firstIdx
= correctedFirstIdx
;
2494 if (correctedLastIdx
!== lastIdx
) {
2495 lastIdx
= correctedLastIdx
;
2498 boundaryIds
[i
-1] = [firstIdx
, lastIdx
];
2500 // .slice's end is exclusive, we want to include lastIdx.
2501 series
= series
.slice(firstIdx
, lastIdx
+ 1);
2503 series
= rolledSeries
[i
];
2504 boundaryIds
[i
-1] = [0, series
.length
-1];
2507 var seriesName
= this.attr_("labels")[i
];
2508 var seriesExtremes
= this.extremeValues_(series
);
2510 var seriesPoints
= Dygraph
.seriesToPoints_(
2511 series
, bars
, seriesName
, boundaryIds
[i
-1][0]);
2513 if (this.attr_("stackedGraph")) {
2514 Dygraph
.stackPoints_(seriesPoints
, cumulativeYval
, seriesExtremes
,
2515 this.attr_("stackedGraphNaNFill"));
2518 extremes
[seriesName
] = seriesExtremes
;
2519 points
[i
] = seriesPoints
;
2522 return { points
: points
, extremes
: extremes
, boundaryIds
: boundaryIds
};
2526 * Update the graph with new data. This method is called when the viewing area
2527 * has changed. If the underlying data or options have changed, predraw_ will
2528 * be called before drawGraph_ is called.
2532 Dygraph
.prototype.drawGraph_
= function() {
2533 var start
= new Date();
2535 // This is used to set the second parameter to drawCallback, below.
2536 var is_initial_draw
= this.is_initial_draw_
;
2537 this.is_initial_draw_
= false;
2539 this.layout_
.removeAllDatasets();
2541 this.attrs_
.pointSize
= 0.5 * this.attr_('highlightCircleSize');
2543 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2544 var points
= packed
.points
;
2545 var extremes
= packed
.extremes
;
2546 this.boundaryIds_
= packed
.boundaryIds
;
2548 this.setIndexByName_
= {};
2549 var labels
= this.attr_("labels");
2550 if (labels
.length
> 0) {
2551 this.setIndexByName_
[labels
[0]] = 0;
2554 for (var i
= 1; i
< points
.length
; i
++) {
2555 this.setIndexByName_
[labels
[i
]] = i
;
2556 if (!this.visibility()[i
- 1]) continue;
2557 this.layout_
.addDataset(labels
[i
], points
[i
]);
2558 this.datasetIndex_
[i
] = dataIdx
++;
2561 this.computeYAxisRanges_(extremes
);
2562 this.layout_
.setYAxes(this.axes_
);
2566 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2567 var tmp_zoomed_x
= this.zoomed_x_
;
2568 // Tell PlotKit to use this new data and render itself
2569 this.zoomed_x_
= tmp_zoomed_x
;
2570 this.layout_
.evaluate();
2571 this.renderGraph_(is_initial_draw
);
2573 if (this.attr_("timingName")) {
2574 var end
= new Date();
2575 Dygraph
.info(this.attr_("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2580 * This does the work of drawing the chart. It assumes that the layout and axis
2581 * scales have already been set (e.g. by predraw_).
2585 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2586 this.cascadeEvents_('clearChart');
2587 this.plotter_
.clear();
2589 if (this.attr_('underlayCallback')) {
2590 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2591 // users who expect a deprecated form of this callback.
2592 this.attr_('underlayCallback')(
2593 this.hidden_ctx_
, this.layout_
.getPlotArea(), this, this);
2597 canvas
: this.hidden_
,
2598 drawingContext
: this.hidden_ctx_
2600 this.cascadeEvents_('willDrawChart', e
);
2601 this.plotter_
.render();
2602 this.cascadeEvents_('didDrawChart', e
);
2603 this.lastRow_
= -1; // because plugins/legend.js clears the legend
2605 // TODO(danvk): is this a performance bottleneck when panning?
2606 // The interaction canvas should already be empty in that situation.
2607 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2608 this.canvas_
.height
);
2610 if (this.attr_("drawCallback") !== null) {
2611 this.attr_("drawCallback")(this, is_initial_draw
);
2617 * Determine properties of the y-axes which are independent of the data
2618 * currently being displayed. This includes things like the number of axes and
2619 * the style of the axes. It does not include the range of each axis and its
2621 * This fills in this.axes_.
2622 * axes_ = [ { options } ]
2623 * indices are into the axes_ array.
2625 Dygraph
.prototype.computeYAxes_
= function() {
2626 // Preserve valueWindow settings if they exist, and if the user hasn't
2627 // specified a new valueRange.
2628 var valueWindows
, axis
, index
, opts
, v
;
2629 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2631 for (index
= 0; index
< this.axes_
.length
; index
++) {
2632 valueWindows
.push(this.axes_
[index
].valueWindow
);
2636 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2637 // data computation as well as options storage.
2638 // Go through once and add all the axes.
2641 for (axis
= 0; axis
< this.attributes_
.numAxes(); axis
++) {
2642 // Add a new axis, making a copy of its per-axis options.
2643 opts
= { g
: this };
2644 Dygraph
.update(opts
, this.attributes_
.axisOptions(axis
));
2645 this.axes_
[axis
] = opts
;
2649 // Copy global valueRange option over to the first axis.
2650 // NOTE(konigsberg): Are these two statements necessary?
2651 // I tried removing it. The automated tests pass, and manually
2652 // messing with tests/zoom
.html showed no trouble
.
2653 v
= this.attr_('valueRange');
2654 if (v
) this.axes_
[0].valueRange
= v
;
2656 if (valueWindows
!== undefined
) {
2657 // Restore valueWindow settings.
2659 // When going from two axes back to one, we only restore
2661 var idxCount
= Math
.min(valueWindows
.length
, this.axes_
.length
);
2663 for (index
= 0; index
< idxCount
; index
++) {
2664 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2668 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2670 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2671 v
= opts("valueRange");
2672 if (v
) this.axes_
[axis
].valueRange
= v
;
2673 } else { // To keep old behavior
2674 var axes
= this.user_attrs_
.axes
;
2675 if (axes
&& axes
.y2
) {
2676 v
= axes
.y2
.valueRange
;
2677 if (v
) this.axes_
[axis
].valueRange
= v
;
2684 * Returns the number of y-axes on the chart.
2685 * @return {Number} the number of axes.
2687 Dygraph
.prototype.numAxes
= function() {
2688 return this.attributes_
.numAxes();
2693 * Returns axis properties for the given series.
2694 * @param { String } setName The name of the series for which to get axis
2695 * properties, e.g. 'Y1'.
2696 * @return { Object } The axis properties.
2698 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2699 // TODO(danvk): handle errors.
2700 return this.axes_
[this.attributes_
.axisForSeries(series
)];
2705 * Determine the value range and tick marks for each axis.
2706 * @param {Object} extremes A mapping from seriesName -> [low, high]
2707 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2709 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2710 var isNullUndefinedOrNaN
= function(num
) {
2711 return isNaN(parseFloat(num
));
2713 var numAxes
= this.attributes_
.numAxes();
2714 var ypadCompat
, span
, series
, ypad
;
2718 // Compute extreme values, a span and tick marks for each axis.
2719 for (var i
= 0; i
< numAxes
; i
++) {
2720 var axis
= this.axes_
[i
];
2721 var logscale
= this.attributes_
.getForAxis("logscale", i
);
2722 var includeZero
= this.attributes_
.getForAxis("includeZero", i
);
2723 var independentTicks
= this.attributes_
.getForAxis("independentTicks", i
);
2724 series
= this.attributes_
.seriesForAxis(i
);
2726 // Add some padding. This supports two Y padding operation modes:
2728 // - backwards compatible (yRangePad not set):
2729 // 10% padding for automatic Y ranges, but not for user-supplied
2730 // ranges, and move a close-to-zero edge to zero except if
2731 // avoidMinZero is set, since drawing at the edge results in
2732 // invisible lines. Unfortunately lines drawn at the edge of a
2733 // user-supplied range will still be invisible. If logscale is
2734 // set, add a variable amount of padding at the top but
2735 // none at the bottom.
2737 // - new-style (yRangePad set by the user):
2738 // always add the specified Y padding.
2741 ypad
= 0.1; // add 10%
2742 if (this.attr_('yRangePad') !== null) {
2744 // Convert pixel padding to ratio
2745 ypad
= this.attr_('yRangePad') / this.plotter_
.area
.h
;
2748 if (series
.length
=== 0) {
2749 // If no series are defined or visible then use a reasonable default
2750 axis
.extremeRange
= [0, 1];
2752 // Calculate the extremes of extremes.
2753 var minY
= Infinity
; // extremes[series[0]][0];
2754 var maxY
= -Infinity
; // extremes[series[0]][1];
2755 var extremeMinY
, extremeMaxY
;
2757 for (var j
= 0; j
< series
.length
; j
++) {
2758 // this skips invisible series
2759 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2761 // Only use valid extremes to stop null data series' from corrupting the scale.
2762 extremeMinY
= extremes
[series
[j
]][0];
2763 if (extremeMinY
!== null) {
2764 minY
= Math
.min(extremeMinY
, minY
);
2766 extremeMaxY
= extremes
[series
[j
]][1];
2767 if (extremeMaxY
!== null) {
2768 maxY
= Math
.max(extremeMaxY
, maxY
);
2772 // Include zero if requested by the user.
2773 if (includeZero
&& !logscale
) {
2774 if (minY
> 0) minY
= 0;
2775 if (maxY
< 0) maxY
= 0;
2778 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2779 if (minY
== Infinity
) minY
= 0;
2780 if (maxY
== -Infinity
) maxY
= 1;
2783 // special case: if we have no sense of scale, center on the sole value.
2786 span
= Math
.abs(maxY
);
2788 // ... and if the sole value is zero, use range 0-1.
2794 var maxAxisY
, minAxisY
;
2797 maxAxisY
= maxY
+ ypad
* span
;
2800 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2801 maxAxisY
= maxY
* logpad
;
2802 minAxisY
= minY
/ logpad
;
2805 maxAxisY
= maxY
+ ypad
* span
;
2806 minAxisY
= minY
- ypad
* span
;
2808 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2809 // close to zero, but not if avoidMinZero is set.
2810 if (ypadCompat
&& !this.attr_("avoidMinZero")) {
2811 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2812 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2815 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2817 if (axis
.valueWindow
) {
2818 // This is only set if the user has zoomed on the y-axis. It is never set
2819 // by a user. It takes precedence over axis.valueRange because, if you set
2820 // valueRange, you'd still expect to be able to pan.
2821 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2822 } else if (axis
.valueRange
) {
2823 // This is a user-set value range for this axis.
2824 var y0
= isNullUndefinedOrNaN(axis
.valueRange
[0]) ? axis
.extremeRange
[0] : axis
.valueRange
[0];
2825 var y1
= isNullUndefinedOrNaN(axis
.valueRange
[1]) ? axis
.extremeRange
[1] : axis
.valueRange
[1];
2827 if (axis
.logscale
) {
2828 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2837 axis
.computedValueRange
= [y0
, y1
];
2839 axis
.computedValueRange
= axis
.extremeRange
;
2843 if(independentTicks
) {
2844 axis
.independentTicks
= independentTicks
;
2845 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2846 var ticker
= opts('ticker');
2847 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2848 axis
.computedValueRange
[1],
2849 this.height_
, // TODO(danvk): should be area.height
2852 // Define the first independent axis as primary axis.
2853 if (!p_axis
) p_axis
= axis
;
2856 if (p_axis
=== undefined
) {
2857 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
2859 // Add ticks. By default, all axes inherit the tick positions of the
2860 // primary axis. However, if an axis is specifically marked as having
2861 // independent ticks, then that is permissible as well.
2862 for (var i
= 0; i
< numAxes
; i
++) {
2863 var axis
= this.axes_
[i
];
2865 if (!axis
.independentTicks
) {
2866 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2867 var ticker
= opts('ticker');
2868 var p_ticks
= p_axis
.ticks
;
2869 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2870 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2871 var tick_values
= [];
2872 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2873 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2874 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2875 tick_values
.push(y_val
);
2878 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2879 axis
.computedValueRange
[1],
2880 this.height_
, // TODO(danvk): should be area.height
2889 * Extracts one series from the raw data (a 2D array) into an array of (date,
2892 * This is where undesirable points (i.e. negative values on log scales and
2893 * missing values through which we wish to connect lines) are dropped.
2894 * TODO(danvk): the "missing values" bit above doesn't seem right.
2897 * @param {Array.<Array.<(number|Array<Number>)>>} rawData Input data. Rectangular
2898 * grid of points, where rawData[row][0] is the X value for the row,
2899 * and rawData[row][i] is the Y data for series #i.
2900 * @param {number} i Series index, starting from 1.
2901 * @param {boolean} logScale True if using logarithmic Y scale.
2902 * @return {Array.<Array.<(?number|Array<?number>)>} Series array, where
2903 * series[row] = [x,y] or [x, [y, err]] or [x, [y, yplus, yminus]].
2905 Dygraph
.prototype.extractSeries_
= function(rawData
, i
, logScale
) {
2906 // TODO(danvk): pre-allocate series here.
2908 var errorBars
= this.attr_("errorBars");
2909 var customBars
= this.attr_("customBars");
2910 for (var j
= 0; j
< rawData
.length
; j
++) {
2911 var x
= rawData
[j
][0];
2912 var point
= rawData
[j
][i
];
2914 // On the log scale, points less than zero do not exist.
2915 // This will create a gap in the chart.
2916 if (errorBars
|| customBars
) {
2917 // point.length is either 2 (errorBars) or 3 (customBars)
2918 for (var k
= 0; k
< point
.length
; k
++) {
2919 if (point
[k
] <= 0) {
2924 } else if (point
<= 0) {
2928 // Fix null points to fit the display type standard.
2929 if (point
!== null) {
2930 series
.push([x
, point
]);
2932 series
.push([x
, errorBars
? [null, null] : customBars
? [null, null, null] : point
]);
2940 * Calculates the rolling average of a data set.
2941 * If originalData is [label, val], rolls the average of those.
2942 * If originalData is [label, [, it's interpreted as [value, stddev]
2943 * and the roll is returned in the same form, with appropriately reduced
2944 * stddev for each value.
2945 * Note that this is where fractional input (i.e. '5/10') is converted into
2947 * @param {Array} originalData The data in the appropriate format (see above)
2948 * @param {Number} rollPeriod The number of points over which to average the
2951 Dygraph
.prototype.rollingAverage
= function(originalData
, rollPeriod
) {
2952 rollPeriod
= Math
.min(rollPeriod
, originalData
.length
);
2953 var rollingData
= [];
2954 var sigma
= this.attr_("sigma");
2956 var low
, high
, i
, j
, y
, sum
, num_ok
, stddev
;
2957 if (this.fractions_
) {
2959 var den
= 0; // numerator/denominator
2961 for (i
= 0; i
< originalData
.length
; i
++) {
2962 num
+= originalData
[i
][1][0];
2963 den
+= originalData
[i
][1][1];
2964 if (i
- rollPeriod
>= 0) {
2965 num
-= originalData
[i
- rollPeriod
][1][0];
2966 den
-= originalData
[i
- rollPeriod
][1][1];
2969 var date
= originalData
[i
][0];
2970 var value
= den
? num
/ den
: 0.0;
2971 if (this.attr_("errorBars")) {
2972 if (this.attr_("wilsonInterval")) {
2973 // For more details on this confidence interval, see:
2974 // http://en.wikipedia.org/wiki
/Binomial_confidence_interval
2976 var p
= value
< 0 ? 0 : value
, n
= den
;
2977 var pm
= sigma
* Math
.sqrt(p
*(1-p
)/n + sigma*sigma/(4*n
*n
));
2978 var denom
= 1 + sigma
* sigma
/ den
;
2979 low
= (p
+ sigma
* sigma
/ (2 * den) - pm) / denom
;
2980 high
= (p
+ sigma
* sigma
/ (2 * den) + pm) / denom
;
2981 rollingData
[i
] = [date
,
2982 [p
* mult
, (p
- low
) * mult
, (high
- p
) * mult
]];
2984 rollingData
[i
] = [date
, [0, 0, 0]];
2987 stddev
= den
? sigma
* Math
.sqrt(value
* (1 - value
) / den
) : 1.0;
2988 rollingData
[i
] = [date
, [mult
* value
, mult
* stddev
, mult
* stddev
]];
2991 rollingData
[i
] = [date
, mult
* value
];
2994 } else if (this.attr_("customBars")) {
2999 for (i
= 0; i
< originalData
.length
; i
++) {
3000 var data
= originalData
[i
][1];
3002 rollingData
[i
] = [originalData
[i
][0], [y
, y
- data
[0], data
[2] - y
]];
3004 if (y
!== null && !isNaN(y
)) {
3010 if (i
- rollPeriod
>= 0) {
3011 var prev
= originalData
[i
- rollPeriod
];
3012 if (prev
[1][1] !== null && !isNaN(prev
[1][1])) {
3020 rollingData
[i
] = [originalData
[i
][0], [ 1.0 * mid
/ count
,
3021 1.0 * (mid
- low
) / count
,
3022 1.0 * (high
- mid
) / count
]];
3024 rollingData
[i
] = [originalData
[i
][0], [null, null, null]];
3028 // Calculate the rolling average for the first rollPeriod - 1 points where
3029 // there is not enough data to roll over the full number of points
3030 if (!this.attr_("errorBars")){
3031 if (rollPeriod
== 1) {
3032 return originalData
;
3035 for (i
= 0; i
< originalData
.length
; i
++) {
3038 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
3039 y
= originalData
[j
][1];
3040 if (y
=== null || isNaN(y
)) continue;
3042 sum
+= originalData
[j
][1];
3045 rollingData
[i
] = [originalData
[i
][0], sum
/ num_ok
];
3047 rollingData
[i
] = [originalData
[i
][0], null];
3052 for (i
= 0; i
< originalData
.length
; i
++) {
3056 for (j
= Math
.max(0, i
- rollPeriod
+ 1); j
< i
+ 1; j
++) {
3057 y
= originalData
[j
][1][0];
3058 if (y
=== null || isNaN(y
)) continue;
3060 sum
+= originalData
[j
][1][0];
3061 variance
+= Math
.pow(originalData
[j
][1][1], 2);
3064 stddev
= Math
.sqrt(variance
) / num_ok
;
3065 rollingData
[i
] = [originalData
[i
][0],
3066 [sum
/ num_ok
, sigma
* stddev
, sigma
* stddev
]];
3068 // This explicitly preserves NaNs to aid with "independent series".
3069 // See testRollingAveragePreservesNaNs.
3070 var v
= (rollPeriod
== 1) ? originalData
[i
][1][0] : null;
3071 rollingData
[i
] = [originalData
[i
][0], [v
, v
, v
]];
3081 * Detects the type of the str (date or numeric) and sets the various
3082 * formatting attributes in this.attrs_ based on this type.
3083 * @param {String} str An x value.
3086 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
3088 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
3089 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
3090 str
.indexOf('/') >= 0 ||
3091 isNaN(parseFloat(str
))) {
3093 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
3094 // TODO(danvk): remove support for this format.
3098 this.setXAxisOptions_(isDate
);
3101 Dygraph
.prototype.setXAxisOptions_
= function(isDate
) {
3103 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3104 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3105 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3106 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3108 /** @private (shut up, jsdoc!) */
3109 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3110 // TODO(danvk): use Dygraph.numberValueFormatter here?
3111 /** @private (shut up, jsdoc!) */
3112 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3113 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3114 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3119 * Parses the value as a floating point number. This is like the parseFloat()
3120 * built-in, but with a few differences:
3121 * - the empty string is parsed as null, rather than NaN.
3122 * - if the string cannot be parsed at all, an error is logged.
3123 * If the string can't be parsed, this method returns null.
3124 * @param {String} x The string to be parsed
3125 * @param {Number} opt_line_no The line number from which the string comes.
3126 * @param {String} opt_line The text of the line from which the string comes.
3130 // Parse the x as a float or return null if it's not a number.
3131 Dygraph
.prototype.parseFloat_
= function(x
, opt_line_no
, opt_line
) {
3132 var val
= parseFloat(x
);
3133 if (!isNaN(val
)) return val
;
3135 // Try to figure out what happeend.
3136 // If the value is the empty string, parse it as null.
3137 if (/^ *$/.test(x
)) return null;
3139 // If it was actually "NaN", return it as NaN.
3140 if (/^ *nan *$/i.test(x
)) return NaN
;
3142 // Looks like a parsing error.
3143 var msg
= "Unable to parse '" + x
+ "' as a number";
3144 if (opt_line
!== null && opt_line_no
!== null) {
3145 msg
+= " on line " + (1+opt_line_no
) + " ('" + opt_line
+ "') of CSV.";
3154 * Parses a string in a special csv format. We expect a csv file where each
3155 * line is a date point, and the first field in each line is the date string.
3156 * We also expect that all remaining fields represent series.
3157 * if the errorBars attribute is set, then interpret the fields as:
3158 * date, series1, stddev1, series2, stddev2, ...
3159 * @param {[Object]} data See above.
3161 * @return [Object] An array with one entry for each row. These entries
3162 * are an array of cells in that row. The first entry is the parsed x-value for
3163 * the row. The second, third, etc. are the y-values. These can take on one of
3164 * three forms, depending on the CSV and constructor parameters:
3166 * 2. [ value, stddev ]
3167 * 3. [ low value, center value, high value ]
3169 Dygraph
.prototype.parseCSV_
= function(data
) {
3171 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3172 var lines
= data
.split(line_delimiter
|| "\n");
3175 // Use the default delimiter or fall back to a tab if that makes sense.
3176 var delim
= this.attr_('delimiter');
3177 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
3182 if (!('labels' in this.user_attrs_
)) {
3183 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3185 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
3186 this.attributes_
.reparseSeries();
3191 var defaultParserSet
= false; // attempt to auto-detect x value type
3192 var expectedCols
= this.attr_("labels").length
;
3193 var outOfOrder
= false;
3194 for (var i
= start
; i
< lines
.length
; i
++) {
3195 var line
= lines
[i
];
3197 if (line
.length
=== 0) continue; // skip blank lines
3198 if (line
[0] == '#') continue; // skip comment lines
3199 var inFields
= line
.split(delim
);
3200 if (inFields
.length
< 2) continue;
3203 if (!defaultParserSet
) {
3204 this.detectTypeFromString_(inFields
[0]);
3205 xParser
= this.attr_("xValueParser");
3206 defaultParserSet
= true;
3208 fields
[0] = xParser(inFields
[0], this);
3210 // If fractions are expected, parse the numbers as "A/B
"
3211 if (this.fractions_) {
3212 for (j = 1; j < inFields.length; j++) {
3213 // TODO(danvk): figure out an appropriate way to flag parse errors.
3214 vals = inFields[j].split("/");
3215 if (vals.length != 2) {
3216 this.error('Expected fractional "num
/den
" values in CSV data ' +
3217 "but found a value
'" + inFields[j] + "' on line
" +
3218 (1 + i) + " ('" + line + "') which is not of
this form
.");
3221 fields[j] = [this.parseFloat_(vals[0], i, line),
3222 this.parseFloat_(vals[1], i, line)];
3225 } else if (this.attr_("errorBars
")) {
3226 // If there are error bars, values are (value, stddev) pairs
3227 if (inFields.length % 2 != 1) {
3228 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3229 'but line ' + (1 + i) + ' has an odd number of values (' +
3230 (inFields.length - 1) + "): '" + line + "'");
3232 for (j = 1; j < inFields.length; j += 2) {
3233 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3234 this.parseFloat_(inFields[j + 1], i, line)];
3236 } else if (this.attr_("customBars
")) {
3237 // Bars are a low;center;high tuple
3238 for (j = 1; j < inFields.length; j++) {
3239 var val = inFields[j];
3240 if (/^ *$/.test(val)) {
3241 fields[j] = [null, null, null];
3243 vals = val.split(";");
3244 if (vals.length == 3) {
3245 fields[j] = [ this.parseFloat_(vals[0], i, line),
3246 this.parseFloat_(vals[1], i, line),
3247 this.parseFloat_(vals[2], i, line) ];
3249 this.warn('When using customBars, values must be either blank ' +
3250 'or "low
;center
;high
" tuples (got "' + val +
3251 '" on line ' + (1+i));
3256 // Values are just numbers
3257 for (j = 1; j < inFields.length; j++) {
3258 fields[j] = this.parseFloat_(inFields[j], i, line);
3261 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3265 if (fields.length != expectedCols) {
3266 this.error("Number of columns
in line
" + i + " (" + fields.length +
3267 ") does not agree
with number of
labels (" + expectedCols +
3271 // If the user specified the 'labels' option and none of the cells of the
3272 // first row parsed correctly, then they probably double-specified the
3273 // labels. We go with the values set in the option, discard this row and
3274 // log a warning to the JS console.
3275 if (i === 0 && this.attr_('labels')) {
3276 var all_null = true;
3277 for (j = 0; all_null && j < fields.length; j++) {
3278 if (fields[j]) all_null = false;
3281 this.warn("The dygraphs
'labels' option is set
, but the first row of
" +
3282 "CSV
data ('" + line + "') appears to also contain labels
. " +
3283 "Will drop the CSV labels and
use the option labels
.");
3291 this.warn("CSV is out of order
; order it correctly to speed loading
.");
3292 ret.sort(function(a,b) { return a[0] - b[0]; });
3300 * The user has provided their data as a pre-packaged JS array. If the x values
3301 * are numeric, this is the same as dygraphs' internal format. If the x values
3302 * are dates, we need to convert them from Date objects to ms since epoch.
3303 * @param {[Object]} data
3304 * @return {[Object]} data with numeric x values.
3306 Dygraph.prototype.parseArray_ = function(data) {
3307 // Peek at the first x value to see if it's numeric.
3308 if (data.length === 0) {
3309 this.error("Can
't plot empty data set");
3312 if (data[0].length === 0) {
3313 this.error("Data set cannot contain an empty row");
3318 if (this.attr_("labels") === null) {
3319 this.warn("Using default labels. Set labels explicitly via 'labels
' " +
3320 "in the options parameter");
3321 this.attrs_.labels = [ "X" ];
3322 for (i = 1; i < data[0].length; i++) {
3323 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
3325 this.attributes_.reparseSeries();
3327 var num_labels = this.attr_("labels");
3328 if (num_labels.length != data[0].length) {
3329 this.error("Mismatch between number of labels (" + num_labels +
3330 ") and number of columns in array (" + data[0].length + ")");
3335 if (Dygraph.isDateLike(data[0][0])) {
3336 // Some intelligent defaults for a date x-axis.
3337 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
3338 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3339 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
3341 // Assume they're all dates
.
3342 var parsedData
= Dygraph
.clone(data
);
3343 for (i
= 0; i
< data
.length
; i
++) {
3344 if (parsedData
[i
].length
=== 0) {
3345 this.error("Row " + (1 + i
) + " of data is empty");
3348 if (parsedData
[i
][0] === null ||
3349 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3350 isNaN(parsedData
[i
][0].getTime())) {
3351 this.error("x value in row " + (1 + i
) + " is not a Date");
3354 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3358 // Some intelligent defaults for a numeric x-axis.
3359 /** @private (shut up, jsdoc!) */
3360 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3361 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3362 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3368 * Parses a DataTable object from gviz.
3369 * The data is expected to have a first column that is either a date or a
3370 * number. All subsequent columns must be numbers. If there is a clear mismatch
3371 * between this.xValueParser_ and the type of the first column, it will be
3372 * fixed. Fills out rawData_.
3373 * @param {[Object]} data See above.
3376 Dygraph
.prototype.parseDataTable_
= function(data
) {
3377 var shortTextForAnnotationNum
= function(num
) {
3378 // converts [0-9]+ [A-Z][a-z]*
3379 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3380 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3381 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3382 num
= Math
.floor(num
/ 26);
3384 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3385 num
= Math
.floor((num
- 1) / 26);
3390 var cols
= data
.getNumberOfColumns();
3391 var rows
= data
.getNumberOfRows();
3393 var indepType
= data
.getColumnType(0);
3394 if (indepType
== 'date' || indepType
== 'datetime') {
3395 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3396 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateString_
;
3397 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3398 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisFormatter
;
3399 } else if (indepType
== 'number') {
3400 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3401 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3402 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericLinearTicks
;
3403 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3405 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3406 "column 1 of DataTable input (Got '" + indepType
+ "')");
3410 // Array of the column indices which contain data (and not annotations).
3412 var annotationCols
= {}; // data index -> [annotation cols]
3413 var hasAnnotations
= false;
3415 for (i
= 1; i
< cols
; i
++) {
3416 var type
= data
.getColumnType(i
);
3417 if (type
== 'number') {
3419 } else if (type
== 'string' && this.attr_('displayAnnotations')) {
3420 // This is OK -- it's an annotation column.
3421 var dataIdx
= colIdx
[colIdx
.length
- 1];
3422 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3423 annotationCols
[dataIdx
] = [i
];
3425 annotationCols
[dataIdx
].push(i
);
3427 hasAnnotations
= true;
3429 this.error("Only 'number' is supported as a dependent type with Gviz." +
3430 " 'string' is only supported if displayAnnotations is true");
3434 // Read column labels
3435 // TODO(danvk): add support back for errorBars
3436 var labels
= [data
.getColumnLabel(0)];
3437 for (i
= 0; i
< colIdx
.length
; i
++) {
3438 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3439 if (this.attr_("errorBars")) i
+= 1;
3441 this.attrs_
.labels
= labels
;
3442 cols
= labels
.length
;
3445 var outOfOrder
= false;
3446 var annotations
= [];
3447 for (i
= 0; i
< rows
; i
++) {
3449 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3450 data
.getValue(i
, 0) === null) {
3451 this.warn("Ignoring row " + i
+
3452 " of DataTable because of undefined or null first column.");
3456 if (indepType
== 'date' || indepType
== 'datetime') {
3457 row
.push(data
.getValue(i
, 0).getTime());
3459 row
.push(data
.getValue(i
, 0));
3461 if (!this.attr_("errorBars")) {
3462 for (j
= 0; j
< colIdx
.length
; j
++) {
3463 var col
= colIdx
[j
];
3464 row
.push(data
.getValue(i
, col
));
3465 if (hasAnnotations
&&
3466 annotationCols
.hasOwnProperty(col
) &&
3467 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3469 ann
.series
= data
.getColumnLabel(col
);
3471 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3473 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3474 if (k
) ann
.text
+= "\n";
3475 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3477 annotations
.push(ann
);
3481 // Strip out infinities, which give dygraphs problems later on.
3482 for (j
= 0; j
< row
.length
; j
++) {
3483 if (!isFinite(row
[j
])) row
[j
] = null;
3486 for (j
= 0; j
< cols
- 1; j
++) {
3487 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3490 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3497 this.warn("DataTable is out of order; order it correctly to speed loading.");
3498 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3500 this.rawData_
= ret
;
3502 if (annotations
.length
> 0) {
3503 this.setAnnotations(annotations
, true);
3505 this.attributes_
.reparseSeries();
3509 * Get the CSV data. If it's in a function, call that function. If it's in a
3510 * file, do an XMLHttpRequest to get it.
3513 Dygraph
.prototype.start_
= function() {
3514 var data
= this.file_
;
3516 // Functions can return references of all other types.
3517 if (typeof data
== 'function') {
3521 if (Dygraph
.isArrayLike(data
)) {
3522 this.rawData_
= this.parseArray_(data
);
3524 } else if (typeof data
== 'object' &&
3525 typeof data
.getColumnRange
== 'function') {
3526 // must be a DataTable from gviz.
3527 this.parseDataTable_(data
);
3529 } else if (typeof data
== 'string') {
3530 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3531 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3532 if (line_delimiter
) {
3533 this.loadedEvent_(data
);
3535 var req
= new XMLHttpRequest();
3537 req
.onreadystatechange
= function () {
3538 if (req
.readyState
== 4) {
3539 if (req
.status
=== 200 || // Normal http
3540 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3541 caller
.loadedEvent_(req
.responseText
);
3546 req
.open("GET", data
, true);
3550 this.error("Unknown data format: " + (typeof data
));
3555 * Changes various properties of the graph. These can include:
3557 * <li>file: changes the source data for the graph</li>
3558 * <li>errorBars: changes whether the data contains stddev</li>
3561 * There's a huge variety of options that can be passed to this method. For a
3562 * full list, see http://dygraphs.com/options.html.
3564 * @param {Object} attrs The new properties and values
3565 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
3566 * call to updateOptions(). If you know better, you can pass true to explicitly
3567 * block the redraw. This can be useful for chaining updateOptions() calls,
3568 * avoiding the occasional infinite loop and preventing redraws when it's not
3569 * necessary (e.g. when updating a callback).
3571 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3572 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3574 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3575 var file
= input_attrs
.file
;
3576 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3578 // TODO(danvk): this is a mess. Move these options into attr_.
3579 if ('rollPeriod' in attrs
) {
3580 this.rollPeriod_
= attrs
.rollPeriod
;
3582 if ('dateWindow' in attrs
) {
3583 this.dateWindow_
= attrs
.dateWindow
;
3584 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3585 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3588 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3589 this.zoomed_y_
= (attrs
.valueRange
!== null);
3592 // TODO(danvk): validate per-series options.
3597 // highlightCircleSize
3599 // Check if this set options will require new points.
3600 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3602 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3604 this.attributes_
.reparseSeries();
3608 if (!block_redraw
) this.start_();
3610 if (!block_redraw
) {
3611 if (requiresNewPoints
) {
3614 this.renderGraph_(false);
3621 * Returns a copy of the options with deprecated names converted into current
3622 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3623 * interested in that, they should save a copy before calling this.
3626 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3628 for (var k
in attrs
) {
3629 if (k
== 'file') continue;
3630 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3633 var set
= function(axis
, opt
, value
) {
3634 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3635 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3636 my_attrs
.axes
[axis
][opt
] = value
;
3638 var map
= function(opt
, axis
, new_opt
) {
3639 if (typeof(attrs
[opt
]) != 'undefined') {
3640 Dygraph
.warn("Option " + opt
+ " is deprecated. Use the " +
3641 new_opt
+ " option for the " + axis
+ " axis instead. " +
3642 "(e.g. { axes : { " + axis
+ " : { " + new_opt
+ " : ... } } } " +
3643 "(see http://dygraphs.com/per-axis.html for more information.");
3644 set(axis
, new_opt
, attrs
[opt
]);
3645 delete my_attrs
[opt
];
3649 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3650 map('xValueFormatter', 'x', 'valueFormatter');
3651 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3652 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3653 map('xTicker', 'x', 'ticker');
3654 map('yValueFormatter', 'y', 'valueFormatter');
3655 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3656 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3657 map('yTicker', 'y', 'ticker');
3662 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3663 * containing div (which has presumably changed size since the dygraph was
3664 * instantiated. If the width/height are specified, the div will be resized.
3666 * This is far more efficient than destroying and re-instantiating a
3667 * Dygraph, since it doesn't have to reparse the underlying data.
3669 * @param {Number} [width] Width (in pixels)
3670 * @param {Number} [height] Height (in pixels)
3672 Dygraph
.prototype.resize
= function(width
, height
) {
3673 if (this.resize_lock
) {
3676 this.resize_lock
= true;
3678 if ((width
=== null) != (height
=== null)) {
3679 this.warn("Dygraph.resize() should be called with zero parameters or " +
3680 "two non-NULL parameters. Pretending it was zero.");
3681 width
= height
= null;
3684 var old_width
= this.width_
;
3685 var old_height
= this.height_
;
3688 this.maindiv_
.style
.width
= width
+ "px";
3689 this.maindiv_
.style
.height
= height
+ "px";
3690 this.width_
= width
;
3691 this.height_
= height
;
3693 this.width_
= this.maindiv_
.clientWidth
;
3694 this.height_
= this.maindiv_
.clientHeight
;
3697 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3698 // Resizing a canvas erases it, even when the size doesn't change, so
3699 // any resize needs to be followed by a redraw.
3700 this.resizeElements_();
3704 this.resize_lock
= false;
3708 * Adjusts the number of points in the rolling average. Updates the graph to
3709 * reflect the new averaging period.
3710 * @param {Number} length Number of points over which to average the data.
3712 Dygraph
.prototype.adjustRoll
= function(length
) {
3713 this.rollPeriod_
= length
;
3718 * Returns a boolean array of visibility statuses.
3720 Dygraph
.prototype.visibility
= function() {
3721 // Do lazy-initialization, so that this happens after we know the number of
3723 if (!this.attr_("visibility")) {
3724 this.attrs_
.visibility
= [];
3726 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3727 while (this.attr_("visibility").length
< this.numColumns() - 1) {
3728 this.attrs_
.visibility
.push(true);
3730 return this.attr_("visibility");
3734 * Changes the visiblity of a series.
3736 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3737 var x
= this.visibility();
3738 if (num
< 0 || num
>= x
.length
) {
3739 this.warn("invalid series number in setVisibility: " + num
);
3747 * How large of an area will the dygraph render itself in?
3748 * This is used for testing.
3749 * @return A {width: w, height: h} object.
3752 Dygraph
.prototype.size
= function() {
3753 return { width
: this.width_
, height
: this.height_
};
3757 * Update the list of annotations and redraw the chart.
3758 * See dygraphs.com/annotations.html for more info on how to use annotations.
3759 * @param ann {Array} An array of annotation objects.
3760 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3762 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3763 // Only add the annotation CSS rule once we know it will be used.
3764 Dygraph
.addAnnotationRule();
3765 this.annotations_
= ann
;
3766 if (!this.layout_
) {
3767 this.warn("Tried to setAnnotations before dygraph was ready. " +
3768 "Try setting them in a drawCallback. See " +
3769 "dygraphs.com/tests/annotation.html");
3773 this.layout_
.setAnnotations(this.annotations_
);
3774 if (!suppressDraw
) {
3780 * Return the list of annotations.
3782 Dygraph
.prototype.annotations
= function() {
3783 return this.annotations_
;
3787 * Get the list of label names for this graph. The first column is the
3788 * x-axis, so the data series names start at index 1.
3790 * Returns null when labels have not yet been defined.
3792 Dygraph
.prototype.getLabels
= function() {
3793 var labels
= this.attr_("labels");
3794 return labels
? labels
.slice() : null;
3798 * Get the index of a series (column) given its name. The first column is the
3799 * x-axis, so the data series start with index 1.
3801 Dygraph
.prototype.indexFromSetName
= function(name
) {
3802 return this.setIndexByName_
[name
];
3806 * Get the internal dataset index given its name. These are numbered starting from 0,
3807 * and only count visible sets.
3810 Dygraph
.prototype.datasetIndexFromSetName_
= function(name
) {
3811 return this.datasetIndex_
[this.indexFromSetName(name
)];
3816 * Adds a default style for the annotation CSS classes to the document. This is
3817 * only executed when annotations are actually used. It is designed to only be
3818 * called once -- all calls after the first will return immediately.
3820 Dygraph
.addAnnotationRule
= function() {
3821 // TODO(danvk): move this function into plugins/annotations.js
?
3822 if (Dygraph
.addedAnnotationCSS
) return;
3824 var rule
= "border: 1px solid black; " +
3825 "background-color: white; " +
3826 "text-align: center;";
3828 var styleSheetElement
= document
.createElement("style");
3829 styleSheetElement
.type
= "text/css";
3830 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3832 // Find the first style sheet that we can access.
3833 // We may not add a rule to a style sheet from another domain for security
3834 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3835 // adds its own style sheets from google.com.
3836 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3837 if (document
.styleSheets
[i
].disabled
) continue;
3838 var mysheet
= document
.styleSheets
[i
];
3840 if (mysheet
.insertRule
) { // Firefox
3841 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3842 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3843 } else if (mysheet
.addRule
) { // IE
3844 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3846 Dygraph
.addedAnnotationCSS
= true;
3849 // Was likely a security exception.
3853 this.warn("Unable to add default annotation CSS rule; display may be off.");
3856 // Older pages may still use this name.
3857 var DateGraph
= Dygraph
;