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,ActiveXObject: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 // These have to go above the "Hack for IE" in __init__ since .ready() can be
66 // called as soon as the constructor returns. Once support for OldIE is
67 // dropped, this can go down with the rest of the initializers.
68 this.is_initial_draw_
= true;
71 if (opt_fourth_param
!== undefined
) {
72 // Old versions of dygraphs took in the series labels as a constructor
73 // parameter. This doesn't make sense anymore, but it's easy to continue
74 // to support this usage.
75 Dygraph
.warn("Using deprecated four-argument dygraph constructor");
76 this.__old_init__(div
, data
, opts
, opt_fourth_param
);
78 this.__init__(div
, data
, opts
);
82 Dygraph
.NAME
= "Dygraph";
83 Dygraph
.VERSION
= "1.0.1";
84 Dygraph
.__repr__
= function() {
85 return "[" + Dygraph
.NAME
+ " " + Dygraph
.VERSION
+ "]";
89 * Returns information about the Dygraph class.
91 Dygraph
.toString
= function() {
92 return Dygraph
.__repr__();
95 // Various default values
96 Dygraph
.DEFAULT_ROLL_PERIOD
= 1;
97 Dygraph
.DEFAULT_WIDTH
= 480;
98 Dygraph
.DEFAULT_HEIGHT
= 320;
100 // For max 60 Hz. animation:
101 Dygraph
.ANIMATION_STEPS
= 12;
102 Dygraph
.ANIMATION_DURATION
= 200;
104 // Label constants for the labelsKMB and labelsKMG2 options.
105 // (i.e. '100000' -> '100K')
106 Dygraph
.KMB_LABELS
= [ 'K', 'M', 'B', 'T', 'Q' ];
107 Dygraph
.KMG2_BIG_LABELS
= [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
108 Dygraph
.KMG2_SMALL_LABELS
= [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
110 // These are defined before DEFAULT_ATTRS so that it can refer to them.
113 * Return a string version of a number. This respects the digitsAfterDecimal
114 * and maxNumberWidth options.
115 * @param {number} x The number to be formatted
116 * @param {Dygraph} opts An options view
117 * @param {string} name The name of the point's data series
118 * @param {Dygraph} g The dygraph object
120 Dygraph
.numberValueFormatter
= function(x
, opts
, pt
, g
) {
121 var sigFigs
= opts('sigFigs');
123 if (sigFigs
!== null) {
124 // User has opted for a fixed number of significant figures.
125 return Dygraph
.floatFormat(x
, sigFigs
);
128 var digits
= opts('digitsAfterDecimal');
129 var maxNumberWidth
= opts('maxNumberWidth');
131 var kmb
= opts('labelsKMB');
132 var kmg2
= opts('labelsKMG2');
136 // switch to scientific notation if we underflow or overflow fixed display.
138 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
139 Math
.abs(x
) < Math
.pow(10, -digits
))) {
140 label
= x
.toExponential(digits
);
142 label
= '' + Dygraph
.round_(x
, digits
);
151 k_labels
= Dygraph
.KMB_LABELS
;
154 if (kmb
) Dygraph
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
156 k_labels
= Dygraph
.KMG2_BIG_LABELS
;
157 m_labels
= Dygraph
.KMG2_SMALL_LABELS
;
160 var absx
= Math
.abs(x
);
161 var n
= Dygraph
.pow(k
, k_labels
.length
);
162 for (var j
= k_labels
.length
- 1; j
>= 0; j
--, n
/= k
) {
164 label
= Dygraph
.round_(x
/ n
, digits
) + k_labels
[j
];
169 // TODO(danvk): clean up this logic. Why so different than kmb?
170 var x_parts
= String(x
.toExponential()).split('e-');
171 if (x_parts
.length
=== 2 && x_parts
[1] >= 3 && x_parts
[1] <= 24) {
172 if (x_parts
[1] % 3 > 0) {
173 label
= Dygraph
.round_(x_parts
[0] /
174 Dygraph
.pow(10, (x_parts
[1] % 3)),
177 label
= Number(x_parts
[0]).toFixed(2);
179 label
+= m_labels
[Math
.floor(x_parts
[1] / 3) - 1];
188 * variant for use as an axisLabelFormatter.
191 Dygraph
.numberAxisLabelFormatter
= function(x
, granularity
, opts
, g
) {
192 return Dygraph
.numberValueFormatter(x
, opts
, g
);
196 * @type {!Array.<string>}
200 Dygraph
.SHORT_MONTH_NAMES_
= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
204 * Convert a JS date to a string appropriate to display on an axis that
205 * is displaying values at the stated granularity. This respects the
206 * labelsDateUTC option.
207 * @param {Date} date The date to format
208 * @param {number} granularity One of the Dygraph granularity constants
209 * @param {Dygraph} opts An options view
210 * @return {string} The date formatted as local time
213 Dygraph
.dateAxisLabelFormatter
= function(date
, granularity
, opts
) {
214 var utc
= opts('labelsDateUTC');
215 var year
, month
, day
, hours
, mins
, secs
, millis
;
217 year
= date
.getUTCFullYear();
218 month
= date
.getUTCMonth();
219 day
= date
.getUTCDate();
220 hours
= date
.getUTCHours();
221 mins
= date
.getUTCMinutes();
222 secs
= date
.getUTCSeconds();
223 millis
= date
.getUTCMilliseconds();
225 year
= date
.getFullYear();
226 month
= date
.getMonth();
227 day
= date
.getDate();
228 hours
= date
.getHours();
229 mins
= date
.getMinutes();
230 secs
= date
.getSeconds();
231 millis
= date
.getMilliseconds();
233 if (granularity
>= Dygraph
.DECADAL
) {
235 } else if (granularity
>= Dygraph
.MONTHLY
) {
236 return Dygraph
.SHORT_MONTH_NAMES_
[month
] + ' ' + Dygraph
.zeropad(year
% 100);
238 // 1e-3 factor on millis missing in original implementation
239 var frac
= hours
* 3600 + mins
* 60 + secs
+ 1e-3 * millis
;
240 if (frac
=== 0 || granularity
>= Dygraph
.DAILY
) {
241 // e.g. '21Jan' (%d%b)
242 return Dygraph
.zeropad(day
) + Dygraph
.SHORT_MONTH_NAMES_
[month
];
244 return Dygraph
.hmsString_(hours
, mins
, secs
);
251 * Return a string version of a JS date for a value label. This respects the
252 * labelsDateUTC option.
253 * @param {Date} date The date to be formatted
254 * @param {Dygraph} opts An options view
256 Dygraph
.dateValueFormatter
= function(d
, opts
) {
257 return Dygraph
.dateString_(d
, opts('labelsDateUTC'));
261 * Standard plotters. These may be used by clients.
262 * Available plotters are:
263 * - Dygraph.Plotters.linePlotter: draws central lines (most common)
264 * - Dygraph.Plotters.errorPlotter: draws error bars
265 * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph)
267 * By default, the plotter is [fillPlotter, errorPlotter, linePlotter].
268 * This causes all the lines to be drawn over all the fills/error bars.
270 Dygraph
.Plotters
= DygraphCanvasRenderer
._Plotters
;
273 // Default attribute values.
274 Dygraph
.DEFAULT_ATTRS
= {
275 highlightCircleSize
: 3,
276 highlightSeriesOpts
: null,
277 highlightSeriesBackgroundAlpha
: 0.5,
281 // TODO(danvk): move defaults from createStatusMessage_ here.
283 labelsSeparateLines
: false,
284 labelsShowZeroValues
: true,
287 showLabelsOnHighlight
: true,
289 digitsAfterDecimal
: 2,
294 strokeBorderWidth
: 0,
295 strokeBorderColor
: "white",
298 axisLabelFontSize
: 14,
304 xValueParser
: Dygraph
.dateParser
,
311 wilsonInterval
: true, // only relevant if fractions is true
315 connectSeparatedPoints
: false,
318 stackedGraphNaNFill
: 'all',
319 hideOverlayOnMouseOut
: true,
321 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
322 legend
: 'onmouseover', // the only relevant value at the moment is 'always'.
328 drawAxesAtZero
: false,
330 // Sizes of the various chart labels.
337 axisLineColor
: "black",
340 axisLabelColor
: "black",
341 axisLabelFont
: "Arial", // TODO(danvk): is this implemented?
345 gridLineColor
: "rgb(128,128,128)",
347 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
348 animatedZooms
: false, // (for now)
350 // Range selector options
351 showRangeSelector
: false,
352 rangeSelectorHeight
: 40,
353 rangeSelectorPlotStrokeColor
: "#808FAB",
354 rangeSelectorPlotFillColor
: "#A7B1C4",
356 // The ordering here ensures that central lines always appear above any
357 // fill bars/error bars
.
359 Dygraph
.Plotters
.fillPlotter
,
360 Dygraph
.Plotters
.errorPlotter
,
361 Dygraph
.Plotters
.linePlotter
370 axisLabelFormatter
: Dygraph
.dateAxisLabelFormatter
,
371 valueFormatter
: Dygraph
.dateValueFormatter
,
374 independentTicks
: true,
375 ticker
: null // will be set in dygraph-tickers.js
379 valueFormatter
: Dygraph
.numberValueFormatter
,
380 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
383 independentTicks
: true,
384 ticker
: null // will be set in dygraph-tickers.js
388 valueFormatter
: Dygraph
.numberValueFormatter
,
389 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
392 independentTicks
: false,
393 ticker
: null // will be set in dygraph-tickers.js
398 // Directions for panning and zooming. Use bit operations when combined
399 // values are possible.
400 Dygraph
.HORIZONTAL
= 1;
401 Dygraph
.VERTICAL
= 2;
403 // Installed plugins, in order of precedence (most-general to most-specific).
404 // Plugins are installed after they are defined, in plugins/install.js
.
408 // Used for initializing annotation CSS rules only once.
409 Dygraph
.addedAnnotationCSS
= false;
411 Dygraph
.prototype.__old_init__
= function(div
, file
, labels
, attrs
) {
412 // Labels is no longer a constructor parameter, since it's typically set
413 // directly from the data source. It also conains a name for the x-axis,
414 // which the previous constructor form did not.
415 if (labels
!== null) {
416 var new_labels
= ["Date"];
417 for (var i
= 0; i
< labels
.length
; i
++) new_labels
.push(labels
[i
]);
418 Dygraph
.update(attrs
, { 'labels': new_labels
});
420 this.__init__(div
, file
, attrs
);
424 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
425 * and context <canvas> inside of it. See the constructor for details.
427 * @param {Element} div the Element to render the graph into.
428 * @param {string | Function} file Source data
429 * @param {Object} attrs Miscellaneous other options
432 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
433 // Hack for IE: if we're using excanvas and the document hasn't finished
434 // loading yet (and hence may not have initialized whatever it needs to
435 // initialize), then keep calling this routine periodically until it has.
436 if (/MSIE/.test(navigator
.userAgent
) && !window
.opera
&&
437 typeof(G_vmlCanvasManager
) != 'undefined' &&
438 document
.readyState
!= 'complete') {
440 setTimeout(function() { self
.__init__(div
, file
, attrs
); }, 100);
444 // Support two-argument constructor
445 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
447 attrs
= Dygraph
.mapLegacyOptions_(attrs
);
449 if (typeof(div
) == 'string') {
450 div
= document
.getElementById(div
);
454 Dygraph
.error("Constructing dygraph with a non-existent div!");
458 this.isUsingExcanvas_
= typeof(G_vmlCanvasManager
) != 'undefined';
460 // Copy the important bits into the object
461 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
464 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
465 this.previousVerticalX_
= -1;
466 this.fractions_
= attrs
.fractions
|| false;
467 this.dateWindow_
= attrs
.dateWindow
|| null;
469 this.annotations_
= [];
471 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
472 this.zoomed_x_
= false;
473 this.zoomed_y_
= false;
475 // Clear the div. This ensure that, if multiple dygraphs are passed the same
476 // div, then only one will be drawn.
479 // For historical reasons, the 'width' and 'height' options trump all CSS
480 // rules _except_ for an explicit 'width' or 'height' on the div.
481 // As an added convenience, if the div has zero height (like <div></div> does
482 // without any styles), then we use a default height/width
.
483 if (div
.style
.width
=== '' && attrs
.width
) {
484 div
.style
.width
= attrs
.width
+ "px";
486 if (div
.style
.height
=== '' && attrs
.height
) {
487 div
.style
.height
= attrs
.height
+ "px";
489 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
490 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
491 if (div
.style
.width
=== '') {
492 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
495 // These will be zero if the dygraph's div is hidden. In that case,
496 // use the user-specified attributes if present. If not, use zero
497 // and assume the user will call resize to fix things later.
498 this.width_
= div
.clientWidth
|| attrs
.width
|| 0;
499 this.height_
= div
.clientHeight
|| attrs
.height
|| 0;
501 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
502 if (attrs
.stackedGraph
) {
503 attrs
.fillGraph
= true;
504 // TODO(nikhilk): Add any other stackedGraph checks here.
507 // DEPRECATION WARNING: All option processing should be moved from
508 // attrs_ and user_attrs_ to options_, which holds all this information.
510 // Dygraphs has many options, some of which interact with one another.
511 // To keep track of everything, we maintain two sets of options:
513 // this.user_attrs_ only options explicitly set by the user.
514 // this.attrs_ defaults, options derived from user_attrs_, data.
516 // Options are then accessed this.attr_('attr'), which first looks at
517 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
518 // defaults without overriding behavior that the user specifically asks for.
519 this.user_attrs_
= {};
520 Dygraph
.update(this.user_attrs_
, attrs
);
522 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
524 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
526 this.boundaryIds_
= [];
527 this.setIndexByName_
= {};
528 this.datasetIndex_
= [];
530 this.registeredEvents_
= [];
531 this.eventListeners_
= {};
533 this.attributes_
= new DygraphOptions(this);
535 // Create the containing DIV and other interactive elements
536 this.createInterface_();
540 var plugins
= Dygraph
.PLUGINS
.concat(this.getOption('plugins'));
541 for (var i
= 0; i
< plugins
.length
; i
++) {
542 var Plugin
= plugins
[i
];
543 var pluginInstance
= new Plugin();
545 plugin
: pluginInstance
,
551 var handlers
= pluginInstance
.activate(this);
552 for (var eventName
in handlers
) {
553 // TODO(danvk): validate eventName.
554 pluginDict
.events
[eventName
] = handlers
[eventName
];
557 this.plugins_
.push(pluginDict
);
560 // At this point, plugins can no longer register event handlers.
561 // Construct a map from event -> ordered list of [callback, plugin].
562 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
563 var plugin_dict
= this.plugins_
[i
];
564 for (var eventName
in plugin_dict
.events
) {
565 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
566 var callback
= plugin_dict
.events
[eventName
];
568 var pair
= [plugin_dict
.plugin
, callback
];
569 if (!(eventName
in this.eventListeners_
)) {
570 this.eventListeners_
[eventName
] = [pair
];
572 this.eventListeners_
[eventName
].push(pair
);
577 this.createDragInterface_();
583 * Triggers a cascade of events to the various plugins which are interested in them.
584 * Returns true if the "default behavior" should be performed, i.e. if none of
585 * the event listeners called event.preventDefault().
588 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
589 if (!(name
in this.eventListeners_
)) return true;
591 // QUESTION: can we use objects & prototypes to speed this up?
595 defaultPrevented
: false,
596 preventDefault
: function() {
597 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
598 e
.defaultPrevented
= true;
600 propagationStopped
: false,
601 stopPropagation
: function() {
602 e
.propagationStopped
= true;
605 Dygraph
.update(e
, extra_props
);
607 var callback_plugin_pairs
= this.eventListeners_
[name
];
608 if (callback_plugin_pairs
) {
609 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
610 var plugin
= callback_plugin_pairs
[i
][0];
611 var callback
= callback_plugin_pairs
[i
][1];
612 callback
.call(plugin
, e
);
613 if (e
.propagationStopped
) break;
616 return e
.defaultPrevented
;
620 * Fetch a plugin instance of a particular class. Only for testing.
622 * @param {!Class} type The type of the plugin.
623 * @return {Object} Instance of the plugin, or null if there is none.
625 Dygraph
.prototype.getPluginInstance_
= function(type
) {
626 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
627 var p
= this.plugins_
[i
];
628 if (p
.plugin
instanceof type
) {
636 * Returns the zoomed status of the chart for one or both axes.
638 * Axis is an optional parameter. Can be set to 'x' or 'y'.
640 * The zoomed status for an axis is set whenever a user zooms using the mouse
641 * or when the dateWindow or valueRange are updated (unless the
642 * isZoomedIgnoreProgrammaticZoom option is also specified).
644 Dygraph
.prototype.isZoomed
= function(axis
) {
645 if (axis
=== null || axis
=== undefined
) {
646 return this.zoomed_x_
|| this.zoomed_y_
;
648 if (axis
=== 'x') return this.zoomed_x_
;
649 if (axis
=== 'y') return this.zoomed_y_
;
650 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
654 * Returns information about the Dygraph object, including its containing ID.
656 Dygraph
.prototype.toString
= function() {
657 var maindiv
= this.maindiv_
;
658 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
659 return "[Dygraph " + id
+ "]";
664 * Returns the value of an option. This may be set by the user (either in the
665 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
667 * @param {string} name The name of the option, e.g. 'rollPeriod'.
668 * @param {string} [seriesName] The name of the series to which the option
669 * will be applied. If no per-series value of this option is available, then
670 * the global value is returned. This is optional.
671 * @return { ... } The value of the option.
673 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
674 // <REMOVE_FOR_COMBINED>
675 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
676 Dygraph
.error('Must include options reference JS for testing');
677 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
678 Dygraph
.error('Dygraphs is using property ' + name
+ ', which has no ' +
679 'entry in the Dygraphs.OPTIONS_REFERENCE listing.');
680 // Only log this error once.
681 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
683 // </REMOVE_FOR_COMBINED
>
684 return seriesName
? this.attributes_
.getForSeries(name
, seriesName
) : this.attributes_
.get(name
);
688 * Returns the current value for an option, as set in the constructor or via
689 * updateOptions. You may pass in an (optional) series name to get per-series
690 * values for the option.
692 * All values returned by this method should be considered immutable. If you
693 * modify them, there is no guarantee that the changes will be honored or that
694 * dygraphs will remain in a consistent state. If you want to modify an option,
695 * use updateOptions() instead.
697 * @param {string} name The name of the option (e.g. 'strokeWidth')
698 * @param {string=} opt_seriesName Series name to get per-series values.
699 * @return {*} The value of the option.
701 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
702 return this.attr_(name
, opt_seriesName
);
706 * Like getOption(), but specifically returns a number.
707 * This is a convenience function for working with the Closure Compiler.
708 * @param {string} name The name of the option (e.g. 'strokeWidth')
709 * @param {string=} opt_seriesName Series name to get per-series values.
710 * @return {number} The value of the option.
713 Dygraph
.prototype.getNumericOption
= function(name
, opt_seriesName
) {
714 return /** @type{number} */(this.getOption(name
, opt_seriesName
));
718 * Like getOption(), but specifically returns a string.
719 * This is a convenience function for working with the Closure Compiler.
720 * @param {string} name The name of the option (e.g. 'strokeWidth')
721 * @param {string=} opt_seriesName Series name to get per-series values.
722 * @return {string} The value of the option.
725 Dygraph
.prototype.getStringOption
= function(name
, opt_seriesName
) {
726 return /** @type{string} */(this.getOption(name
, opt_seriesName
));
730 * Like getOption(), but specifically returns a boolean.
731 * This is a convenience function for working with the Closure Compiler.
732 * @param {string} name The name of the option (e.g. 'strokeWidth')
733 * @param {string=} opt_seriesName Series name to get per-series values.
734 * @return {boolean} The value of the option.
737 Dygraph
.prototype.getBooleanOption
= function(name
, opt_seriesName
) {
738 return /** @type{boolean} */(this.getOption(name
, opt_seriesName
));
742 * Like getOption(), but specifically returns a function.
743 * This is a convenience function for working with the Closure Compiler.
744 * @param {string} name The name of the option (e.g. 'strokeWidth')
745 * @param {string=} opt_seriesName Series name to get per-series values.
746 * @return {function(...)} The value of the option.
749 Dygraph
.prototype.getFunctionOption
= function(name
, opt_seriesName
) {
750 return /** @type{function(...)} */(this.getOption(name
, opt_seriesName
));
753 Dygraph
.prototype.getOptionForAxis
= function(name
, axis
) {
754 return this.attributes_
.getForAxis(name
, axis
);
759 * @param {string} axis The name of the axis (i.e. 'x', 'y' or 'y2')
760 * @return { ... } A function mapping string -> option value
762 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
764 return function(opt
) {
765 var axis_opts
= self
.user_attrs_
.axes
;
766 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
767 return axis_opts
[axis
][opt
];
770 // I don't like that this is in a second spot.
771 if (axis
=== 'x' && opt
=== 'logscale') {
772 // return the default value.
773 // TODO(konigsberg): pull the default from a global default.
777 // user-specified attributes always trump defaults, even if they're less
779 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
780 return self
.user_attrs_
[opt
];
783 axis_opts
= self
.attrs_
.axes
;
784 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
785 return axis_opts
[axis
][opt
];
787 // check old-style axis options
788 // TODO(danvk): add a deprecation warning if either of these match.
789 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
790 return self
.axes_
[0][opt
];
791 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
792 return self
.axes_
[1][opt
];
794 return self
.attr_(opt
);
799 * Returns the current rolling period, as set by the user or an option.
800 * @return {number} The number of points in the rolling window
802 Dygraph
.prototype.rollPeriod
= function() {
803 return this.rollPeriod_
;
807 * Returns the currently-visible x-range. This can be affected by zooming,
808 * panning or a call to updateOptions.
809 * Returns a two-element array: [left, right].
810 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
812 Dygraph
.prototype.xAxisRange
= function() {
813 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
817 * Returns the lower- and upper-bound x-axis values of the
820 Dygraph
.prototype.xAxisExtremes
= function() {
821 var pad
= this.getNumericOption('xRangePad') / this.plotter_
.area
.w
;
822 if (this.numRows() === 0) {
823 return [0 - pad
, 1 + pad
];
825 var left
= this.rawData_
[0][0];
826 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
828 // Must keep this in sync with dygraph-layout _evaluateLimits()
829 var range
= right
- left
;
831 right
+= range
* pad
;
833 return [left
, right
];
837 * Returns the currently-visible y-range for an axis. This can be affected by
838 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
839 * called with no arguments, returns the range of the first axis.
840 * Returns a two-element array: [bottom, top].
842 Dygraph
.prototype.yAxisRange
= function(idx
) {
843 if (typeof(idx
) == "undefined") idx
= 0;
844 if (idx
< 0 || idx
>= this.axes_
.length
) {
847 var axis
= this.axes_
[idx
];
848 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
852 * Returns the currently-visible y-ranges for each axis. This can be affected by
853 * zooming, panning, calls to updateOptions, etc.
854 * Returns an array of [bottom, top] pairs, one for each y-axis.
856 Dygraph
.prototype.yAxisRanges
= function() {
858 for (var i
= 0; i
< this.axes_
.length
; i
++) {
859 ret
.push(this.yAxisRange(i
));
864 // TODO(danvk): use these functions throughout dygraphs.
866 * Convert from data coordinates to canvas/div X/Y coordinates.
867 * If specified, do this conversion for the coordinate system of a particular
868 * axis. Uses the first axis by default.
869 * Returns a two-element array: [X, Y]
871 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
872 * instead of toDomCoords(null, y, axis).
874 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
875 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
879 * Convert from data x coordinates to canvas/div X coordinate.
880 * If specified, do this conversion for the coordinate system of a particular
882 * Returns a single value or null if x is null.
884 Dygraph
.prototype.toDomXCoord
= function(x
) {
889 var area
= this.plotter_
.area
;
890 var xRange
= this.xAxisRange();
891 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
895 * Convert from data x coordinates to canvas/div Y coordinate and optional
896 * axis. Uses the first axis by default.
898 * returns a single value or null if y is null.
900 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
901 var pct
= this.toPercentYCoord(y
, axis
);
906 var area
= this.plotter_
.area
;
907 return area
.y
+ pct
* area
.h
;
911 * Convert from canvas/div coords to data coordinates.
912 * If specified, do this conversion for the coordinate system of a particular
913 * axis. Uses the first axis by default.
914 * Returns a two-element array: [X, Y].
916 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
917 * instead of toDataCoords(null, y, axis).
919 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
920 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
924 * Convert from canvas/div x coordinate to data coordinate.
926 * If x is null, this returns null.
928 Dygraph
.prototype.toDataXCoord
= function(x
) {
933 var area
= this.plotter_
.area
;
934 var xRange
= this.xAxisRange();
936 if (!this.attributes_
.getForAxis("logscale", 'x')) {
937 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
939 // TODO: remove duplicate code?
940 // Computing the inverse of toDomCoord.
941 var pct
= (x
- area
.x
) / area
.w
;
943 // Computing the inverse of toPercentXCoord. The function was arrived at with
944 // the following steps:
946 // Original calcuation:
947 // pct = (log(x) - log(xRange[0])) / (log(xRange
[1]) - log(xRange
[0])));
949 // Multiply both sides by the right-side demoninator.
950 // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0])
952 // add log(xRange[0]) to both sides
953 // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) = log(x);
955 // Swap both sides of the equation,
956 // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))
958 // Use both sides as the exponent in 10^exp and we're done.
959 // x = 10 ^ (log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])))
960 var logr0
= Dygraph
.log10(xRange
[0]);
961 var logr1
= Dygraph
.log10(xRange
[1]);
962 var exponent
= logr0
+ (pct
* (logr1
- logr0
));
963 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
969 * Convert from canvas/div y coord to value.
971 * If y is null, this returns null.
972 * if axis is null, this uses the first axis.
974 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
979 var area
= this.plotter_
.area
;
980 var yRange
= this.yAxisRange(axis
);
982 if (typeof(axis
) == "undefined") axis
= 0;
983 if (!this.attributes_
.getForAxis("logscale", axis
)) {
984 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
986 // Computing the inverse of toDomCoord.
987 var pct
= (y
- area
.y
) / area
.h
;
989 // Computing the inverse of toPercentYCoord. The function was arrived at with
990 // the following steps:
992 // Original calcuation:
993 // pct = (log(yRange[1]) - log(y)) / (log(yRange
[1]) - log(yRange
[0]));
995 // Multiply both sides by the right-side demoninator.
996 // pct * (log(yRange[1]) - log(yRange[0])) = log(yRange[1]) - log(y);
998 // subtract log(yRange[1]) from both sides.
999 // (pct * (log(yRange[1]) - log(yRange[0]))) - log(yRange[1]) = -log(y);
1001 // and multiply both sides by -1.
1002 // log(yRange[1]) - (pct * (logr1 - log(yRange[0])) = log(y);
1004 // Swap both sides of the equation,
1005 // log(y) = log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0])));
1007 // Use both sides as the exponent in 10^exp and we're done.
1008 // y = 10 ^ (log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0]))));
1009 var logr0
= Dygraph
.log10(yRange
[0]);
1010 var logr1
= Dygraph
.log10(yRange
[1]);
1011 var exponent
= logr1
- (pct
* (logr1
- logr0
));
1012 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
1018 * Converts a y for an axis to a percentage from the top to the
1019 * bottom of the drawing area.
1021 * If the coordinate represents a value visible on the canvas, then
1022 * the value will be between 0 and 1, where 0 is the top of the canvas.
1023 * However, this method will return values outside the range, as
1024 * values can fall outside the canvas.
1026 * If y is null, this returns null.
1027 * if axis is null, this uses the first axis.
1029 * @param {number} y The data y-coordinate.
1030 * @param {number} [axis] The axis number on which the data coordinate lives.
1031 * @return {number} A fraction in [0, 1] where 0 = the top edge.
1033 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
1037 if (typeof(axis
) == "undefined") axis
= 0;
1039 var yRange
= this.yAxisRange(axis
);
1042 var logscale
= this.attributes_
.getForAxis("logscale", axis
);
1044 var logr0
= Dygraph
.log10(yRange
[0]);
1045 var logr1
= Dygraph
.log10(yRange
[1]);
1046 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- logr0
);
1048 // yRange[1] - y is unit distance from the bottom.
1049 // yRange[1] - yRange[0] is the scale of the range.
1050 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
1051 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
1057 * Converts an x value to a percentage from the left to the right of
1060 * If the coordinate represents a value visible on the canvas, then
1061 * the value will be between 0 and 1, where 0 is the left of the canvas.
1062 * However, this method will return values outside the range, as
1063 * values can fall outside the canvas.
1065 * If x is null, this returns null.
1066 * @param {number} x The data x-coordinate.
1067 * @return {number} A fraction in [0, 1] where 0 = the left edge.
1069 Dygraph
.prototype.toPercentXCoord
= function(x
) {
1074 var xRange
= this.xAxisRange();
1076 var logscale
= this.attributes_
.getForAxis("logscale", 'x') ;
1077 if (logscale
== true) { // logscale can be null so we test for true explicitly.
1078 var logr0
= Dygraph
.log10(xRange
[0]);
1079 var logr1
= Dygraph
.log10(xRange
[1]);
1080 pct
= (Dygraph
.log10(x
) - logr0
) / (logr1
- logr0
);
1082 // x - xRange[0] is unit distance from the left.
1083 // xRange[1] - xRange[0] is the scale of the range.
1084 // The full expression below is the % from the left.
1085 pct
= (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
1091 * Returns the number of columns (including the independent variable).
1092 * @return {number} The number of columns.
1094 Dygraph
.prototype.numColumns
= function() {
1095 if (!this.rawData_
) return 0;
1096 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
1100 * Returns the number of rows (excluding any header/label row).
1101 * @return {number} The number of rows, less any header.
1103 Dygraph
.prototype.numRows
= function() {
1104 if (!this.rawData_
) return 0;
1105 return this.rawData_
.length
;
1109 * Returns the value in the given row and column. If the row and column exceed
1110 * the bounds on the data, returns null. Also returns null if the value is
1112 * @param {number} row The row number of the data (0-based). Row 0 is the
1113 * first row of data, not a header row.
1114 * @param {number} col The column number of the data (0-based)
1115 * @return {number} The value in the specified cell or null if the row/col
1116 * were out of range.
1118 Dygraph
.prototype.getValue
= function(row
, col
) {
1119 if (row
< 0 || row
> this.rawData_
.length
) return null;
1120 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
1122 return this.rawData_
[row
][col
];
1126 * Generates interface elements for the Dygraph: a containing div, a div to
1127 * display the current point, and a textbox to adjust the rolling average
1128 * period. Also creates the Renderer/Layout elements.
1131 Dygraph
.prototype.createInterface_
= function() {
1132 // Create the all-enclosing graph div
1133 var enclosing
= this.maindiv_
;
1135 this.graphDiv
= document
.createElement("div");
1137 // TODO(danvk): any other styles that are useful to set here?
1138 this.graphDiv
.style
.textAlign
= 'left'; // This is a CSS "reset"
1139 this.graphDiv
.style
.position
= 'relative';
1140 enclosing
.appendChild(this.graphDiv
);
1142 // Create the canvas for interactive parts of the chart.
1143 this.canvas_
= Dygraph
.createCanvas();
1144 this.canvas_
.style
.position
= "absolute";
1146 // ... and for static parts of the chart.
1147 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
1149 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
1150 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
1152 this.resizeElements_();
1154 // The interactive parts of the graph are drawn on top of the chart.
1155 this.graphDiv
.appendChild(this.hidden_
);
1156 this.graphDiv
.appendChild(this.canvas_
);
1157 this.mouseEventElement_
= this.createMouseEventElement_();
1159 // Create the grapher
1160 this.layout_
= new DygraphLayout(this);
1164 this.mouseMoveHandler_
= function(e
) {
1165 dygraph
.mouseMove_(e
);
1168 this.mouseOutHandler_
= function(e
) {
1169 // The mouse has left the chart if:
1170 // 1. e.target is inside the chart
1171 // 2. e.relatedTarget is outside the chart
1172 var target
= e
.target
|| e
.fromElement
;
1173 var relatedTarget
= e
.relatedTarget
|| e
.toElement
;
1174 if (Dygraph
.isNodeContainedBy(target
, dygraph
.graphDiv
) &&
1175 !Dygraph
.isNodeContainedBy(relatedTarget
, dygraph
.graphDiv
)) {
1176 dygraph
.mouseOut_(e
);
1180 this.addAndTrackEvent(window
, 'mouseout', this.mouseOutHandler_
);
1181 this.addAndTrackEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1183 // Don't recreate and register the resize handler on subsequent calls.
1184 // This happens when the graph is resized.
1185 if (!this.resizeHandler_
) {
1186 this.resizeHandler_
= function(e
) {
1190 // Update when the window is resized.
1191 // TODO(danvk): drop frames depending on complexity of the chart.
1192 this.addAndTrackEvent(window
, 'resize', this.resizeHandler_
);
1196 Dygraph
.prototype.resizeElements_
= function() {
1197 this.graphDiv
.style
.width
= this.width_
+ "px";
1198 this.graphDiv
.style
.height
= this.height_
+ "px";
1200 var canvasScale
= Dygraph
.getContextPixelRatio(this.canvas_ctx_
);
1201 this.canvas_
.width
= this.width_
* canvasScale
;
1202 this.canvas_
.height
= this.height_
* canvasScale
;
1203 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
1204 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
1205 if (canvasScale
!== 1) {
1206 this.canvas_ctx_
.scale(canvasScale
, canvasScale
);
1209 var hiddenScale
= Dygraph
.getContextPixelRatio(this.hidden_ctx_
);
1210 this.hidden_
.width
= this.width_
* hiddenScale
;
1211 this.hidden_
.height
= this.height_
* hiddenScale
;
1212 this.hidden_
.style
.width
= this.width_
+ "px"; // for IE
1213 this.hidden_
.style
.height
= this.height_
+ "px"; // for IE
1214 if (hiddenScale
!== 1) {
1215 this.hidden_ctx_
.scale(hiddenScale
, hiddenScale
);
1220 * Detach DOM elements in the dygraph and null out all data references.
1221 * Calling this when you're done with a dygraph can dramatically reduce memory
1222 * usage. See, e.g., the tests/perf.html example.
1224 Dygraph
.prototype.destroy
= function() {
1225 this.canvas_ctx_
.restore();
1226 this.hidden_ctx_
.restore();
1228 var removeRecursive
= function(node
) {
1229 while (node
.hasChildNodes()) {
1230 removeRecursive(node
.firstChild
);
1231 node
.removeChild(node
.firstChild
);
1235 this.removeTrackedEvents_();
1237 // remove mouse event handlers (This may not be necessary anymore)
1238 Dygraph
.removeEvent(window
, 'mouseout', this.mouseOutHandler_
);
1239 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1241 // remove window handlers
1242 Dygraph
.removeEvent(window
,'resize',this.resizeHandler_
);
1243 this.resizeHandler_
= null;
1245 removeRecursive(this.maindiv_
);
1247 var nullOut
= function(obj
) {
1248 for (var n
in obj
) {
1249 if (typeof(obj
[n
]) === 'object') {
1254 // These may not all be necessary, but it can't hurt...
1255 nullOut(this.layout_
);
1256 nullOut(this.plotter_
);
1261 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1262 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1263 * or the zoom rectangles) is done on this.canvas_.
1264 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1265 * @return {Object} The newly-created canvas
1268 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1269 var h
= Dygraph
.createCanvas();
1270 h
.style
.position
= "absolute";
1271 // TODO(danvk): h should be offset from canvas. canvas needs to include
1272 // some extra area to make it easier to zoom in on the far left and far
1273 // right. h needs to be precisely the plot area, so that clipping occurs.
1274 h
.style
.top
= canvas
.style
.top
;
1275 h
.style
.left
= canvas
.style
.left
;
1276 h
.width
= this.width_
;
1277 h
.height
= this.height_
;
1278 h
.style
.width
= this.width_
+ "px"; // for IE
1279 h
.style
.height
= this.height_
+ "px"; // for IE
1284 * Creates an overlay element used to handle mouse events.
1285 * @return {Object} The mouse event element.
1288 Dygraph
.prototype.createMouseEventElement_
= function() {
1289 if (this.isUsingExcanvas_
) {
1290 var elem
= document
.createElement("div");
1291 elem
.style
.position
= 'absolute';
1292 elem
.style
.backgroundColor
= 'white';
1293 elem
.style
.filter
= 'alpha(opacity=0)';
1294 elem
.style
.width
= this.width_
+ "px";
1295 elem
.style
.height
= this.height_
+ "px";
1296 this.graphDiv
.appendChild(elem
);
1299 return this.canvas_
;
1304 * Generate a set of distinct colors for the data series. This is done with a
1305 * color wheel. Saturation/Value are customizable, and the hue is
1306 * equally-spaced around the color wheel. If a custom set of colors is
1307 * specified, that is used instead.
1310 Dygraph
.prototype.setColors_
= function() {
1311 var labels
= this.getLabels();
1312 var num
= labels
.length
- 1;
1314 this.colorsMap_
= {};
1316 // These are used for when no custom colors are specified.
1317 var sat
= this.getNumericOption('colorSaturation') || 1.0;
1318 var val
= this.getNumericOption('colorValue') || 0.5;
1319 var half
= Math
.ceil(num
/ 2);
1321 var colors
= this.getOption('colors');
1322 var visibility
= this.visibility();
1323 for (var i
= 0; i
< num
; i
++) {
1324 if (!visibility
[i
]) {
1327 var label
= labels
[i
+ 1];
1328 var colorStr
= this.attributes_
.getForSeries('color', label
);
1331 colorStr
= colors
[i
% colors
.length
];
1333 // alternate colors for high contrast.
1334 var idx
= i
% 2 ? (half
+ (i
+ 1)/ 2) : Math.ceil((i + 1) / 2);
1335 var hue
= (1.0 * idx
/ (1 + num
));
1336 colorStr
= Dygraph
.hsvToRGB(hue
, sat
, val
);
1339 this.colors_
.push(colorStr
);
1340 this.colorsMap_
[label
] = colorStr
;
1345 * Return the list of colors. This is either the list of colors passed in the
1346 * attributes or the autogenerated list of rgb(r,g,b) strings.
1347 * This does not return colors for invisible series.
1348 * @return {Array.<string>} The list of colors.
1350 Dygraph
.prototype.getColors
= function() {
1351 return this.colors_
;
1355 * Returns a few attributes of a series, i.e. its color, its visibility, which
1356 * axis it's assigned to, and its column in the original data.
1357 * Returns null if the series does not exist.
1358 * Otherwise, returns an object with column, visibility, color and axis properties.
1359 * The "axis" property will be set to 1 for y1 and 2 for y2.
1360 * The "column" property can be fed back into getValue(row, column) to get
1361 * values for this series.
1363 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1365 var labels
= this.getLabels();
1366 for (var i
= 1; i
< labels
.length
; i
++) {
1367 if (labels
[i
] == series_name
) {
1372 if (idx
== -1) return null;
1377 visible
: this.visibility()[idx
- 1],
1378 color
: this.colorsMap_
[series_name
],
1379 axis
: 1 + this.attributes_
.axisForSeries(series_name
)
1384 * Create the text box to adjust the averaging period
1387 Dygraph
.prototype.createRollInterface_
= function() {
1388 // Create a roller if one doesn't exist already.
1389 if (!this.roller_
) {
1390 this.roller_
= document
.createElement("input");
1391 this.roller_
.type
= "text";
1392 this.roller_
.style
.display
= "none";
1393 this.graphDiv
.appendChild(this.roller_
);
1396 var display
= this.getBooleanOption('showRoller') ? 'block' : 'none';
1398 var area
= this.plotter_
.area
;
1399 var textAttr
= { "position": "absolute",
1401 "top": (area
.y
+ area
.h
- 25) + "px",
1402 "left": (area
.x
+ 1) + "px",
1405 this.roller_
.size
= "2";
1406 this.roller_
.value
= this.rollPeriod_
;
1407 for (var name
in textAttr
) {
1408 if (textAttr
.hasOwnProperty(name
)) {
1409 this.roller_
.style
[name
] = textAttr
[name
];
1414 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1418 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1422 Dygraph
.prototype.createDragInterface_
= function() {
1424 // Tracks whether the mouse is down right now
1426 isPanning
: false, // is this drag part of a pan?
1427 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1428 dragStartX
: null, // pixel coordinates
1429 dragStartY
: null, // pixel coordinates
1430 dragEndX
: null, // pixel coordinates
1431 dragEndY
: null, // pixel coordinates
1432 dragDirection
: null,
1433 prevEndX
: null, // pixel coordinates
1434 prevEndY
: null, // pixel coordinates
1435 prevDragDirection
: null,
1436 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1438 // The value on the left side of the graph when a pan operation starts.
1439 initialLeftmostDate
: null,
1441 // The number of units each pixel spans. (This won't be valid for log
1443 xUnitsPerPixel
: null,
1445 // TODO(danvk): update this comment
1446 // The range in second/value units that the viewport encompasses during a
1447 // panning operation.
1450 // Top-left corner of the canvas, in DOM coords
1451 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1455 // Values for use with panEdgeFraction, which limit how far outside the
1456 // graph's data boundaries it can be panned.
1457 boundedDates
: null, // [minDate, maxDate]
1458 boundedValues
: null, // [[minValue, maxValue] ...]
1460 // We cover iframes during mouse interactions. See comments in
1461 // dygraph-utils.js for more info on why this is a good idea.
1462 tarp
: new Dygraph
.IFrameTarp(),
1464 // contextB is the same thing as this context object but renamed.
1465 initializeMouseDown
: function(event
, g
, contextB
) {
1466 // prevents mouse drags from selecting page text.
1467 if (event
.preventDefault
) {
1468 event
.preventDefault(); // Firefox, Chrome, etc.
1470 event
.returnValue
= false; // IE
1471 event
.cancelBubble
= true;
1474 var canvasPos
= Dygraph
.findPos(g
.canvas_
);
1475 contextB
.px
= canvasPos
.x
;
1476 contextB
.py
= canvasPos
.y
;
1477 contextB
.dragStartX
= Dygraph
.dragGetX_(event
, contextB
);
1478 contextB
.dragStartY
= Dygraph
.dragGetY_(event
, contextB
);
1479 contextB
.cancelNextDblclick
= false;
1480 contextB
.tarp
.cover();
1484 var interactionModel
= this.getOption("interactionModel");
1486 // Self is the graph.
1489 // Function that binds the graph and context to the handler.
1490 var bindHandler
= function(handler
) {
1491 return function(event
) {
1492 handler(event
, self
, context
);
1496 for (var eventName
in interactionModel
) {
1497 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1498 this.addAndTrackEvent(this.mouseEventElement_
, eventName
,
1499 bindHandler(interactionModel
[eventName
]));
1502 // If the user releases the mouse button during a drag, but not over the
1503 // canvas, then it doesn't count as a zooming action.
1504 var mouseUpHandler
= function(event
) {
1505 if (context
.isZooming
|| context
.isPanning
) {
1506 context
.isZooming
= false;
1507 context
.dragStartX
= null;
1508 context
.dragStartY
= null;
1511 if (context
.isPanning
) {
1512 context
.isPanning
= false;
1513 context
.draggingDate
= null;
1514 context
.dateRange
= null;
1515 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1516 delete self
.axes_
[i
].draggingValue
;
1517 delete self
.axes_
[i
].dragValueRange
;
1521 context
.tarp
.uncover();
1524 this.addAndTrackEvent(document
, 'mouseup', mouseUpHandler
);
1528 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1529 * up any previous zoom rectangles that were drawn. This could be optimized to
1530 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1533 * @param {number} direction the direction of the zoom rectangle. Acceptable
1534 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1535 * @param {number} startX The X position where the drag started, in canvas
1537 * @param {number} endX The current X position of the drag, in canvas coords.
1538 * @param {number} startY The Y position where the drag started, in canvas
1540 * @param {number} endY The current Y position of the drag, in canvas coords.
1541 * @param {number} prevDirection the value of direction on the previous call to
1542 * this function. Used to avoid excess redrawing
1543 * @param {number} prevEndX The value of endX on the previous call to this
1544 * function. Used to avoid excess redrawing
1545 * @param {number} prevEndY The value of endY on the previous call to this
1546 * function. Used to avoid excess redrawing
1549 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1550 endY
, prevDirection
, prevEndX
,
1552 var ctx
= this.canvas_ctx_
;
1554 // Clean up from the previous rect if necessary
1555 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1556 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1557 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1558 } else if (prevDirection
== Dygraph
.VERTICAL
) {
1559 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1560 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1563 // Draw a light-grey rectangle to show the new viewing area
1564 if (direction
== Dygraph
.HORIZONTAL
) {
1565 if (endX
&& startX
) {
1566 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1567 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1568 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1570 } else if (direction
== Dygraph
.VERTICAL
) {
1571 if (endY
&& startY
) {
1572 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1573 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1574 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1578 if (this.isUsingExcanvas_
) {
1579 this.currentZoomRectArgs_
= [direction
, startX
, endX
, startY
, endY
, 0, 0, 0];
1584 * Clear the zoom rectangle (and perform no zoom).
1587 Dygraph
.prototype.clearZoomRect_
= function() {
1588 this.currentZoomRectArgs_
= null;
1589 this.canvas_ctx_
.clearRect(0, 0, this.canvas_
.width
, this.canvas_
.height
);
1593 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1594 * the canvas. The exact zoom window may be slightly larger if there are no data
1595 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1596 * which accepts dates that match the raw data. This function redraws the graph.
1598 * @param {number} lowX The leftmost pixel value that should be visible.
1599 * @param {number} highX The rightmost pixel value that should be visible.
1602 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1603 this.currentZoomRectArgs_
= null;
1604 // Find the earliest and latest dates contained in this canvasx range.
1605 // Convert the call to date ranges of the raw data.
1606 var minDate
= this.toDataXCoord(lowX
);
1607 var maxDate
= this.toDataXCoord(highX
);
1608 this.doZoomXDates_(minDate
, maxDate
);
1612 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1613 * method with doZoomX which accepts pixel coordinates. This function redraws
1616 * @param {number} minDate The minimum date that should be visible.
1617 * @param {number} maxDate The maximum date that should be visible.
1620 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1621 // TODO(danvk): when xAxisRange is null (i.e. "fit to data", the animation
1622 // can produce strange effects. Rather than the x-axis transitioning slowly
1623 // between values, it can jerk around.)
1624 var old_window
= this.xAxisRange();
1625 var new_window
= [minDate
, maxDate
];
1626 this.zoomed_x_
= true;
1628 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1629 if (that
.getFunctionOption("zoomCallback")) {
1630 that
.getFunctionOption("zoomCallback")(
1631 minDate
, maxDate
, that
.yAxisRanges());
1637 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1638 * the canvas. This function redraws the graph.
1640 * @param {number} lowY The topmost pixel value that should be visible.
1641 * @param {number} highY The lowest pixel value that should be visible.
1644 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1645 this.currentZoomRectArgs_
= null;
1646 // Find the highest and lowest values in pixel range for each axis.
1647 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1648 // This is because pixels increase as you go down on the screen, whereas data
1649 // coordinates increase as you go up the screen.
1650 var oldValueRanges
= this.yAxisRanges();
1651 var newValueRanges
= [];
1652 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1653 var hi
= this.toDataYCoord(lowY
, i
);
1654 var low
= this.toDataYCoord(highY
, i
);
1655 newValueRanges
.push([low
, hi
]);
1658 this.zoomed_y_
= true;
1660 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1661 if (that
.getFunctionOption("zoomCallback")) {
1662 var xRange
= that
.xAxisRange();
1663 that
.getFunctionOption("zoomCallback")(
1664 xRange
[0], xRange
[1], that
.yAxisRanges());
1670 * Transition function to use in animations. Returns values between 0.0
1671 * (totally old values) and 1.0 (totally new values) for each frame.
1674 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1676 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1680 * Reset the zoom to the original view coordinates. This is the same as
1681 * double-clicking on the graph.
1683 Dygraph
.prototype.resetZoom
= function() {
1684 var dirty
= false, dirtyX
= false, dirtyY
= false;
1685 if (this.dateWindow_
!== null) {
1690 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1691 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1697 // Clear any selection, since it's likely to be drawn in the wrong place.
1698 this.clearSelection();
1701 this.zoomed_x_
= false;
1702 this.zoomed_y_
= false;
1704 var minDate
= this.rawData_
[0][0];
1705 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1707 // With only one frame, don't bother calculating extreme ranges.
1708 // TODO(danvk): merge this block w/ the code below
.
1709 if (!this.getBooleanOption("animatedZooms")) {
1710 this.dateWindow_
= null;
1711 for (i
= 0; i
< this.axes_
.length
; i
++) {
1712 if (this.axes_
[i
].valueWindow
!== null) {
1713 delete this.axes_
[i
].valueWindow
;
1717 if (this.getFunctionOption("zoomCallback")) {
1718 this.getFunctionOption("zoomCallback")(
1719 minDate
, maxDate
, this.yAxisRanges());
1724 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1726 oldWindow
= this.xAxisRange();
1727 newWindow
= [minDate
, maxDate
];
1731 oldValueRanges
= this.yAxisRanges();
1732 // TODO(danvk): this is pretty inefficient
1733 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1734 var extremes
= packed
.extremes
;
1736 // this has the side-effect of modifying this.axes_.
1737 // this doesn't make much sense in this context, but it's convenient (we
1738 // need this.axes_[*].extremeValues) and not harmful since we'll be
1739 // calling drawGraph_ shortly, which clobbers these values.
1740 this.computeYAxisRanges_(extremes
);
1742 newValueRanges
= [];
1743 for (i
= 0; i
< this.axes_
.length
; i
++) {
1744 var axis
= this.axes_
[i
];
1745 newValueRanges
.push((axis
.valueRange
!== null &&
1746 axis
.valueRange
!== undefined
) ?
1747 axis
.valueRange
: axis
.extremeRange
);
1752 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1754 that
.dateWindow_
= null;
1755 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1756 if (that
.axes_
[i
].valueWindow
!== null) {
1757 delete that
.axes_
[i
].valueWindow
;
1760 if (that
.getFunctionOption("zoomCallback")) {
1761 that
.getFunctionOption("zoomCallback")(
1762 minDate
, maxDate
, that
.yAxisRanges());
1769 * Combined animation logic for all zoom functions.
1770 * either the x parameters or y parameters may be null.
1773 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1774 var steps
= this.getBooleanOption("animatedZooms") ?
1775 Dygraph
.ANIMATION_STEPS
: 1;
1778 var valueRanges
= [];
1781 if (oldXRange
!== null && newXRange
!== null) {
1782 for (step
= 1; step
<= steps
; step
++) {
1783 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1784 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1785 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1789 if (oldYRanges
!== null && newYRanges
!== null) {
1790 for (step
= 1; step
<= steps
; step
++) {
1791 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1793 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1794 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1795 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1797 valueRanges
[step
-1] = thisRange
;
1802 Dygraph
.repeatAndCleanup(function(step
) {
1803 if (valueRanges
.length
) {
1804 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1805 var w
= valueRanges
[step
][i
];
1806 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1809 if (windows
.length
) {
1810 that
.dateWindow_
= windows
[step
];
1813 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1817 * Get the current graph's area object.
1819 * Returns: {x, y, w, h}
1821 Dygraph
.prototype.getArea
= function() {
1822 return this.plotter_
.area
;
1826 * Convert a mouse event to DOM coordinates relative to the graph origin.
1828 * Returns a two-element array: [X, Y].
1830 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1831 if (event
.offsetX
&& event
.offsetY
) {
1832 return [ event
.offsetX
, event
.offsetY
];
1834 var eventElementPos
= Dygraph
.findPos(this.mouseEventElement_
);
1835 var canvasx
= Dygraph
.pageX(event
) - eventElementPos
.x
;
1836 var canvasy
= Dygraph
.pageY(event
) - eventElementPos
.y
;
1837 return [canvasx
, canvasy
];
1842 * Given a canvas X coordinate, find the closest row.
1843 * @param {number} domX graph-relative DOM X coordinate
1844 * Returns {number} row number.
1847 Dygraph
.prototype.findClosestRow
= function(domX
) {
1848 var minDistX
= Infinity
;
1849 var closestRow
= -1;
1850 var sets
= this.layout_
.points
;
1851 for (var i
= 0; i
< sets
.length
; i
++) {
1852 var points
= sets
[i
];
1853 var len
= points
.length
;
1854 for (var j
= 0; j
< len
; j
++) {
1855 var point
= points
[j
];
1856 if (!Dygraph
.isValidPoint(point
, true)) continue;
1857 var dist
= Math
.abs(point
.canvasx
- domX
);
1858 if (dist
< minDistX
) {
1860 closestRow
= point
.idx
;
1869 * Given canvas X,Y coordinates, find the closest point.
1871 * This finds the individual data point across all visible series
1872 * that's closest to the supplied DOM coordinates using the standard
1873 * Euclidean X,Y distance.
1875 * @param {number} domX graph-relative DOM X coordinate
1876 * @param {number} domY graph-relative DOM Y coordinate
1877 * Returns: {row, seriesName, point}
1880 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1881 var minDist
= Infinity
;
1882 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
, closestRow
;
1883 for ( var setIdx
= this.layout_
.points
.length
- 1 ; setIdx
>= 0 ; --setIdx
) {
1884 var points
= this.layout_
.points
[setIdx
];
1885 for (var i
= 0; i
< points
.length
; ++i
) {
1887 if (!Dygraph
.isValidPoint(point
)) continue;
1888 dx
= point
.canvasx
- domX
;
1889 dy
= point
.canvasy
- domY
;
1890 dist
= dx
* dx
+ dy
* dy
;
1891 if (dist
< minDist
) {
1893 closestPoint
= point
;
1894 closestSeries
= setIdx
;
1895 closestRow
= point
.idx
;
1899 var name
= this.layout_
.setNames
[closestSeries
];
1908 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1910 * This first finds the X data point closest to the supplied DOM X coordinate,
1911 * then finds the series which puts the Y coordinate on top of its filled area,
1912 * using linear interpolation between adjacent point pairs.
1914 * @param {number} domX graph-relative DOM X coordinate
1915 * @param {number} domY graph-relative DOM Y coordinate
1916 * Returns: {row, seriesName, point}
1919 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1920 var row
= this.findClosestRow(domX
);
1921 var closestPoint
, closestSeries
;
1922 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
1923 var boundary
= this.getLeftBoundary_(setIdx
);
1924 var rowIdx
= row
- boundary
;
1925 var points
= this.layout_
.points
[setIdx
];
1926 if (rowIdx
>= points
.length
) continue;
1927 var p1
= points
[rowIdx
];
1928 if (!Dygraph
.isValidPoint(p1
)) continue;
1929 var py
= p1
.canvasy
;
1930 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < points
.length
) {
1931 // interpolate series Y value using next point
1932 var p2
= points
[rowIdx
+ 1];
1933 if (Dygraph
.isValidPoint(p2
)) {
1934 var dx
= p2
.canvasx
- p1
.canvasx
;
1936 var r
= (domX
- p1
.canvasx
) / dx
;
1937 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1940 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1941 // interpolate series Y value using previous point
1942 var p0
= points
[rowIdx
- 1];
1943 if (Dygraph
.isValidPoint(p0
)) {
1944 var dx
= p1
.canvasx
- p0
.canvasx
;
1946 var r
= (p1
.canvasx
- domX
) / dx
;
1947 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1951 // Stop if the point (domX, py) is above this series' upper edge
1952 if (setIdx
=== 0 || py
< domY
) {
1954 closestSeries
= setIdx
;
1957 var name
= this.layout_
.setNames
[closestSeries
];
1966 * When the mouse moves in the canvas, display information about a nearby data
1967 * point and draw dots over those points in the data series. This function
1968 * takes care of cleanup of previously-drawn dots.
1969 * @param {Object} event The mousemove event from the browser.
1972 Dygraph
.prototype.mouseMove_
= function(event
) {
1973 // This prevents JS errors when mousing over the canvas before data loads.
1974 var points
= this.layout_
.points
;
1975 if (points
=== undefined
|| points
=== null) return;
1977 var canvasCoords
= this.eventToDomCoords(event
);
1978 var canvasx
= canvasCoords
[0];
1979 var canvasy
= canvasCoords
[1];
1981 var highlightSeriesOpts
= this.getOption("highlightSeriesOpts");
1982 var selectionChanged
= false;
1983 if (highlightSeriesOpts
&& !this.isSeriesLocked()) {
1985 if (this.getBooleanOption("stackedGraph")) {
1986 closest
= this.findStackedPoint(canvasx
, canvasy
);
1988 closest
= this.findClosestPoint(canvasx
, canvasy
);
1990 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1992 var idx
= this.findClosestRow(canvasx
);
1993 selectionChanged
= this.setSelection(idx
);
1996 var callback
= this.getFunctionOption("highlightCallback");
1997 if (callback
&& selectionChanged
) {
2002 this.highlightSet_
);
2007 * Fetch left offset from the specified set index or if not passed, the
2008 * first defined boundaryIds record (see bug #236).
2011 Dygraph
.prototype.getLeftBoundary_
= function(setIdx
) {
2012 if (this.boundaryIds_
[setIdx
]) {
2013 return this.boundaryIds_
[setIdx
][0];
2015 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
2016 if (this.boundaryIds_
[i
] !== undefined
) {
2017 return this.boundaryIds_
[i
][0];
2024 Dygraph
.prototype.animateSelection_
= function(direction
) {
2025 var totalSteps
= 10;
2027 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
2028 if (this.animateId
=== undefined
) this.animateId
= 0;
2029 var start
= this.fadeLevel
;
2030 var steps
= direction
< 0 ? start
: totalSteps
- start
;
2032 if (this.fadeLevel
) {
2033 this.updateSelection_(1.0);
2038 var thisId
= ++this.animateId
;
2040 Dygraph
.repeatAndCleanup(
2042 // ignore simultaneous animations
2043 if (that
.animateId
!= thisId
) return;
2045 that
.fadeLevel
+= direction
;
2046 if (that
.fadeLevel
=== 0) {
2047 that
.clearSelection();
2049 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
2052 steps
, millis
, function() {});
2056 * Draw dots over the selectied points in the data series. This function
2057 * takes care of cleanup of previously-drawn dots.
2060 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
2061 /*var defaultPrevented = */
2062 this.cascadeEvents_('select', {
2063 selectedX
: this.lastx_
,
2064 selectedPoints
: this.selPoints_
2066 // TODO(danvk): use defaultPrevented here?
2068 // Clear the previously drawn vertical, if there is one
2070 var ctx
= this.canvas_ctx_
;
2071 if (this.getOption('highlightSeriesOpts')) {
2072 ctx
.clearRect(0, 0, this.width_
, this.height_
);
2073 var alpha
= 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha');
2075 // Activating background fade includes an animation effect for a gradual
2076 // fade. TODO(klausw): make this independently configurable if it causes
2077 // issues? Use a shared preference to control animations?
2078 var animateBackgroundFade
= true;
2079 if (animateBackgroundFade
) {
2080 if (opt_animFraction
=== undefined
) {
2081 // start a new animation
2082 this.animateSelection_(1);
2085 alpha
*= opt_animFraction
;
2087 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
2088 ctx
.fillRect(0, 0, this.width_
, this.height_
);
2091 // Redraw only the highlighted series in the interactive canvas (not the
2092 // static plot canvas, which is where series are usually drawn).
2093 this.plotter_
._renderLineChart(this.highlightSet_
, ctx
);
2094 } else if (this.previousVerticalX_
>= 0) {
2095 // Determine the maximum highlight circle size.
2096 var maxCircleSize
= 0;
2097 var labels
= this.attr_('labels');
2098 for (i
= 1; i
< labels
.length
; i
++) {
2099 var r
= this.getNumericOption('highlightCircleSize', labels
[i
]);
2100 if (r
> maxCircleSize
) maxCircleSize
= r
;
2102 var px
= this.previousVerticalX_
;
2103 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
2104 2 * maxCircleSize
+ 2, this.height_
);
2107 if (this.isUsingExcanvas_
&& this.currentZoomRectArgs_
) {
2108 Dygraph
.prototype.drawZoomRect_
.apply(this, this.currentZoomRectArgs_
);
2111 if (this.selPoints_
.length
> 0) {
2112 // Draw colored circles over the center of each selected point
2113 var canvasx
= this.selPoints_
[0].canvasx
;
2115 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
2116 var pt
= this.selPoints_
[i
];
2117 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
2119 var circleSize
= this.getNumericOption('highlightCircleSize', pt
.name
);
2120 var callback
= this.getFunctionOption("drawHighlightPointCallback", pt
.name
);
2121 var color
= this.plotter_
.colors
[pt
.name
];
2123 callback
= Dygraph
.Circles
.DEFAULT
;
2125 ctx
.lineWidth
= this.getNumericOption('strokeWidth', pt
.name
);
2126 ctx
.strokeStyle
= color
;
2127 ctx
.fillStyle
= color
;
2128 callback(this, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
2129 color
, circleSize
, pt
.idx
);
2133 this.previousVerticalX_
= canvasx
;
2138 * Manually set the selected points and display information about them in the
2139 * legend. The selection can be cleared using clearSelection() and queried
2140 * using getSelection().
2141 * @param {number} row Row number that should be highlighted (i.e. appear with
2142 * hover dots on the chart). Set to false to clear any selection.
2143 * @param {seriesName} optional series name to highlight that series with the
2144 * the highlightSeriesOpts setting.
2145 * @param { locked } optional If true, keep seriesName selected when mousing
2146 * over the graph, disabling closest-series highlighting. Call clearSelection()
2149 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
, opt_locked
) {
2150 // Extract the points we've selected
2151 this.selPoints_
= [];
2153 var changed
= false;
2154 if (row
!== false && row
>= 0) {
2155 if (row
!= this.lastRow_
) changed
= true;
2156 this.lastRow_
= row
;
2157 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
2158 var points
= this.layout_
.points
[setIdx
];
2159 // Check if the point at the appropriate index is the point we're looking
2160 // for. If it is, just use it, otherwise search the array for a point
2161 // in the proper place.
2162 var setRow
= row
- this.getLeftBoundary_(setIdx
);
2163 if (setRow
< points
.length
&& points
[setRow
].idx
== row
) {
2164 var point
= points
[setRow
];
2165 if (point
.yval
!== null) this.selPoints_
.push(point
);
2167 for (var pointIdx
= 0; pointIdx
< points
.length
; ++pointIdx
) {
2168 var point
= points
[pointIdx
];
2169 if (point
.idx
== row
) {
2170 if (point
.yval
!== null) {
2171 this.selPoints_
.push(point
);
2179 if (this.lastRow_
>= 0) changed
= true;
2183 if (this.selPoints_
.length
) {
2184 this.lastx_
= this.selPoints_
[0].xval
;
2189 if (opt_seriesName
!== undefined
) {
2190 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
2191 this.highlightSet_
= opt_seriesName
;
2194 if (opt_locked
!== undefined
) {
2195 this.lockedSet_
= opt_locked
;
2199 this.updateSelection_(undefined
);
2205 * The mouse has left the canvas. Clear out whatever artifacts remain
2206 * @param {Object} event the mouseout event from the browser.
2209 Dygraph
.prototype.mouseOut_
= function(event
) {
2210 if (this.getFunctionOption("unhighlightCallback")) {
2211 this.getFunctionOption("unhighlightCallback")(event
);
2214 if (this.getFunctionOption("hideOverlayOnMouseOut") && !this.lockedSet_
) {
2215 this.clearSelection();
2220 * Clears the current selection (i.e. points that were highlighted by moving
2221 * the mouse over the chart).
2223 Dygraph
.prototype.clearSelection
= function() {
2224 this.cascadeEvents_('deselect', {});
2226 this.lockedSet_
= false;
2227 // Get rid of the overlay data
2228 if (this.fadeLevel
) {
2229 this.animateSelection_(-1);
2232 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
2234 this.selPoints_
= [];
2237 this.highlightSet_
= null;
2241 * Returns the number of the currently selected row. To get data for this row,
2242 * you can use the getValue method.
2243 * @return {number} row number, or -1 if nothing is selected
2245 Dygraph
.prototype.getSelection
= function() {
2246 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
2250 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; setIdx
++) {
2251 var points
= this.layout_
.points
[setIdx
];
2252 for (var row
= 0; row
< points
.length
; row
++) {
2253 if (points
[row
].x
== this.selPoints_
[0].x
) {
2254 return points
[row
].idx
;
2262 * Returns the name of the currently-highlighted series.
2263 * Only available when the highlightSeriesOpts option is in use.
2265 Dygraph
.prototype.getHighlightSeries
= function() {
2266 return this.highlightSet_
;
2270 * Returns true if the currently-highlighted series was locked
2271 * via setSelection(..., seriesName, true).
2273 Dygraph
.prototype.isSeriesLocked
= function() {
2274 return this.lockedSet_
;
2278 * Fires when there's data available to be graphed.
2279 * @param {string} data Raw CSV data to be plotted
2282 Dygraph
.prototype.loadedEvent_
= function(data
) {
2283 this.rawData_
= this.parseCSV_(data
);
2288 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2291 Dygraph
.prototype.addXTicks_
= function() {
2292 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2294 if (this.dateWindow_
) {
2295 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2297 range
= this.xAxisExtremes();
2300 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2301 var xTicks
= xAxisOptionsView('ticker')(
2304 this.width_
, // TODO(danvk): should be area.width
2307 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2308 // console.log(msg);
2309 this.layout_
.setXTicks(xTicks
);
2313 * Returns the correct handler class for the currently set options.
2316 Dygraph
.prototype.getHandlerClass_
= function() {
2318 if (this.attr_('dataHandler')) {
2319 handlerClass
= this.attr_('dataHandler');
2320 } else if (this.fractions_
) {
2321 if (this.getBooleanOption('errorBars')) {
2322 handlerClass
= Dygraph
.DataHandlers
.FractionsBarsHandler
;
2324 handlerClass
= Dygraph
.DataHandlers
.DefaultFractionHandler
;
2326 } else if (this.getBooleanOption('customBars')) {
2327 handlerClass
= Dygraph
.DataHandlers
.CustomBarsHandler
;
2328 } else if (this.getBooleanOption('errorBars')) {
2329 handlerClass
= Dygraph
.DataHandlers
.ErrorBarsHandler
;
2331 handlerClass
= Dygraph
.DataHandlers
.DefaultHandler
;
2333 return handlerClass
;
2338 * This function is called once when the chart's data is changed or the options
2339 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2340 * idea is that values derived from the chart's data can be computed here,
2341 * rather than every time the chart is drawn. This includes things like the
2342 * number of axes, rolling averages, etc.
2344 Dygraph
.prototype.predraw_
= function() {
2345 var start
= new Date();
2347 // Create the correct dataHandler
2348 this.dataHandler_
= new (this.getHandlerClass_())();
2350 this.layout_
.computePlotArea();
2352 // TODO(danvk): move more computations out of drawGraph_ and into here.
2353 this.computeYAxes_();
2355 // Create a new plotter.
2356 if (this.plotter_
) {
2357 this.cascadeEvents_('clearChart');
2358 this.plotter_
.clear();
2361 if (!this.is_initial_draw_
) {
2362 this.canvas_ctx_
.restore();
2363 this.hidden_ctx_
.restore();
2366 this.canvas_ctx_
.save();
2367 this.hidden_ctx_
.save();
2369 this.plotter_
= new DygraphCanvasRenderer(this,
2374 // The roller sits in the bottom left corner of the chart. We don't know where
2375 // this will be until the options are available, so it's positioned here.
2376 this.createRollInterface_();
2378 this.cascadeEvents_('predraw');
2380 // Convert the raw data (a 2D array) into the internal format and compute
2381 // rolling averages.
2382 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2383 for (var i
= 1; i
< this.numColumns(); i
++) {
2384 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too
.
2385 var series
= this.dataHandler_
.extractSeries(this.rawData_
, i
, this.attributes_
);
2386 if (this.rollPeriod_
> 1) {
2387 series
= this.dataHandler_
.rollingAverage(series
, this.rollPeriod_
, this.attributes_
);
2390 this.rolledSeries_
.push(series
);
2393 // If the data or options have changed, then we'd better redraw.
2396 // This is used to determine whether to do various animations.
2397 var end
= new Date();
2398 this.drawingTimeMs_
= (end
- start
);
2404 * xval_* and yval_* are the original unscaled data values,
2405 * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
2406 * yval_stacked is the cumulative Y value used for stacking graphs,
2407 * and bottom/top/minus/plus are used for error bar graphs.
2414 * y_bottom: ?number,
2416 * y_stacked: ?number,
2418 * yval_minus: ?number,
2420 * yval_plus: ?number,
2424 Dygraph
.PointType
= undefined
;
2427 * Calculates point stacking for stackedGraph=true.
2429 * For stacking purposes, interpolate or extend neighboring data across
2430 * NaN values based on stackedGraphNaNFill settings. This is for display
2431 * only, the underlying data value as shown in the legend remains NaN.
2433 * @param {Array.<Dygraph.PointType>} points Point array for a single series.
2434 * Updates each Point's yval_stacked property.
2435 * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
2436 * values for the series seen so far. Index is the row number. Updated
2437 * based on the current series's values.
2438 * @param {Array.<number>} seriesExtremes Min and max values, updated
2439 * to reflect the stacked values.
2440 * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
2444 Dygraph
.stackPoints_
= function(
2445 points
, cumulativeYval
, seriesExtremes
, fillMethod
) {
2446 var lastXval
= null;
2447 var prevPoint
= null;
2448 var nextPoint
= null;
2449 var nextPointIdx
= -1;
2451 // Find the next stackable point starting from the given index.
2452 var updateNextPoint
= function(idx
) {
2453 // If we've previously found a non-NaN point and haven't gone past it yet,
2455 if (nextPointIdx
>= idx
) return;
2457 // We haven't found a non-NaN point yet or have moved past it,
2458 // look towards the right to find a non-NaN point.
2459 for (var j
= idx
; j
< points
.length
; ++j
) {
2460 // Clear out a previously-found point (if any) since it's no longer
2461 // valid, we shouldn't use it for interpolation anymore.
2463 if (!isNaN(points
[j
].yval
) && points
[j
].yval
!== null) {
2465 nextPoint
= points
[j
];
2471 for (var i
= 0; i
< points
.length
; ++i
) {
2472 var point
= points
[i
];
2473 var xval
= point
.xval
;
2474 if (cumulativeYval
[xval
] === undefined
) {
2475 cumulativeYval
[xval
] = 0;
2478 var actualYval
= point
.yval
;
2479 if (isNaN(actualYval
) || actualYval
=== null) {
2480 if(fillMethod
== 'none') {
2483 // Interpolate/extend
for stacking purposes
if possible
.
2485 if (prevPoint
&& nextPoint
&& fillMethod
!= 'none') {
2486 // Use linear interpolation between prevPoint and nextPoint.
2487 actualYval
= prevPoint
.yval
+ (nextPoint
.yval
- prevPoint
.yval
) *
2488 ((xval
- prevPoint
.xval
) / (nextPoint
.xval
- prevPoint
.xval
));
2489 } else if (prevPoint
&& fillMethod
== 'all') {
2490 actualYval
= prevPoint
.yval
;
2491 } else if (nextPoint
&& fillMethod
== 'all') {
2492 actualYval
= nextPoint
.yval
;
2501 var stackedYval
= cumulativeYval
[xval
];
2502 if (lastXval
!= xval
) {
2503 // If an x-value is repeated, we ignore the duplicates.
2504 stackedYval
+= actualYval
;
2505 cumulativeYval
[xval
] = stackedYval
;
2509 point
.yval_stacked
= stackedYval
;
2511 if (stackedYval
> seriesExtremes
[1]) {
2512 seriesExtremes
[1] = stackedYval
;
2514 if (stackedYval
< seriesExtremes
[0]) {
2515 seriesExtremes
[0] = stackedYval
;
2522 * Loop over all fields and create datasets, calculating extreme y-values for
2523 * each series and extreme x-indices as we go.
2525 * dateWindow is passed in as an explicit parameter so that we can compute
2526 * extreme values "speculatively", i.e. without actually setting state on the
2529 * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
2530 * rolledSeries[seriesIndex][row] = raw point, where
2531 * seriesIndex is the column number starting with 1, and
2532 * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
2533 * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
2535 * points: Array.<Array.<Dygraph.PointType>>,
2536 * seriesExtremes: Array.<Array.<number>>,
2537 * boundaryIds: Array.<number>}}
2540 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2541 var boundaryIds
= [];
2543 var cumulativeYval
= []; // For stacked series.
2544 var extremes
= {}; // series name -> [low, high]
2545 var seriesIdx
, sampleIdx
;
2546 var firstIdx
, lastIdx
;
2548 // Loop over the fields (series). Go from the last to the first,
2549 // because if they're stacked that's how we accumulate the values.
2550 var num_series
= rolledSeries
.length
- 1;
2552 for (seriesIdx
= num_series
; seriesIdx
>= 1; seriesIdx
--) {
2553 if (!this.visibility()[seriesIdx
- 1]) continue;
2555 // Prune down to the desired range, if necessary (for zooming)
2556 // Because there can be lines going to points outside of the visible area,
2557 // we actually prune to visible points, plus one on either side.
2559 series
= rolledSeries
[seriesIdx
];
2560 var low
= dateWindow
[0];
2561 var high
= dateWindow
[1];
2563 // TODO(danvk): do binary search instead of linear search.
2564 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2567 for (sampleIdx
= 0; sampleIdx
< series
.length
; sampleIdx
++) {
2568 if (series
[sampleIdx
][0] >= low
&& firstIdx
=== null) {
2569 firstIdx
= sampleIdx
;
2571 if (series
[sampleIdx
][0] <= high
) {
2572 lastIdx
= sampleIdx
;
2576 if (firstIdx
=== null) firstIdx
= 0;
2577 var correctedFirstIdx
= firstIdx
;
2578 var isInvalidValue
= true;
2579 while (isInvalidValue
&& correctedFirstIdx
> 0) {
2580 correctedFirstIdx
--;
2581 // check if the y value is null.
2582 isInvalidValue
= series
[correctedFirstIdx
][1] === null;
2585 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2586 var correctedLastIdx
= lastIdx
;
2587 isInvalidValue
= true;
2588 while (isInvalidValue
&& correctedLastIdx
< series
.length
- 1) {
2590 isInvalidValue
= series
[correctedLastIdx
][1] === null;
2593 if (correctedFirstIdx
!==firstIdx
) {
2594 firstIdx
= correctedFirstIdx
;
2596 if (correctedLastIdx
!== lastIdx
) {
2597 lastIdx
= correctedLastIdx
;
2600 boundaryIds
[seriesIdx
-1] = [firstIdx
, lastIdx
];
2602 // .slice's end is exclusive, we want to include lastIdx.
2603 series
= series
.slice(firstIdx
, lastIdx
+ 1);
2605 series
= rolledSeries
[seriesIdx
];
2606 boundaryIds
[seriesIdx
-1] = [0, series
.length
-1];
2609 var seriesName
= this.attr_("labels")[seriesIdx
];
2610 var seriesExtremes
= this.dataHandler_
.getExtremeYValues(series
,
2611 dateWindow
, this.getBooleanOption("stepPlot",seriesName
));
2613 var seriesPoints
= this.dataHandler_
.seriesToPoints(series
,
2614 seriesName
, boundaryIds
[seriesIdx
-1][0]);
2616 if (this.getBooleanOption("stackedGraph")) {
2617 Dygraph
.stackPoints_(seriesPoints
, cumulativeYval
, seriesExtremes
,
2618 this.getBooleanOption("stackedGraphNaNFill"));
2621 extremes
[seriesName
] = seriesExtremes
;
2622 points
[seriesIdx
] = seriesPoints
;
2625 return { points
: points
, extremes
: extremes
, boundaryIds
: boundaryIds
};
2629 * Update the graph with new data. This method is called when the viewing area
2630 * has changed. If the underlying data or options have changed, predraw_ will
2631 * be called before drawGraph_ is called.
2635 Dygraph
.prototype.drawGraph_
= function() {
2636 var start
= new Date();
2638 // This is used to set the second parameter to drawCallback, below.
2639 var is_initial_draw
= this.is_initial_draw_
;
2640 this.is_initial_draw_
= false;
2642 this.layout_
.removeAllDatasets();
2644 this.attrs_
.pointSize
= 0.5 * this.getNumericOption('highlightCircleSize');
2646 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2647 var points
= packed
.points
;
2648 var extremes
= packed
.extremes
;
2649 this.boundaryIds_
= packed
.boundaryIds
;
2651 this.setIndexByName_
= {};
2652 var labels
= this.attr_("labels");
2653 if (labels
.length
> 0) {
2654 this.setIndexByName_
[labels
[0]] = 0;
2657 for (var i
= 1; i
< points
.length
; i
++) {
2658 this.setIndexByName_
[labels
[i
]] = i
;
2659 if (!this.visibility()[i
- 1]) continue;
2660 this.layout_
.addDataset(labels
[i
], points
[i
]);
2661 this.datasetIndex_
[i
] = dataIdx
++;
2664 this.computeYAxisRanges_(extremes
);
2665 this.layout_
.setYAxes(this.axes_
);
2669 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2670 var tmp_zoomed_x
= this.zoomed_x_
;
2671 // Tell PlotKit to use this new data and render itself
2672 this.zoomed_x_
= tmp_zoomed_x
;
2673 this.layout_
.evaluate();
2674 this.renderGraph_(is_initial_draw
);
2676 if (this.getStringOption("timingName")) {
2677 var end
= new Date();
2678 Dygraph
.info(this.getStringOption("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2683 * This does the work of drawing the chart. It assumes that the layout and axis
2684 * scales have already been set (e.g. by predraw_).
2688 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2689 this.cascadeEvents_('clearChart');
2690 this.plotter_
.clear();
2692 if (this.getFunctionOption('underlayCallback')) {
2693 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2694 // users who expect a deprecated form of this callback.
2695 this.getFunctionOption('underlayCallback')(
2696 this.hidden_ctx_
, this.layout_
.getPlotArea(), this, this);
2700 canvas
: this.hidden_
,
2701 drawingContext
: this.hidden_ctx_
2703 this.cascadeEvents_('willDrawChart', e
);
2704 this.plotter_
.render();
2705 this.cascadeEvents_('didDrawChart', e
);
2706 this.lastRow_
= -1; // because plugins/legend.js clears the legend
2708 // TODO(danvk): is this a performance bottleneck when panning?
2709 // The interaction canvas should already be empty in that situation.
2710 this.canvas_
.getContext('2d').clearRect(0, 0, this.canvas_
.width
,
2711 this.canvas_
.height
);
2713 if (this.getFunctionOption("drawCallback") !== null) {
2714 this.getFunctionOption("drawCallback")(this, is_initial_draw
);
2716 if (is_initial_draw
) {
2717 this.readyFired_
= true;
2718 while (this.readyFns_
.length
> 0) {
2719 var fn
= this.readyFns_
.pop();
2727 * Determine properties of the y-axes which are independent of the data
2728 * currently being displayed. This includes things like the number of axes and
2729 * the style of the axes. It does not include the range of each axis and its
2731 * This fills in this.axes_.
2732 * axes_ = [ { options } ]
2733 * indices are into the axes_ array.
2735 Dygraph
.prototype.computeYAxes_
= function() {
2736 // Preserve valueWindow settings if they exist, and if the user hasn't
2737 // specified a new valueRange.
2738 var valueWindows
, axis
, index
, opts
, v
;
2739 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2741 for (index
= 0; index
< this.axes_
.length
; index
++) {
2742 valueWindows
.push(this.axes_
[index
].valueWindow
);
2746 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2747 // data computation as well as options storage.
2748 // Go through once and add all the axes.
2751 for (axis
= 0; axis
< this.attributes_
.numAxes(); axis
++) {
2752 // Add a new axis, making a copy of its per-axis options.
2753 opts
= { g
: this };
2754 Dygraph
.update(opts
, this.attributes_
.axisOptions(axis
));
2755 this.axes_
[axis
] = opts
;
2759 // Copy global valueRange option over to the first axis.
2760 // NOTE(konigsberg): Are these two statements necessary?
2761 // I tried removing it. The automated tests pass, and manually
2762 // messing with tests/zoom
.html showed no trouble
.
2763 v
= this.attr_('valueRange');
2764 if (v
) this.axes_
[0].valueRange
= v
;
2766 if (valueWindows
!== undefined
) {
2767 // Restore valueWindow settings.
2769 // When going from two axes back to one, we only restore
2771 var idxCount
= Math
.min(valueWindows
.length
, this.axes_
.length
);
2773 for (index
= 0; index
< idxCount
; index
++) {
2774 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2778 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2780 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2781 v
= opts("valueRange");
2782 if (v
) this.axes_
[axis
].valueRange
= v
;
2783 } else { // To keep old behavior
2784 var axes
= this.user_attrs_
.axes
;
2785 if (axes
&& axes
.y2
) {
2786 v
= axes
.y2
.valueRange
;
2787 if (v
) this.axes_
[axis
].valueRange
= v
;
2794 * Returns the number of y-axes on the chart.
2795 * @return {number} the number of axes.
2797 Dygraph
.prototype.numAxes
= function() {
2798 return this.attributes_
.numAxes();
2803 * Returns axis properties for the given series.
2804 * @param {string} setName The name of the series for which to get axis
2805 * properties, e.g. 'Y1'.
2806 * @return {Object} The axis properties.
2808 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2809 // TODO(danvk): handle errors.
2810 return this.axes_
[this.attributes_
.axisForSeries(series
)];
2815 * Determine the value range and tick marks for each axis.
2816 * @param {Object} extremes A mapping from seriesName -> [low, high]
2817 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2819 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2820 var isNullUndefinedOrNaN
= function(num
) {
2821 return isNaN(parseFloat(num
));
2823 var numAxes
= this.attributes_
.numAxes();
2824 var ypadCompat
, span
, series
, ypad
;
2828 // Compute extreme values, a span and tick marks for each axis.
2829 for (var i
= 0; i
< numAxes
; i
++) {
2830 var axis
= this.axes_
[i
];
2831 var logscale
= this.attributes_
.getForAxis("logscale", i
);
2832 var includeZero
= this.attributes_
.getForAxis("includeZero", i
);
2833 var independentTicks
= this.attributes_
.getForAxis("independentTicks", i
);
2834 series
= this.attributes_
.seriesForAxis(i
);
2836 // Add some padding. This supports two Y padding operation modes:
2838 // - backwards compatible (yRangePad not set):
2839 // 10% padding for automatic Y ranges, but not for user-supplied
2840 // ranges, and move a close-to-zero edge to zero except if
2841 // avoidMinZero is set, since drawing at the edge results in
2842 // invisible lines. Unfortunately lines drawn at the edge of a
2843 // user-supplied range will still be invisible. If logscale is
2844 // set, add a variable amount of padding at the top but
2845 // none at the bottom.
2847 // - new-style (yRangePad set by the user):
2848 // always add the specified Y padding.
2851 ypad
= 0.1; // add 10%
2852 if (this.getNumericOption('yRangePad') !== null) {
2854 // Convert pixel padding to ratio
2855 ypad
= this.getNumericOption('yRangePad') / this.plotter_
.area
.h
;
2858 if (series
.length
=== 0) {
2859 // If no series are defined or visible then use a reasonable default
2860 axis
.extremeRange
= [0, 1];
2862 // Calculate the extremes of extremes.
2863 var minY
= Infinity
; // extremes[series[0]][0];
2864 var maxY
= -Infinity
; // extremes[series[0]][1];
2865 var extremeMinY
, extremeMaxY
;
2867 for (var j
= 0; j
< series
.length
; j
++) {
2868 // this skips invisible series
2869 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2871 // Only use valid extremes to stop null data series' from corrupting the scale.
2872 extremeMinY
= extremes
[series
[j
]][0];
2873 if (extremeMinY
!== null) {
2874 minY
= Math
.min(extremeMinY
, minY
);
2876 extremeMaxY
= extremes
[series
[j
]][1];
2877 if (extremeMaxY
!== null) {
2878 maxY
= Math
.max(extremeMaxY
, maxY
);
2882 // Include zero if requested by the user.
2883 if (includeZero
&& !logscale
) {
2884 if (minY
> 0) minY
= 0;
2885 if (maxY
< 0) maxY
= 0;
2888 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2889 if (minY
== Infinity
) minY
= 0;
2890 if (maxY
== -Infinity
) maxY
= 1;
2893 // special case: if we have no sense of scale, center on the sole value.
2896 span
= Math
.abs(maxY
);
2898 // ... and if the sole value is zero, use range 0-1.
2904 var maxAxisY
, minAxisY
;
2907 maxAxisY
= maxY
+ ypad
* span
;
2910 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2911 maxAxisY
= maxY
* logpad
;
2912 minAxisY
= minY
/ logpad
;
2915 maxAxisY
= maxY
+ ypad
* span
;
2916 minAxisY
= minY
- ypad
* span
;
2918 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2919 // close to zero, but not if avoidMinZero is set.
2920 if (ypadCompat
&& !this.getBooleanOption("avoidMinZero")) {
2921 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2922 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2925 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2927 if (axis
.valueWindow
) {
2928 // This is only set if the user has zoomed on the y-axis. It is never set
2929 // by a user. It takes precedence over axis.valueRange because, if you set
2930 // valueRange, you'd still expect to be able to pan.
2931 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2932 } else if (axis
.valueRange
) {
2933 // This is a user-set value range for this axis.
2934 var y0
= isNullUndefinedOrNaN(axis
.valueRange
[0]) ? axis
.extremeRange
[0] : axis
.valueRange
[0];
2935 var y1
= isNullUndefinedOrNaN(axis
.valueRange
[1]) ? axis
.extremeRange
[1] : axis
.valueRange
[1];
2937 if (axis
.logscale
) {
2938 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2947 axis
.computedValueRange
= [y0
, y1
];
2949 axis
.computedValueRange
= axis
.extremeRange
;
2953 if (independentTicks
) {
2954 axis
.independentTicks
= independentTicks
;
2955 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2956 var ticker
= opts('ticker');
2957 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2958 axis
.computedValueRange
[1],
2959 this.height_
, // TODO(danvk): should be area.height
2962 // Define the first independent axis as primary axis.
2963 if (!p_axis
) p_axis
= axis
;
2966 if (p_axis
=== undefined
) {
2967 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
2969 // Add ticks. By default, all axes inherit the tick positions of the
2970 // primary axis. However, if an axis is specifically marked as having
2971 // independent ticks, then that is permissible as well.
2972 for (var i
= 0; i
< numAxes
; i
++) {
2973 var axis
= this.axes_
[i
];
2975 if (!axis
.independentTicks
) {
2976 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2977 var ticker
= opts('ticker');
2978 var p_ticks
= p_axis
.ticks
;
2979 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2980 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2981 var tick_values
= [];
2982 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2983 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2984 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2985 tick_values
.push(y_val
);
2988 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2989 axis
.computedValueRange
[1],
2990 this.height_
, // TODO(danvk): should be area.height
2999 * Detects the type of the str (date or numeric) and sets the various
3000 * formatting attributes in this.attrs_ based on this type.
3001 * @param {string} str An x value.
3004 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
3006 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
3007 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
3008 str
.indexOf('/') >= 0 ||
3009 isNaN(parseFloat(str
))) {
3011 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
3012 // TODO(danvk): remove support for this format.
3016 this.setXAxisOptions_(isDate
);
3019 Dygraph
.prototype.setXAxisOptions_
= function(isDate
) {
3021 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3022 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateValueFormatter
;
3023 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3024 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisLabelFormatter
;
3026 /** @private (shut up, jsdoc!) */
3027 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3028 // TODO(danvk): use Dygraph.numberValueFormatter here?
3029 /** @private (shut up, jsdoc!) */
3030 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3031 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
3032 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3038 * Parses a string in a special csv format. We expect a csv file where each
3039 * line is a date point, and the first field in each line is the date string.
3040 * We also expect that all remaining fields represent series.
3041 * if the errorBars attribute is set, then interpret the fields as:
3042 * date, series1, stddev1, series2, stddev2, ...
3043 * @param {[Object]} data See above.
3045 * @return [Object] An array with one entry for each row. These entries
3046 * are an array of cells in that row. The first entry is the parsed x-value for
3047 * the row. The second, third, etc. are the y-values. These can take on one of
3048 * three forms, depending on the CSV and constructor parameters:
3050 * 2. [ value, stddev ]
3051 * 3. [ low value, center value, high value ]
3053 Dygraph
.prototype.parseCSV_
= function(data
) {
3055 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3056 var lines
= data
.split(line_delimiter
|| "\n");
3059 // Use the default delimiter or fall back to a tab if that makes sense.
3060 var delim
= this.getStringOption('delimiter');
3061 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
3066 if (!('labels' in this.user_attrs_
)) {
3067 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3069 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
3070 this.attributes_
.reparseSeries();
3075 var defaultParserSet
= false; // attempt to auto-detect x value type
3076 var expectedCols
= this.attr_("labels").length
;
3077 var outOfOrder
= false;
3078 for (var i
= start
; i
< lines
.length
; i
++) {
3079 var line
= lines
[i
];
3081 if (line
.length
=== 0) continue; // skip blank lines
3082 if (line
[0] == '#') continue; // skip comment lines
3083 var inFields
= line
.split(delim
);
3084 if (inFields
.length
< 2) continue;
3087 if (!defaultParserSet
) {
3088 this.detectTypeFromString_(inFields
[0]);
3089 xParser
= this.getFunctionOption("xValueParser");
3090 defaultParserSet
= true;
3092 fields
[0] = xParser(inFields
[0], this);
3094 // If fractions are expected, parse the numbers as "A/B
"
3095 if (this.fractions_) {
3096 for (j = 1; j < inFields.length; j++) {
3097 // TODO(danvk): figure out an appropriate way to flag parse errors.
3098 vals = inFields[j].split("/");
3099 if (vals.length != 2) {
3100 Dygraph.error('Expected fractional "num
/den
" values in CSV data ' +
3101 "but found a value
'" + inFields[j] + "' on line
" +
3102 (1 + i) + " ('" + line + "') which is not of
this form
.");
3105 fields[j] = [Dygraph.parseFloat_(vals[0], i, line),
3106 Dygraph.parseFloat_(vals[1], i, line)];
3109 } else if (this.getBooleanOption("errorBars
")) {
3110 // If there are error bars, values are (value, stddev) pairs
3111 if (inFields.length % 2 != 1) {
3112 Dygraph.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3113 'but line ' + (1 + i) + ' has an odd number of values (' +
3114 (inFields.length - 1) + "): '" + line + "'");
3116 for (j = 1; j < inFields.length; j += 2) {
3117 fields[(j + 1) / 2] = [Dygraph.parseFloat_(inFields[j], i, line),
3118 Dygraph.parseFloat_(inFields[j + 1], i, line)];
3120 } else if (this.getBooleanOption("customBars
")) {
3121 // Bars are a low;center;high tuple
3122 for (j = 1; j < inFields.length; j++) {
3123 var val = inFields[j];
3124 if (/^ *$/.test(val)) {
3125 fields[j] = [null, null, null];
3127 vals = val.split(";");
3128 if (vals.length == 3) {
3129 fields[j] = [ Dygraph.parseFloat_(vals[0], i, line),
3130 Dygraph.parseFloat_(vals[1], i, line),
3131 Dygraph.parseFloat_(vals[2], i, line) ];
3133 Dygraph.warn('When using customBars, values must be either blank ' +
3134 'or "low
;center
;high
" tuples (got "' + val +
3135 '" on line ' + (1+i));
3140 // Values are just numbers
3141 for (j = 1; j < inFields.length; j++) {
3142 fields[j] = Dygraph.parseFloat_(inFields[j], i, line);
3145 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3149 if (fields.length != expectedCols) {
3150 Dygraph.error("Number of columns
in line
" + i + " (" + fields.length +
3151 ") does not agree
with number of
labels (" + expectedCols +
3155 // If the user specified the 'labels' option and none of the cells of the
3156 // first row parsed correctly, then they probably double-specified the
3157 // labels. We go with the values set in the option, discard this row and
3158 // log a warning to the JS console.
3159 if (i === 0 && this.attr_('labels')) {
3160 var all_null = true;
3161 for (j = 0; all_null && j < fields.length; j++) {
3162 if (fields[j]) all_null = false;
3165 Dygraph.warn("The dygraphs
'labels' option is set
, but the first row
" +
3166 "of CSV
data ('" + line + "') appears to also contain
" +
3167 "labels
. Will drop the CSV labels and
use the option
" +
3176 Dygraph.warn("CSV is out of order
; order it correctly to speed loading
.");
3177 ret.sort(function(a,b) { return a[0] - b[0]; });
3184 * The user has provided their data as a pre-packaged JS array. If the x values
3185 * are numeric, this is the same as dygraphs' internal format. If the x values
3186 * are dates, we need to convert them from Date objects to ms since epoch.
3187 * @param {!Array} data
3188 * @return {Object} data with numeric x values.
3191 Dygraph.prototype.parseArray_ = function(data) {
3192 // Peek at the first x value to see if it's numeric.
3193 if (data.length === 0) {
3194 Dygraph.error("Can
't plot empty data set");
3197 if (data[0].length === 0) {
3198 Dygraph.error("Data set cannot contain an empty row");
3203 if (this.attr_("labels") === null) {
3204 Dygraph.warn("Using default labels. Set labels explicitly via 'labels
' " +
3205 "in the options parameter");
3206 this.attrs_.labels = [ "X" ];
3207 for (i = 1; i < data[0].length; i++) {
3208 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
3210 this.attributes_.reparseSeries();
3212 var num_labels = this.attr_("labels");
3213 if (num_labels.length != data[0].length) {
3214 Dygraph.error("Mismatch between number of labels (" + num_labels + ")" +
3215 " and number of columns in array (" + data[0].length + ")");
3220 if (Dygraph.isDateLike(data[0][0])) {
3221 // Some intelligent defaults for a date x-axis.
3222 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
3223 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3224 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
3226 // Assume they're all dates
.
3227 var parsedData
= Dygraph
.clone(data
);
3228 for (i
= 0; i
< data
.length
; i
++) {
3229 if (parsedData
[i
].length
=== 0) {
3230 Dygraph
.error("Row " + (1 + i
) + " of data is empty");
3233 if (parsedData
[i
][0] === null ||
3234 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3235 isNaN(parsedData
[i
][0].getTime())) {
3236 Dygraph
.error("x value in row " + (1 + i
) + " is not a Date");
3239 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3243 // Some intelligent defaults for a numeric x-axis.
3244 /** @private (shut up, jsdoc!) */
3245 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3246 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
3247 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3253 * Parses a DataTable object from gviz.
3254 * The data is expected to have a first column that is either a date or a
3255 * number. All subsequent columns must be numbers. If there is a clear mismatch
3256 * between this.xValueParser_ and the type of the first column, it will be
3257 * fixed. Fills out rawData_.
3258 * @param {!google.visualization.DataTable} data See above.
3261 Dygraph
.prototype.parseDataTable_
= function(data
) {
3262 var shortTextForAnnotationNum
= function(num
) {
3263 // converts [0-9]+ [A-Z][a-z]*
3264 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3265 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3266 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3267 num
= Math
.floor(num
/ 26);
3269 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3270 num
= Math
.floor((num
- 1) / 26);
3275 var cols
= data
.getNumberOfColumns();
3276 var rows
= data
.getNumberOfRows();
3278 var indepType
= data
.getColumnType(0);
3279 if (indepType
== 'date' || indepType
== 'datetime') {
3280 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3281 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateValueFormatter
;
3282 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3283 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisLabelFormatter
;
3284 } else if (indepType
== 'number') {
3285 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3286 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3287 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
3288 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3290 Dygraph
.error("only 'date', 'datetime' and 'number' types are supported " +
3291 "for column 1 of DataTable input (Got '" + indepType
+ "')");
3295 // Array of the column indices which contain data (and not annotations).
3297 var annotationCols
= {}; // data index -> [annotation cols]
3298 var hasAnnotations
= false;
3300 for (i
= 1; i
< cols
; i
++) {
3301 var type
= data
.getColumnType(i
);
3302 if (type
== 'number') {
3304 } else if (type
== 'string' && this.getBooleanOption('displayAnnotations')) {
3305 // This is OK -- it's an annotation column.
3306 var dataIdx
= colIdx
[colIdx
.length
- 1];
3307 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3308 annotationCols
[dataIdx
] = [i
];
3310 annotationCols
[dataIdx
].push(i
);
3312 hasAnnotations
= true;
3314 Dygraph
.error("Only 'number' is supported as a dependent type with Gviz." +
3315 " 'string' is only supported if displayAnnotations is true");
3319 // Read column labels
3320 // TODO(danvk): add support back for errorBars
3321 var labels
= [data
.getColumnLabel(0)];
3322 for (i
= 0; i
< colIdx
.length
; i
++) {
3323 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3324 if (this.getBooleanOption("errorBars")) i
+= 1;
3326 this.attrs_
.labels
= labels
;
3327 cols
= labels
.length
;
3330 var outOfOrder
= false;
3331 var annotations
= [];
3332 for (i
= 0; i
< rows
; i
++) {
3334 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3335 data
.getValue(i
, 0) === null) {
3336 Dygraph
.warn("Ignoring row " + i
+
3337 " of DataTable because of undefined or null first column.");
3341 if (indepType
== 'date' || indepType
== 'datetime') {
3342 row
.push(data
.getValue(i
, 0).getTime());
3344 row
.push(data
.getValue(i
, 0));
3346 if (!this.getBooleanOption("errorBars")) {
3347 for (j
= 0; j
< colIdx
.length
; j
++) {
3348 var col
= colIdx
[j
];
3349 row
.push(data
.getValue(i
, col
));
3350 if (hasAnnotations
&&
3351 annotationCols
.hasOwnProperty(col
) &&
3352 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3354 ann
.series
= data
.getColumnLabel(col
);
3356 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3358 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3359 if (k
) ann
.text
+= "\n";
3360 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3362 annotations
.push(ann
);
3366 // Strip out infinities, which give dygraphs problems later on.
3367 for (j
= 0; j
< row
.length
; j
++) {
3368 if (!isFinite(row
[j
])) row
[j
] = null;
3371 for (j
= 0; j
< cols
- 1; j
++) {
3372 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3375 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3382 Dygraph
.warn("DataTable is out of order; order it correctly to speed loading.");
3383 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3385 this.rawData_
= ret
;
3387 if (annotations
.length
> 0) {
3388 this.setAnnotations(annotations
, true);
3390 this.attributes_
.reparseSeries();
3394 * Get the CSV data. If it's in a function, call that function. If it's in a
3395 * file, do an XMLHttpRequest to get it.
3398 Dygraph
.prototype.start_
= function() {
3399 var data
= this.file_
;
3401 // Functions can return references of all other types.
3402 if (typeof data
== 'function') {
3406 if (Dygraph
.isArrayLike(data
)) {
3407 this.rawData_
= this.parseArray_(data
);
3409 } else if (typeof data
== 'object' &&
3410 typeof data
.getColumnRange
== 'function') {
3411 // must be a DataTable from gviz.
3412 this.parseDataTable_(data
);
3414 } else if (typeof data
== 'string') {
3415 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3416 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3417 if (line_delimiter
) {
3418 this.loadedEvent_(data
);
3422 if (window
.XMLHttpRequest
) {
3423 // Firefox, Opera, IE7, and other browsers will use the native object
3424 req
= new XMLHttpRequest();
3426 // IE 5 and 6 will use the ActiveX control
3427 req
= new ActiveXObject("Microsoft.XMLHTTP");
3431 req
.onreadystatechange
= function () {
3432 if (req
.readyState
== 4) {
3433 if (req
.status
=== 200 || // Normal http
3434 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3435 caller
.loadedEvent_(req
.responseText
);
3440 req
.open("GET", data
, true);
3444 Dygraph
.error("Unknown data format: " + (typeof data
));
3449 * Changes various properties of the graph. These can include:
3451 * <li>file: changes the source data for the graph</li>
3452 * <li>errorBars: changes whether the data contains stddev</li>
3455 * There's a huge variety of options that can be passed to this method. For a
3456 * full list, see http://dygraphs.com/options.html.
3458 * @param {Object} input_attrs The new properties and values
3459 * @param {boolean} block_redraw Usually the chart is redrawn after every
3460 * call to updateOptions(). If you know better, you can pass true to
3461 * explicitly block the redraw. This can be useful for chaining
3462 * updateOptions() calls, avoiding the occasional infinite loop and
3463 * preventing redraws when it's not necessary (e.g. when updating a
3466 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3467 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3469 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
3470 var file
= input_attrs
.file
;
3471 var attrs
= Dygraph
.mapLegacyOptions_(input_attrs
);
3473 // TODO(danvk): this is a mess. Move these options into attr_.
3474 if ('rollPeriod' in attrs
) {
3475 this.rollPeriod_
= attrs
.rollPeriod
;
3477 if ('dateWindow' in attrs
) {
3478 this.dateWindow_
= attrs
.dateWindow
;
3479 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3480 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3483 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3484 this.zoomed_y_
= (attrs
.valueRange
!== null);
3487 // TODO(danvk): validate per-series options.
3492 // highlightCircleSize
3494 // Check if this set options will require new points.
3495 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3497 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3499 this.attributes_
.reparseSeries();
3503 if (!block_redraw
) this.start_();
3505 if (!block_redraw
) {
3506 if (requiresNewPoints
) {
3509 this.renderGraph_(false);
3516 * Returns a copy of the options with deprecated names converted into current
3517 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
3518 * interested in that, they should save a copy before calling this.
3521 Dygraph
.mapLegacyOptions_
= function(attrs
) {
3523 for (var k
in attrs
) {
3524 if (k
== 'file') continue;
3525 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3528 var set
= function(axis
, opt
, value
) {
3529 if (!my_attrs
.axes
) my_attrs
.axes
= {};
3530 if (!my_attrs
.axes
[axis
]) my_attrs
.axes
[axis
] = {};
3531 my_attrs
.axes
[axis
][opt
] = value
;
3533 var map
= function(opt
, axis
, new_opt
) {
3534 if (typeof(attrs
[opt
]) != 'undefined') {
3535 Dygraph
.warn("Option " + opt
+ " is deprecated. Use the " +
3536 new_opt
+ " option for the " + axis
+ " axis instead. " +
3537 "(e.g. { axes : { " + axis
+ " : { " + new_opt
+ " : ... } } } " +
3538 "(see http://dygraphs.com/per-axis.html for more information.");
3539 set(axis
, new_opt
, attrs
[opt
]);
3540 delete my_attrs
[opt
];
3544 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3545 map('xValueFormatter', 'x', 'valueFormatter');
3546 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3547 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3548 map('xTicker', 'x', 'ticker');
3549 map('yValueFormatter', 'y', 'valueFormatter');
3550 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3551 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3552 map('yTicker', 'y', 'ticker');
3553 map('drawXGrid', 'x', 'drawGrid');
3554 map('drawXAxis', 'x', 'drawAxis');
3555 map('drawYGrid', 'y', 'drawGrid');
3556 map('drawYAxis', 'y', 'drawAxis');
3561 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3562 * containing div (which has presumably changed size since the dygraph was
3563 * instantiated. If the width/height are specified, the div will be resized.
3565 * This is far more efficient than destroying and re-instantiating a
3566 * Dygraph, since it doesn't have to reparse the underlying data.
3568 * @param {number} width Width (in pixels)
3569 * @param {number} height Height (in pixels)
3571 Dygraph
.prototype.resize
= function(width
, height
) {
3572 if (this.resize_lock
) {
3575 this.resize_lock
= true;
3577 if ((width
=== null) != (height
=== null)) {
3578 Dygraph
.warn("Dygraph.resize() should be called with zero parameters or " +
3579 "two non-NULL parameters. Pretending it was zero.");
3580 width
= height
= null;
3583 var old_width
= this.width_
;
3584 var old_height
= this.height_
;
3587 this.maindiv_
.style
.width
= width
+ "px";
3588 this.maindiv_
.style
.height
= height
+ "px";
3589 this.width_
= width
;
3590 this.height_
= height
;
3592 this.width_
= this.maindiv_
.clientWidth
;
3593 this.height_
= this.maindiv_
.clientHeight
;
3596 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3597 // Resizing a canvas erases it, even when the size doesn't change, so
3598 // any resize needs to be followed by a redraw.
3599 this.resizeElements_();
3603 this.resize_lock
= false;
3607 * Adjusts the number of points in the rolling average. Updates the graph to
3608 * reflect the new averaging period.
3609 * @param {number} length Number of points over which to average the data.
3611 Dygraph
.prototype.adjustRoll
= function(length
) {
3612 this.rollPeriod_
= length
;
3617 * Returns a boolean array of visibility statuses.
3619 Dygraph
.prototype.visibility
= function() {
3620 // Do lazy-initialization, so that this happens after we know the number of
3622 if (!this.getOption("visibility")) {
3623 this.attrs_
.visibility
= [];
3625 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3626 while (this.getOption("visibility").length
< this.numColumns() - 1) {
3627 this.attrs_
.visibility
.push(true);
3629 return this.getOption("visibility");
3633 * Changes the visiblity of a series.
3635 * @param {number} num the series index
3636 * @param {boolean} value true or false, identifying the visibility.
3638 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3639 var x
= this.visibility();
3640 if (num
< 0 || num
>= x
.length
) {
3641 Dygraph
.warn("invalid series number in setVisibility: " + num
);
3649 * How large of an area will the dygraph render itself in?
3650 * This is used for testing.
3651 * @return A {width: w, height: h} object.
3654 Dygraph
.prototype.size
= function() {
3655 return { width
: this.width_
, height
: this.height_
};
3659 * Update the list of annotations and redraw the chart.
3660 * See dygraphs.com/annotations.html for more info on how to use annotations.
3661 * @param ann {Array} An array of annotation objects.
3662 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3664 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3665 // Only add the annotation CSS rule once we know it will be used.
3666 Dygraph
.addAnnotationRule();
3667 this.annotations_
= ann
;
3668 if (!this.layout_
) {
3669 Dygraph
.warn("Tried to setAnnotations before dygraph was ready. " +
3670 "Try setting them in a ready() block. See " +
3671 "dygraphs.com/tests/annotation.html");
3675 this.layout_
.setAnnotations(this.annotations_
);
3676 if (!suppressDraw
) {
3682 * Return the list of annotations.
3684 Dygraph
.prototype.annotations
= function() {
3685 return this.annotations_
;
3689 * Get the list of label names for this graph. The first column is the
3690 * x-axis, so the data series names start at index 1.
3692 * Returns null when labels have not yet been defined.
3694 Dygraph
.prototype.getLabels
= function() {
3695 var labels
= this.attr_("labels");
3696 return labels
? labels
.slice() : null;
3700 * Get the index of a series (column) given its name. The first column is the
3701 * x-axis, so the data series start with index 1.
3703 Dygraph
.prototype.indexFromSetName
= function(name
) {
3704 return this.setIndexByName_
[name
];
3708 * Trigger a callback when the dygraph has drawn itself and is ready to be
3709 * manipulated. This is primarily useful when dygraphs has to do an XHR for the
3710 * data (i.e. a URL is passed as the data source) and the chart is drawn
3711 * asynchronously. If the chart has already drawn, the callback will fire
3714 * This is a good place to call setAnnotation().
3716 * @param {function(!Dygraph)} callback The callback to trigger when the chart
3719 Dygraph
.prototype.ready
= function(callback
) {
3720 if (this.is_initial_draw_
) {
3721 this.readyFns_
.push(callback
);
3729 * Adds a default style for the annotation CSS classes to the document. This is
3730 * only executed when annotations are actually used. It is designed to only be
3731 * called once -- all calls after the first will return immediately.
3733 Dygraph
.addAnnotationRule
= function() {
3734 // TODO(danvk): move this function into plugins/annotations.js
?
3735 if (Dygraph
.addedAnnotationCSS
) return;
3737 var rule
= "border: 1px solid black; " +
3738 "background-color: white; " +
3739 "text-align: center;";
3741 var styleSheetElement
= document
.createElement("style");
3742 styleSheetElement
.type
= "text/css";
3743 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3745 // Find the first style sheet that we can access.
3746 // We may not add a rule to a style sheet from another domain for security
3747 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3748 // adds its own style sheets from google.com.
3749 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3750 if (document
.styleSheets
[i
].disabled
) continue;
3751 var mysheet
= document
.styleSheets
[i
];
3753 if (mysheet
.insertRule
) { // Firefox
3754 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3755 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3756 } else if (mysheet
.addRule
) { // IE
3757 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3759 Dygraph
.addedAnnotationCSS
= true;
3762 // Was likely a security exception.
3766 Dygraph
.warn("Unable to add default annotation CSS rule; display may be off.");