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 // For "production" code, this gets set to false by uglifyjs.
47 if (typeof(DEBUG
) === 'undefined') DEBUG
=true;
49 var Dygraph
= (function() {
50 /*global DygraphLayout:false, DygraphCanvasRenderer:false, DygraphOptions:false, G_vmlCanvasManager:false,ActiveXObject:false */
54 * Creates an interactive, zoomable chart.
57 * @param {div | String} div A div or the id of a div into which to construct
59 * @param {String | Function} file A file containing CSV data or a function
60 * that returns this data. The most basic expected format for each line is
61 * "YYYY/MM/DD,val1,val2,...". For more information, see
62 * http://dygraphs.com/data.html.
63 * @param {Object} attrs Various other attributes, e.g. errorBars determines
64 * whether the input data contains error ranges. For a complete list of
65 * options, see http://dygraphs.com/options.html.
67 var Dygraph
= function(div
, data
, opts
) {
68 this.__init__(div
, data
, opts
);
71 Dygraph
.NAME
= "Dygraph";
72 Dygraph
.VERSION
= "1.1.0";
74 // Various default values
75 Dygraph
.DEFAULT_ROLL_PERIOD
= 1;
76 Dygraph
.DEFAULT_WIDTH
= 480;
77 Dygraph
.DEFAULT_HEIGHT
= 320;
79 // For max 60 Hz. animation:
80 Dygraph
.ANIMATION_STEPS
= 12;
81 Dygraph
.ANIMATION_DURATION
= 200;
83 // Label constants for the labelsKMB and labelsKMG2 options.
84 // (i.e. '100000' -> '100K')
85 Dygraph
.KMB_LABELS
= [ 'K', 'M', 'B', 'T', 'Q' ];
86 Dygraph
.KMG2_BIG_LABELS
= [ 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' ];
87 Dygraph
.KMG2_SMALL_LABELS
= [ 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y' ];
89 // These are defined before DEFAULT_ATTRS so that it can refer to them.
92 * Return a string version of a number. This respects the digitsAfterDecimal
93 * and maxNumberWidth options.
94 * @param {number} x The number to be formatted
95 * @param {Dygraph} opts An options view
97 Dygraph
.numberValueFormatter
= function(x
, opts
) {
98 var sigFigs
= opts('sigFigs');
100 if (sigFigs
!== null) {
101 // User has opted for a fixed number of significant figures.
102 return Dygraph
.floatFormat(x
, sigFigs
);
105 var digits
= opts('digitsAfterDecimal');
106 var maxNumberWidth
= opts('maxNumberWidth');
108 var kmb
= opts('labelsKMB');
109 var kmg2
= opts('labelsKMG2');
113 // switch to scientific notation if we underflow or overflow fixed display.
115 (Math
.abs(x
) >= Math
.pow(10, maxNumberWidth
) ||
116 Math
.abs(x
) < Math
.pow(10, -digits
))) {
117 label
= x
.toExponential(digits
);
119 label
= '' + Dygraph
.round_(x
, digits
);
128 k_labels
= Dygraph
.KMB_LABELS
;
131 if (kmb
) console
.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
133 k_labels
= Dygraph
.KMG2_BIG_LABELS
;
134 m_labels
= Dygraph
.KMG2_SMALL_LABELS
;
137 var absx
= Math
.abs(x
);
138 var n
= Dygraph
.pow(k
, k_labels
.length
);
139 for (var j
= k_labels
.length
- 1; j
>= 0; j
--, n
/= k
) {
141 label
= Dygraph
.round_(x
/ n
, digits
) + k_labels
[j
];
146 // TODO(danvk): clean up this logic. Why so different than kmb?
147 var x_parts
= String(x
.toExponential()).split('e-');
148 if (x_parts
.length
=== 2 && x_parts
[1] >= 3 && x_parts
[1] <= 24) {
149 if (x_parts
[1] % 3 > 0) {
150 label
= Dygraph
.round_(x_parts
[0] /
151 Dygraph
.pow(10, (x_parts
[1] % 3)),
154 label
= Number(x_parts
[0]).toFixed(2);
156 label
+= m_labels
[Math
.floor(x_parts
[1] / 3) - 1];
165 * variant for use as an axisLabelFormatter.
168 Dygraph
.numberAxisLabelFormatter
= function(x
, granularity
, opts
) {
169 return Dygraph
.numberValueFormatter
.call(this, x
, opts
);
173 * @type {!Array.<string>}
177 Dygraph
.SHORT_MONTH_NAMES_
= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
181 * Convert a JS date to a string appropriate to display on an axis that
182 * is displaying values at the stated granularity. This respects the
184 * @param {Date} date The date to format
185 * @param {number} granularity One of the Dygraph granularity constants
186 * @param {Dygraph} opts An options view
187 * @return {string} The date formatted as local time
190 Dygraph
.dateAxisLabelFormatter
= function(date
, granularity
, opts
) {
191 var utc
= opts('labelsUTC');
192 var accessors
= utc
? Dygraph
.DateAccessorsUTC
: Dygraph
.DateAccessorsLocal
;
194 var year
= accessors
.getFullYear(date
),
195 month
= accessors
.getMonth(date
),
196 day
= accessors
.getDate(date
),
197 hours
= accessors
.getHours(date
),
198 mins
= accessors
.getMinutes(date
),
199 secs
= accessors
.getSeconds(date
),
200 millis
= accessors
.getSeconds(date
);
202 if (granularity
>= Dygraph
.DECADAL
) {
204 } else if (granularity
>= Dygraph
.MONTHLY
) {
205 return Dygraph
.SHORT_MONTH_NAMES_
[month
] + ' ' + year
;
207 var frac
= hours
* 3600 + mins
* 60 + secs
+ 1e-3 * millis
;
208 if (frac
=== 0 || granularity
>= Dygraph
.DAILY
) {
209 // e.g. '21 Jan' (%d%b)
210 return Dygraph
.zeropad(day
) + ' ' + Dygraph
.SHORT_MONTH_NAMES_
[month
];
212 return Dygraph
.hmsString_(hours
, mins
, secs
);
216 // alias in case anyone is referencing the old method.
217 Dygraph
.dateAxisFormatter
= Dygraph
.dateAxisLabelFormatter
;
220 * Return a string version of a JS date for a value label. This respects the
222 * @param {Date} date The date to be formatted
223 * @param {Dygraph} opts An options view
226 Dygraph
.dateValueFormatter
= function(d
, opts
) {
227 return Dygraph
.dateString_(d
, opts('labelsUTC'));
231 * Standard plotters. These may be used by clients.
232 * Available plotters are:
233 * - Dygraph.Plotters.linePlotter: draws central lines (most common)
234 * - Dygraph.Plotters.errorPlotter: draws error bars
235 * - Dygraph.Plotters.fillPlotter: draws fills under lines (used with fillGraph)
237 * By default, the plotter is [fillPlotter, errorPlotter, linePlotter].
238 * This causes all the lines to be drawn over all the fills/error bars.
240 Dygraph
.Plotters
= DygraphCanvasRenderer
._Plotters
;
243 // Default attribute values.
244 Dygraph
.DEFAULT_ATTRS
= {
245 highlightCircleSize
: 3,
246 highlightSeriesOpts
: null,
247 highlightSeriesBackgroundAlpha
: 0.5,
251 // TODO(danvk): move defaults from createStatusMessage_ here.
253 labelsSeparateLines
: false,
254 labelsShowZeroValues
: true,
257 showLabelsOnHighlight
: true,
259 digitsAfterDecimal
: 2,
264 strokeBorderWidth
: 0,
265 strokeBorderColor
: "white",
268 axisLabelFontSize
: 14,
272 xValueParser
: Dygraph
.dateParser
,
279 wilsonInterval
: true, // only relevant if fractions is true
283 connectSeparatedPoints
: false,
286 stackedGraphNaNFill
: 'all',
287 hideOverlayOnMouseOut
: true,
289 legend
: 'onmouseover',
294 drawAxesAtZero
: false,
296 // Sizes of the various chart labels.
301 axisLineColor
: "black",
304 axisLabelColor
: "black",
306 gridLineColor
: "rgb(128,128,128)",
308 interactionModel
: null, // will be set to Dygraph.Interaction.defaultModel
309 animatedZooms
: false, // (for now)
311 // Range selector options
312 showRangeSelector
: false,
313 rangeSelectorHeight
: 40,
314 rangeSelectorPlotStrokeColor
: "#808FAB",
315 rangeSelectorPlotFillGradientColor
: "white",
316 rangeSelectorPlotFillColor
: "#A7B1C4",
317 rangeSelectorBackgroundStrokeColor
: "gray",
318 rangeSelectorBackgroundLineWidth
: 1,
319 rangeSelectorPlotLineWidth
:1.5,
320 rangeSelectorForegroundStrokeColor
: "black",
321 rangeSelectorForegroundLineWidth
: 1,
322 rangeSelectorAlpha
: 0.6,
323 showInRangeSelector
: null,
325 // The ordering here ensures that central lines always appear above any
326 // fill bars/error bars
.
328 Dygraph
.Plotters
.fillPlotter
,
329 Dygraph
.Plotters
.errorPlotter
,
330 Dygraph
.Plotters
.linePlotter
340 axisLabelFormatter
: Dygraph
.dateAxisLabelFormatter
,
341 valueFormatter
: Dygraph
.dateValueFormatter
,
344 independentTicks
: true,
345 ticker
: null // will be set in dygraph-tickers.js
350 valueFormatter
: Dygraph
.numberValueFormatter
,
351 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
354 independentTicks
: true,
355 ticker
: null // will be set in dygraph-tickers.js
360 valueFormatter
: Dygraph
.numberValueFormatter
,
361 axisLabelFormatter
: Dygraph
.numberAxisLabelFormatter
,
362 drawAxis
: true, // only applies when there are two axes of data.
364 independentTicks
: false,
365 ticker
: null // will be set in dygraph-tickers.js
370 // Directions for panning and zooming. Use bit operations when combined
371 // values are possible.
372 Dygraph
.HORIZONTAL
= 1;
373 Dygraph
.VERTICAL
= 2;
375 // Installed plugins, in order of precedence (most-general to most-specific).
376 // Plugins are installed after they are defined, in plugins/install.js
.
380 // Used for initializing annotation CSS rules only once.
381 Dygraph
.addedAnnotationCSS
= false;
384 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
385 * and context <canvas> inside of it. See the constructor for details.
387 * @param {Element} div the Element to render the graph into.
388 * @param {string | Function} file Source data
389 * @param {Object} attrs Miscellaneous other options
392 Dygraph
.prototype.__init__
= function(div
, file
, attrs
) {
393 this.is_initial_draw_
= true;
396 // Support two-argument constructor
397 if (attrs
=== null || attrs
=== undefined
) { attrs
= {}; }
399 attrs
= Dygraph
.copyUserAttrs_(attrs
);
401 if (typeof(div
) == 'string') {
402 div
= document
.getElementById(div
);
406 throw new Error('Constructing dygraph with a non-existent div!');
409 // Copy the important bits into the object
410 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
413 this.rollPeriod_
= attrs
.rollPeriod
|| Dygraph
.DEFAULT_ROLL_PERIOD
;
414 this.previousVerticalX_
= -1;
415 this.fractions_
= attrs
.fractions
|| false;
416 this.dateWindow_
= attrs
.dateWindow
|| null;
418 this.annotations_
= [];
420 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
421 this.zoomed_x_
= false;
422 this.zoomed_y_
= false;
424 // Clear the div. This ensure that, if multiple dygraphs are passed the same
425 // div, then only one will be drawn.
428 // For historical reasons, the 'width' and 'height' options trump all CSS
429 // rules _except_ for an explicit 'width' or 'height' on the div.
430 // As an added convenience, if the div has zero height (like <div></div> does
431 // without any styles), then we use a default height/width
.
432 if (div
.style
.width
=== '' && attrs
.width
) {
433 div
.style
.width
= attrs
.width
+ "px";
435 if (div
.style
.height
=== '' && attrs
.height
) {
436 div
.style
.height
= attrs
.height
+ "px";
438 if (div
.style
.height
=== '' && div
.clientHeight
=== 0) {
439 div
.style
.height
= Dygraph
.DEFAULT_HEIGHT
+ "px";
440 if (div
.style
.width
=== '') {
441 div
.style
.width
= Dygraph
.DEFAULT_WIDTH
+ "px";
444 // These will be zero if the dygraph's div is hidden. In that case,
445 // use the user-specified attributes if present. If not, use zero
446 // and assume the user will call resize to fix things later.
447 this.width_
= div
.clientWidth
|| attrs
.width
|| 0;
448 this.height_
= div
.clientHeight
|| attrs
.height
|| 0;
450 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
451 if (attrs
.stackedGraph
) {
452 attrs
.fillGraph
= true;
453 // TODO(nikhilk): Add any other stackedGraph checks here.
456 // DEPRECATION WARNING: All option processing should be moved from
457 // attrs_ and user_attrs_ to options_, which holds all this information.
459 // Dygraphs has many options, some of which interact with one another.
460 // To keep track of everything, we maintain two sets of options:
462 // this.user_attrs_ only options explicitly set by the user.
463 // this.attrs_ defaults, options derived from user_attrs_, data.
465 // Options are then accessed this.attr_('attr'), which first looks at
466 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
467 // defaults without overriding behavior that the user specifically asks for.
468 this.user_attrs_
= {};
469 Dygraph
.update(this.user_attrs_
, attrs
);
471 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
473 Dygraph
.updateDeep(this.attrs_
, Dygraph
.DEFAULT_ATTRS
);
475 this.boundaryIds_
= [];
476 this.setIndexByName_
= {};
477 this.datasetIndex_
= [];
479 this.registeredEvents_
= [];
480 this.eventListeners_
= {};
482 this.attributes_
= new DygraphOptions(this);
484 // Create the containing DIV and other interactive elements
485 this.createInterface_();
489 var plugins
= Dygraph
.PLUGINS
.concat(this.getOption('plugins'));
490 for (var i
= 0; i
< plugins
.length
; i
++) {
491 // the plugins option may contain either plugin classes or instances.
492 // Plugin instances contain an activate method.
493 var Plugin
= plugins
[i
]; // either a constructor or an instance.
495 if (typeof(Plugin
.activate
) !== 'undefined') {
496 pluginInstance
= Plugin
;
498 pluginInstance
= new Plugin();
502 plugin
: pluginInstance
,
508 var handlers
= pluginInstance
.activate(this);
509 for (var eventName
in handlers
) {
510 if (!handlers
.hasOwnProperty(eventName
)) continue;
511 // TODO(danvk): validate eventName.
512 pluginDict
.events
[eventName
] = handlers
[eventName
];
515 this.plugins_
.push(pluginDict
);
518 // At this point, plugins can no longer register event handlers.
519 // Construct a map from event -> ordered list of [callback, plugin].
520 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
521 var plugin_dict
= this.plugins_
[i
];
522 for (var eventName
in plugin_dict
.events
) {
523 if (!plugin_dict
.events
.hasOwnProperty(eventName
)) continue;
524 var callback
= plugin_dict
.events
[eventName
];
526 var pair
= [plugin_dict
.plugin
, callback
];
527 if (!(eventName
in this.eventListeners_
)) {
528 this.eventListeners_
[eventName
] = [pair
];
530 this.eventListeners_
[eventName
].push(pair
);
535 this.createDragInterface_();
541 * Triggers a cascade of events to the various plugins which are interested in them.
542 * Returns true if the "default behavior" should be prevented, i.e. if one
543 * of the event listeners called event.preventDefault().
546 Dygraph
.prototype.cascadeEvents_
= function(name
, extra_props
) {
547 if (!(name
in this.eventListeners_
)) return false;
549 // QUESTION: can we use objects & prototypes to speed this up?
553 defaultPrevented
: false,
554 preventDefault
: function() {
555 if (!e
.cancelable
) throw "Cannot call preventDefault on non-cancelable event.";
556 e
.defaultPrevented
= true;
558 propagationStopped
: false,
559 stopPropagation
: function() {
560 e
.propagationStopped
= true;
563 Dygraph
.update(e
, extra_props
);
565 var callback_plugin_pairs
= this.eventListeners_
[name
];
566 if (callback_plugin_pairs
) {
567 for (var i
= callback_plugin_pairs
.length
- 1; i
>= 0; i
--) {
568 var plugin
= callback_plugin_pairs
[i
][0];
569 var callback
= callback_plugin_pairs
[i
][1];
570 callback
.call(plugin
, e
);
571 if (e
.propagationStopped
) break;
574 return e
.defaultPrevented
;
578 * Fetch a plugin instance of a particular class. Only for testing.
580 * @param {!Class} type The type of the plugin.
581 * @return {Object} Instance of the plugin, or null if there is none.
583 Dygraph
.prototype.getPluginInstance_
= function(type
) {
584 for (var i
= 0; i
< this.plugins_
.length
; i
++) {
585 var p
= this.plugins_
[i
];
586 if (p
.plugin
instanceof type
) {
594 * Returns the zoomed status of the chart for one or both axes.
596 * Axis is an optional parameter. Can be set to 'x' or 'y'.
598 * The zoomed status for an axis is set whenever a user zooms using the mouse
599 * or when the dateWindow or valueRange are updated (unless the
600 * isZoomedIgnoreProgrammaticZoom option is also specified).
602 Dygraph
.prototype.isZoomed
= function(axis
) {
603 if (axis
=== null || axis
=== undefined
) {
604 return this.zoomed_x_
|| this.zoomed_y_
;
606 if (axis
=== 'x') return this.zoomed_x_
;
607 if (axis
=== 'y') return this.zoomed_y_
;
608 throw "axis parameter is [" + axis
+ "] must be null, 'x' or 'y'.";
612 * Returns information about the Dygraph object, including its containing ID.
614 Dygraph
.prototype.toString
= function() {
615 var maindiv
= this.maindiv_
;
616 var id
= (maindiv
&& maindiv
.id
) ? maindiv
.id
: maindiv
;
617 return "[Dygraph " + id
+ "]";
622 * Returns the value of an option. This may be set by the user (either in the
623 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
625 * @param {string} name The name of the option, e.g. 'rollPeriod'.
626 * @param {string} [seriesName] The name of the series to which the option
627 * will be applied. If no per-series value of this option is available, then
628 * the global value is returned. This is optional.
629 * @return { ... } The value of the option.
631 Dygraph
.prototype.attr_
= function(name
, seriesName
) {
633 if (typeof(Dygraph
.OPTIONS_REFERENCE
) === 'undefined') {
634 console
.error('Must include options reference JS for testing');
635 } else if (!Dygraph
.OPTIONS_REFERENCE
.hasOwnProperty(name
)) {
636 console
.error('Dygraphs is using property ' + name
+ ', which has no ' +
637 'entry in the Dygraphs.OPTIONS_REFERENCE listing.');
638 // Only log this error once.
639 Dygraph
.OPTIONS_REFERENCE
[name
] = true;
642 return seriesName
? this.attributes_
.getForSeries(name
, seriesName
) : this.attributes_
.get(name
);
646 * Returns the current value for an option, as set in the constructor or via
647 * updateOptions. You may pass in an (optional) series name to get per-series
648 * values for the option.
650 * All values returned by this method should be considered immutable. If you
651 * modify them, there is no guarantee that the changes will be honored or that
652 * dygraphs will remain in a consistent state. If you want to modify an option,
653 * use updateOptions() instead.
655 * @param {string} name The name of the option (e.g. 'strokeWidth')
656 * @param {string=} opt_seriesName Series name to get per-series values.
657 * @return {*} The value of the option.
659 Dygraph
.prototype.getOption
= function(name
, opt_seriesName
) {
660 return this.attr_(name
, opt_seriesName
);
664 * Like getOption(), but specifically returns a number.
665 * This is a convenience function for working with the Closure Compiler.
666 * @param {string} name The name of the option (e.g. 'strokeWidth')
667 * @param {string=} opt_seriesName Series name to get per-series values.
668 * @return {number} The value of the option.
671 Dygraph
.prototype.getNumericOption
= function(name
, opt_seriesName
) {
672 return /** @type{number} */(this.getOption(name
, opt_seriesName
));
676 * Like getOption(), but specifically returns a string.
677 * This is a convenience function for working with the Closure Compiler.
678 * @param {string} name The name of the option (e.g. 'strokeWidth')
679 * @param {string=} opt_seriesName Series name to get per-series values.
680 * @return {string} The value of the option.
683 Dygraph
.prototype.getStringOption
= function(name
, opt_seriesName
) {
684 return /** @type{string} */(this.getOption(name
, opt_seriesName
));
688 * Like getOption(), but specifically returns a boolean.
689 * This is a convenience function for working with the Closure Compiler.
690 * @param {string} name The name of the option (e.g. 'strokeWidth')
691 * @param {string=} opt_seriesName Series name to get per-series values.
692 * @return {boolean} The value of the option.
695 Dygraph
.prototype.getBooleanOption
= function(name
, opt_seriesName
) {
696 return /** @type{boolean} */(this.getOption(name
, opt_seriesName
));
700 * Like getOption(), but specifically returns a function.
701 * This is a convenience function for working with the Closure Compiler.
702 * @param {string} name The name of the option (e.g. 'strokeWidth')
703 * @param {string=} opt_seriesName Series name to get per-series values.
704 * @return {function(...)} The value of the option.
707 Dygraph
.prototype.getFunctionOption
= function(name
, opt_seriesName
) {
708 return /** @type{function(...)} */(this.getOption(name
, opt_seriesName
));
711 Dygraph
.prototype.getOptionForAxis
= function(name
, axis
) {
712 return this.attributes_
.getForAxis(name
, axis
);
717 * @param {string} axis The name of the axis (i.e. 'x', 'y' or 'y2')
718 * @return { ... } A function mapping string -> option value
720 Dygraph
.prototype.optionsViewForAxis_
= function(axis
) {
722 return function(opt
) {
723 var axis_opts
= self
.user_attrs_
.axes
;
724 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
725 return axis_opts
[axis
][opt
];
728 // I don't like that this is in a second spot.
729 if (axis
=== 'x' && opt
=== 'logscale') {
730 // return the default value.
731 // TODO(konigsberg): pull the default from a global default.
735 // user-specified attributes always trump defaults, even if they're less
737 if (typeof(self
.user_attrs_
[opt
]) != 'undefined') {
738 return self
.user_attrs_
[opt
];
741 axis_opts
= self
.attrs_
.axes
;
742 if (axis_opts
&& axis_opts
[axis
] && axis_opts
[axis
].hasOwnProperty(opt
)) {
743 return axis_opts
[axis
][opt
];
745 // check old-style axis options
746 // TODO(danvk): add a deprecation warning if either of these match.
747 if (axis
== 'y' && self
.axes_
[0].hasOwnProperty(opt
)) {
748 return self
.axes_
[0][opt
];
749 } else if (axis
== 'y2' && self
.axes_
[1].hasOwnProperty(opt
)) {
750 return self
.axes_
[1][opt
];
752 return self
.attr_(opt
);
757 * Returns the current rolling period, as set by the user or an option.
758 * @return {number} The number of points in the rolling window
760 Dygraph
.prototype.rollPeriod
= function() {
761 return this.rollPeriod_
;
765 * Returns the currently-visible x-range. This can be affected by zooming,
766 * panning or a call to updateOptions.
767 * Returns a two-element array: [left, right].
768 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
770 Dygraph
.prototype.xAxisRange
= function() {
771 return this.dateWindow_
? this.dateWindow_
: this.xAxisExtremes();
775 * Returns the lower- and upper-bound x-axis values of the
778 Dygraph
.prototype.xAxisExtremes
= function() {
779 var pad
= this.getNumericOption('xRangePad') / this.plotter_
.area
.w
;
780 if (this.numRows() === 0) {
781 return [0 - pad
, 1 + pad
];
783 var left
= this.rawData_
[0][0];
784 var right
= this.rawData_
[this.rawData_
.length
- 1][0];
786 // Must keep this in sync with dygraph-layout _evaluateLimits()
787 var range
= right
- left
;
789 right
+= range
* pad
;
791 return [left
, right
];
795 * Returns the currently-visible y-range for an axis. This can be affected by
796 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
797 * called with no arguments, returns the range of the first axis.
798 * Returns a two-element array: [bottom, top].
800 Dygraph
.prototype.yAxisRange
= function(idx
) {
801 if (typeof(idx
) == "undefined") idx
= 0;
802 if (idx
< 0 || idx
>= this.axes_
.length
) {
805 var axis
= this.axes_
[idx
];
806 return [ axis
.computedValueRange
[0], axis
.computedValueRange
[1] ];
810 * Returns the currently-visible y-ranges for each axis. This can be affected by
811 * zooming, panning, calls to updateOptions, etc.
812 * Returns an array of [bottom, top] pairs, one for each y-axis.
814 Dygraph
.prototype.yAxisRanges
= function() {
816 for (var i
= 0; i
< this.axes_
.length
; i
++) {
817 ret
.push(this.yAxisRange(i
));
822 // TODO(danvk): use these functions throughout dygraphs.
824 * Convert from data coordinates to canvas/div X/Y coordinates.
825 * If specified, do this conversion for the coordinate system of a particular
826 * axis. Uses the first axis by default.
827 * Returns a two-element array: [X, Y]
829 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
830 * instead of toDomCoords(null, y, axis).
832 Dygraph
.prototype.toDomCoords
= function(x
, y
, axis
) {
833 return [ this.toDomXCoord(x
), this.toDomYCoord(y
, axis
) ];
837 * Convert from data x coordinates to canvas/div X coordinate.
838 * If specified, do this conversion for the coordinate system of a particular
840 * Returns a single value or null if x is null.
842 Dygraph
.prototype.toDomXCoord
= function(x
) {
847 var area
= this.plotter_
.area
;
848 var xRange
= this.xAxisRange();
849 return area
.x
+ (x
- xRange
[0]) / (xRange
[1] - xRange
[0]) * area
.w
;
853 * Convert from data x coordinates to canvas/div Y coordinate and optional
854 * axis. Uses the first axis by default.
856 * returns a single value or null if y is null.
858 Dygraph
.prototype.toDomYCoord
= function(y
, axis
) {
859 var pct
= this.toPercentYCoord(y
, axis
);
864 var area
= this.plotter_
.area
;
865 return area
.y
+ pct
* area
.h
;
869 * Convert from canvas/div coords to data coordinates.
870 * If specified, do this conversion for the coordinate system of a particular
871 * axis. Uses the first axis by default.
872 * Returns a two-element array: [X, Y].
874 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
875 * instead of toDataCoords(null, y, axis).
877 Dygraph
.prototype.toDataCoords
= function(x
, y
, axis
) {
878 return [ this.toDataXCoord(x
), this.toDataYCoord(y
, axis
) ];
882 * Convert from canvas/div x coordinate to data coordinate.
884 * If x is null, this returns null.
886 Dygraph
.prototype.toDataXCoord
= function(x
) {
891 var area
= this.plotter_
.area
;
892 var xRange
= this.xAxisRange();
894 if (!this.attributes_
.getForAxis("logscale", 'x')) {
895 return xRange
[0] + (x
- area
.x
) / area
.w
* (xRange
[1] - xRange
[0]);
897 // TODO: remove duplicate code?
898 // Computing the inverse of toDomCoord.
899 var pct
= (x
- area
.x
) / area
.w
;
901 // Computing the inverse of toPercentXCoord. The function was arrived at with
902 // the following steps:
904 // Original calcuation:
905 // pct = (log(x) - log(xRange[0])) / (log(xRange
[1]) - log(xRange
[0])));
907 // Multiply both sides by the right-side demoninator.
908 // pct * (log(xRange[1] - log(xRange[0]))) = log(x) - log(xRange[0])
910 // add log(xRange[0]) to both sides
911 // log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])) = log(x);
913 // Swap both sides of the equation,
914 // log(x) = log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0]))
916 // Use both sides as the exponent in 10^exp and we're done.
917 // x = 10 ^ (log(xRange[0]) + (pct * (log(xRange[1]) - log(xRange[0])))
918 var logr0
= Dygraph
.log10(xRange
[0]);
919 var logr1
= Dygraph
.log10(xRange
[1]);
920 var exponent
= logr0
+ (pct
* (logr1
- logr0
));
921 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
927 * Convert from canvas/div y coord to value.
929 * If y is null, this returns null.
930 * if axis is null, this uses the first axis.
932 Dygraph
.prototype.toDataYCoord
= function(y
, axis
) {
937 var area
= this.plotter_
.area
;
938 var yRange
= this.yAxisRange(axis
);
940 if (typeof(axis
) == "undefined") axis
= 0;
941 if (!this.attributes_
.getForAxis("logscale", axis
)) {
942 return yRange
[0] + (area
.y
+ area
.h
- y
) / area
.h
* (yRange
[1] - yRange
[0]);
944 // Computing the inverse of toDomCoord.
945 var pct
= (y
- area
.y
) / area
.h
;
947 // Computing the inverse of toPercentYCoord. The function was arrived at with
948 // the following steps:
950 // Original calcuation:
951 // pct = (log(yRange[1]) - log(y)) / (log(yRange
[1]) - log(yRange
[0]));
953 // Multiply both sides by the right-side demoninator.
954 // pct * (log(yRange[1]) - log(yRange[0])) = log(yRange[1]) - log(y);
956 // subtract log(yRange[1]) from both sides.
957 // (pct * (log(yRange[1]) - log(yRange[0]))) - log(yRange[1]) = -log(y);
959 // and multiply both sides by -1.
960 // log(yRange[1]) - (pct * (logr1 - log(yRange[0])) = log(y);
962 // Swap both sides of the equation,
963 // log(y) = log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0])));
965 // Use both sides as the exponent in 10^exp and we're done.
966 // y = 10 ^ (log(yRange[1]) - (pct * (log(yRange[1]) - log(yRange[0]))));
967 var logr0
= Dygraph
.log10(yRange
[0]);
968 var logr1
= Dygraph
.log10(yRange
[1]);
969 var exponent
= logr1
- (pct
* (logr1
- logr0
));
970 var value
= Math
.pow(Dygraph
.LOG_SCALE
, exponent
);
976 * Converts a y for an axis to a percentage from the top to the
977 * bottom of the drawing area.
979 * If the coordinate represents a value visible on the canvas, then
980 * the value will be between 0 and 1, where 0 is the top of the canvas.
981 * However, this method will return values outside the range, as
982 * values can fall outside the canvas.
984 * If y is null, this returns null.
985 * if axis is null, this uses the first axis.
987 * @param {number} y The data y-coordinate.
988 * @param {number} [axis] The axis number on which the data coordinate lives.
989 * @return {number} A fraction in [0, 1] where 0 = the top edge.
991 Dygraph
.prototype.toPercentYCoord
= function(y
, axis
) {
995 if (typeof(axis
) == "undefined") axis
= 0;
997 var yRange
= this.yAxisRange(axis
);
1000 var logscale
= this.attributes_
.getForAxis("logscale", axis
);
1002 var logr0
= Dygraph
.log10(yRange
[0]);
1003 var logr1
= Dygraph
.log10(yRange
[1]);
1004 pct
= (logr1
- Dygraph
.log10(y
)) / (logr1
- logr0
);
1006 // yRange[1] - y is unit distance from the bottom.
1007 // yRange[1] - yRange[0] is the scale of the range.
1008 // (yRange[1] - y) / (yRange
[1] - yRange
[0]) is the
% from the bottom
.
1009 pct
= (yRange
[1] - y
) / (yRange
[1] - yRange
[0]);
1015 * Converts an x value to a percentage from the left to the right of
1018 * If the coordinate represents a value visible on the canvas, then
1019 * the value will be between 0 and 1, where 0 is the left of the canvas.
1020 * However, this method will return values outside the range, as
1021 * values can fall outside the canvas.
1023 * If x is null, this returns null.
1024 * @param {number} x The data x-coordinate.
1025 * @return {number} A fraction in [0, 1] where 0 = the left edge.
1027 Dygraph
.prototype.toPercentXCoord
= function(x
) {
1032 var xRange
= this.xAxisRange();
1034 var logscale
= this.attributes_
.getForAxis("logscale", 'x') ;
1035 if (logscale
=== true) { // logscale can be null so we test for true explicitly.
1036 var logr0
= Dygraph
.log10(xRange
[0]);
1037 var logr1
= Dygraph
.log10(xRange
[1]);
1038 pct
= (Dygraph
.log10(x
) - logr0
) / (logr1
- logr0
);
1040 // x - xRange[0] is unit distance from the left.
1041 // xRange[1] - xRange[0] is the scale of the range.
1042 // The full expression below is the % from the left.
1043 pct
= (x
- xRange
[0]) / (xRange
[1] - xRange
[0]);
1049 * Returns the number of columns (including the independent variable).
1050 * @return {number} The number of columns.
1052 Dygraph
.prototype.numColumns
= function() {
1053 if (!this.rawData_
) return 0;
1054 return this.rawData_
[0] ? this.rawData_
[0].length
: this.attr_("labels").length
;
1058 * Returns the number of rows (excluding any header/label row).
1059 * @return {number} The number of rows, less any header.
1061 Dygraph
.prototype.numRows
= function() {
1062 if (!this.rawData_
) return 0;
1063 return this.rawData_
.length
;
1067 * Returns the value in the given row and column. If the row and column exceed
1068 * the bounds on the data, returns null. Also returns null if the value is
1070 * @param {number} row The row number of the data (0-based). Row 0 is the
1071 * first row of data, not a header row.
1072 * @param {number} col The column number of the data (0-based)
1073 * @return {number} The value in the specified cell or null if the row/col
1074 * were out of range.
1076 Dygraph
.prototype.getValue
= function(row
, col
) {
1077 if (row
< 0 || row
> this.rawData_
.length
) return null;
1078 if (col
< 0 || col
> this.rawData_
[row
].length
) return null;
1080 return this.rawData_
[row
][col
];
1084 * Generates interface elements for the Dygraph: a containing div, a div to
1085 * display the current point, and a textbox to adjust the rolling average
1086 * period. Also creates the Renderer/Layout elements.
1089 Dygraph
.prototype.createInterface_
= function() {
1090 // Create the all-enclosing graph div
1091 var enclosing
= this.maindiv_
;
1093 this.graphDiv
= document
.createElement("div");
1095 // TODO(danvk): any other styles that are useful to set here?
1096 this.graphDiv
.style
.textAlign
= 'left'; // This is a CSS "reset"
1097 this.graphDiv
.style
.position
= 'relative';
1098 enclosing
.appendChild(this.graphDiv
);
1100 // Create the canvas for interactive parts of the chart.
1101 this.canvas_
= Dygraph
.createCanvas();
1102 this.canvas_
.style
.position
= "absolute";
1104 // ... and for static parts of the chart.
1105 this.hidden_
= this.createPlotKitCanvas_(this.canvas_
);
1107 this.canvas_ctx_
= Dygraph
.getContext(this.canvas_
);
1108 this.hidden_ctx_
= Dygraph
.getContext(this.hidden_
);
1110 this.resizeElements_();
1112 // The interactive parts of the graph are drawn on top of the chart.
1113 this.graphDiv
.appendChild(this.hidden_
);
1114 this.graphDiv
.appendChild(this.canvas_
);
1115 this.mouseEventElement_
= this.createMouseEventElement_();
1117 // Create the grapher
1118 this.layout_
= new DygraphLayout(this);
1122 this.mouseMoveHandler_
= function(e
) {
1123 dygraph
.mouseMove_(e
);
1126 this.mouseOutHandler_
= function(e
) {
1127 // The mouse has left the chart if:
1128 // 1. e.target is inside the chart
1129 // 2. e.relatedTarget is outside the chart
1130 var target
= e
.target
|| e
.fromElement
;
1131 var relatedTarget
= e
.relatedTarget
|| e
.toElement
;
1132 if (Dygraph
.isNodeContainedBy(target
, dygraph
.graphDiv
) &&
1133 !Dygraph
.isNodeContainedBy(relatedTarget
, dygraph
.graphDiv
)) {
1134 dygraph
.mouseOut_(e
);
1138 this.addAndTrackEvent(window
, 'mouseout', this.mouseOutHandler_
);
1139 this.addAndTrackEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1141 // Don't recreate and register the resize handler on subsequent calls.
1142 // This happens when the graph is resized.
1143 if (!this.resizeHandler_
) {
1144 this.resizeHandler_
= function(e
) {
1148 // Update when the window is resized.
1149 // TODO(danvk): drop frames depending on complexity of the chart.
1150 this.addAndTrackEvent(window
, 'resize', this.resizeHandler_
);
1154 Dygraph
.prototype.resizeElements_
= function() {
1155 this.graphDiv
.style
.width
= this.width_
+ "px";
1156 this.graphDiv
.style
.height
= this.height_
+ "px";
1158 var canvasScale
= Dygraph
.getContextPixelRatio(this.canvas_ctx_
);
1159 this.canvas_
.width
= this.width_
* canvasScale
;
1160 this.canvas_
.height
= this.height_
* canvasScale
;
1161 this.canvas_
.style
.width
= this.width_
+ "px"; // for IE
1162 this.canvas_
.style
.height
= this.height_
+ "px"; // for IE
1163 if (canvasScale
!== 1) {
1164 this.canvas_ctx_
.scale(canvasScale
, canvasScale
);
1167 var hiddenScale
= Dygraph
.getContextPixelRatio(this.hidden_ctx_
);
1168 this.hidden_
.width
= this.width_
* hiddenScale
;
1169 this.hidden_
.height
= this.height_
* hiddenScale
;
1170 this.hidden_
.style
.width
= this.width_
+ "px"; // for IE
1171 this.hidden_
.style
.height
= this.height_
+ "px"; // for IE
1172 if (hiddenScale
!== 1) {
1173 this.hidden_ctx_
.scale(hiddenScale
, hiddenScale
);
1178 * Detach DOM elements in the dygraph and null out all data references.
1179 * Calling this when you're done with a dygraph can dramatically reduce memory
1180 * usage. See, e.g., the tests/perf.html example.
1182 Dygraph
.prototype.destroy
= function() {
1183 this.canvas_ctx_
.restore();
1184 this.hidden_ctx_
.restore();
1186 // Destroy any plugins, in the reverse order that they were registered.
1187 for (var i
= this.plugins_
.length
- 1; i
>= 0; i
--) {
1188 var p
= this.plugins_
.pop();
1189 if (p
.plugin
.destroy
) p
.plugin
.destroy();
1192 var removeRecursive
= function(node
) {
1193 while (node
.hasChildNodes()) {
1194 removeRecursive(node
.firstChild
);
1195 node
.removeChild(node
.firstChild
);
1199 this.removeTrackedEvents_();
1201 // remove mouse event handlers (This may not be necessary anymore)
1202 Dygraph
.removeEvent(window
, 'mouseout', this.mouseOutHandler_
);
1203 Dygraph
.removeEvent(this.mouseEventElement_
, 'mousemove', this.mouseMoveHandler_
);
1205 // remove window handlers
1206 Dygraph
.removeEvent(window
,'resize', this.resizeHandler_
);
1207 this.resizeHandler_
= null;
1209 removeRecursive(this.maindiv_
);
1211 var nullOut
= function(obj
) {
1212 for (var n
in obj
) {
1213 if (typeof(obj
[n
]) === 'object') {
1218 // These may not all be necessary, but it can't hurt...
1219 nullOut(this.layout_
);
1220 nullOut(this.plotter_
);
1225 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
1226 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
1227 * or the zoom rectangles) is done on this.canvas_.
1228 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
1229 * @return {Object} The newly-created canvas
1232 Dygraph
.prototype.createPlotKitCanvas_
= function(canvas
) {
1233 var h
= Dygraph
.createCanvas();
1234 h
.style
.position
= "absolute";
1235 // TODO(danvk): h should be offset from canvas. canvas needs to include
1236 // some extra area to make it easier to zoom in on the far left and far
1237 // right. h needs to be precisely the plot area, so that clipping occurs.
1238 h
.style
.top
= canvas
.style
.top
;
1239 h
.style
.left
= canvas
.style
.left
;
1240 h
.width
= this.width_
;
1241 h
.height
= this.height_
;
1242 h
.style
.width
= this.width_
+ "px"; // for IE
1243 h
.style
.height
= this.height_
+ "px"; // for IE
1248 * Creates an overlay element used to handle mouse events.
1249 * @return {Object} The mouse event element.
1252 Dygraph
.prototype.createMouseEventElement_
= function() {
1253 return this.canvas_
;
1257 * Generate a set of distinct colors for the data series. This is done with a
1258 * color wheel. Saturation/Value are customizable, and the hue is
1259 * equally-spaced around the color wheel. If a custom set of colors is
1260 * specified, that is used instead.
1263 Dygraph
.prototype.setColors_
= function() {
1264 var labels
= this.getLabels();
1265 var num
= labels
.length
- 1;
1267 this.colorsMap_
= {};
1269 // These are used for when no custom colors are specified.
1270 var sat
= this.getNumericOption('colorSaturation') || 1.0;
1271 var val
= this.getNumericOption('colorValue') || 0.5;
1272 var half
= Math
.ceil(num
/ 2);
1274 var colors
= this.getOption('colors');
1275 var visibility
= this.visibility();
1276 for (var i
= 0; i
< num
; i
++) {
1277 if (!visibility
[i
]) {
1280 var label
= labels
[i
+ 1];
1281 var colorStr
= this.attributes_
.getForSeries('color', label
);
1284 colorStr
= colors
[i
% colors
.length
];
1286 // alternate colors for high contrast.
1287 var idx
= i
% 2 ? (half
+ (i
+ 1)/ 2) : Math.ceil((i + 1) / 2);
1288 var hue
= (1.0 * idx
/ (1 + num
));
1289 colorStr
= Dygraph
.hsvToRGB(hue
, sat
, val
);
1292 this.colors_
.push(colorStr
);
1293 this.colorsMap_
[label
] = colorStr
;
1298 * Return the list of colors. This is either the list of colors passed in the
1299 * attributes or the autogenerated list of rgb(r,g,b) strings.
1300 * This does not return colors for invisible series.
1301 * @return {Array.<string>} The list of colors.
1303 Dygraph
.prototype.getColors
= function() {
1304 return this.colors_
;
1308 * Returns a few attributes of a series, i.e. its color, its visibility, which
1309 * axis it's assigned to, and its column in the original data.
1310 * Returns null if the series does not exist.
1311 * Otherwise, returns an object with column, visibility, color and axis properties.
1312 * The "axis" property will be set to 1 for y1 and 2 for y2.
1313 * The "column" property can be fed back into getValue(row, column) to get
1314 * values for this series.
1316 Dygraph
.prototype.getPropertiesForSeries
= function(series_name
) {
1318 var labels
= this.getLabels();
1319 for (var i
= 1; i
< labels
.length
; i
++) {
1320 if (labels
[i
] == series_name
) {
1325 if (idx
== -1) return null;
1330 visible
: this.visibility()[idx
- 1],
1331 color
: this.colorsMap_
[series_name
],
1332 axis
: 1 + this.attributes_
.axisForSeries(series_name
)
1337 * Create the text box to adjust the averaging period
1340 Dygraph
.prototype.createRollInterface_
= function() {
1341 // Create a roller if one doesn't exist already.
1342 if (!this.roller_
) {
1343 this.roller_
= document
.createElement("input");
1344 this.roller_
.type
= "text";
1345 this.roller_
.style
.display
= "none";
1346 this.graphDiv
.appendChild(this.roller_
);
1349 var display
= this.getBooleanOption('showRoller') ? 'block' : 'none';
1351 var area
= this.plotter_
.area
;
1352 var textAttr
= { "position": "absolute",
1354 "top": (area
.y
+ area
.h
- 25) + "px",
1355 "left": (area
.x
+ 1) + "px",
1358 this.roller_
.size
= "2";
1359 this.roller_
.value
= this.rollPeriod_
;
1360 for (var name
in textAttr
) {
1361 if (textAttr
.hasOwnProperty(name
)) {
1362 this.roller_
.style
[name
] = textAttr
[name
];
1367 this.roller_
.onchange
= function() { dygraph
.adjustRoll(dygraph
.roller_
.value
); };
1371 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1375 Dygraph
.prototype.createDragInterface_
= function() {
1377 // Tracks whether the mouse is down right now
1379 isPanning
: false, // is this drag part of a pan?
1380 is2DPan
: false, // if so, is that pan 1- or 2-dimensional?
1381 dragStartX
: null, // pixel coordinates
1382 dragStartY
: null, // pixel coordinates
1383 dragEndX
: null, // pixel coordinates
1384 dragEndY
: null, // pixel coordinates
1385 dragDirection
: null,
1386 prevEndX
: null, // pixel coordinates
1387 prevEndY
: null, // pixel coordinates
1388 prevDragDirection
: null,
1389 cancelNextDblclick
: false, // see comment in dygraph-interaction-model.js
1391 // The value on the left side of the graph when a pan operation starts.
1392 initialLeftmostDate
: null,
1394 // The number of units each pixel spans. (This won't be valid for log
1396 xUnitsPerPixel
: null,
1398 // TODO(danvk): update this comment
1399 // The range in second/value units that the viewport encompasses during a
1400 // panning operation.
1403 // Top-left corner of the canvas, in DOM coords
1404 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
1408 // Values for use with panEdgeFraction, which limit how far outside the
1409 // graph's data boundaries it can be panned.
1410 boundedDates
: null, // [minDate, maxDate]
1411 boundedValues
: null, // [[minValue, maxValue] ...]
1413 // We cover iframes during mouse interactions. See comments in
1414 // dygraph-utils.js for more info on why this is a good idea.
1415 tarp
: new Dygraph
.IFrameTarp(),
1417 // contextB is the same thing as this context object but renamed.
1418 initializeMouseDown
: function(event
, g
, contextB
) {
1419 // prevents mouse drags from selecting page text.
1420 if (event
.preventDefault
) {
1421 event
.preventDefault(); // Firefox, Chrome, etc.
1423 event
.returnValue
= false; // IE
1424 event
.cancelBubble
= true;
1427 var canvasPos
= Dygraph
.findPos(g
.canvas_
);
1428 contextB
.px
= canvasPos
.x
;
1429 contextB
.py
= canvasPos
.y
;
1430 contextB
.dragStartX
= Dygraph
.dragGetX_(event
, contextB
);
1431 contextB
.dragStartY
= Dygraph
.dragGetY_(event
, contextB
);
1432 contextB
.cancelNextDblclick
= false;
1433 contextB
.tarp
.cover();
1435 destroy
: function() {
1437 if (context
.isZooming
|| context
.isPanning
) {
1438 context
.isZooming
= false;
1439 context
.dragStartX
= null;
1440 context
.dragStartY
= null;
1443 if (context
.isPanning
) {
1444 context
.isPanning
= false;
1445 context
.draggingDate
= null;
1446 context
.dateRange
= null;
1447 for (var i
= 0; i
< self
.axes_
.length
; i
++) {
1448 delete self
.axes_
[i
].draggingValue
;
1449 delete self
.axes_
[i
].dragValueRange
;
1453 context
.tarp
.uncover();
1457 var interactionModel
= this.getOption("interactionModel");
1459 // Self is the graph.
1462 // Function that binds the graph and context to the handler.
1463 var bindHandler
= function(handler
) {
1464 return function(event
) {
1465 handler(event
, self
, context
);
1469 for (var eventName
in interactionModel
) {
1470 if (!interactionModel
.hasOwnProperty(eventName
)) continue;
1471 this.addAndTrackEvent(this.mouseEventElement_
, eventName
,
1472 bindHandler(interactionModel
[eventName
]));
1475 // If the user releases the mouse button during a drag, but not over the
1476 // canvas, then it doesn't count as a zooming action.
1477 if (!interactionModel
.willDestroyContextMyself
) {
1478 var mouseUpHandler
= function(event
) {
1482 this.addAndTrackEvent(document
, 'mouseup', mouseUpHandler
);
1487 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1488 * up any previous zoom rectangles that were drawn. This could be optimized to
1489 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1492 * @param {number} direction the direction of the zoom rectangle. Acceptable
1493 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
1494 * @param {number} startX The X position where the drag started, in canvas
1496 * @param {number} endX The current X position of the drag, in canvas coords.
1497 * @param {number} startY The Y position where the drag started, in canvas
1499 * @param {number} endY The current Y position of the drag, in canvas coords.
1500 * @param {number} prevDirection the value of direction on the previous call to
1501 * this function. Used to avoid excess redrawing
1502 * @param {number} prevEndX The value of endX on the previous call to this
1503 * function. Used to avoid excess redrawing
1504 * @param {number} prevEndY The value of endY on the previous call to this
1505 * function. Used to avoid excess redrawing
1508 Dygraph
.prototype.drawZoomRect_
= function(direction
, startX
, endX
, startY
,
1509 endY
, prevDirection
, prevEndX
,
1511 var ctx
= this.canvas_ctx_
;
1513 // Clean up from the previous rect if necessary
1514 if (prevDirection
== Dygraph
.HORIZONTAL
) {
1515 ctx
.clearRect(Math
.min(startX
, prevEndX
), this.layout_
.getPlotArea().y
,
1516 Math
.abs(startX
- prevEndX
), this.layout_
.getPlotArea().h
);
1517 } else if (prevDirection
== Dygraph
.VERTICAL
) {
1518 ctx
.clearRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, prevEndY
),
1519 this.layout_
.getPlotArea().w
, Math
.abs(startY
- prevEndY
));
1522 // Draw a light-grey rectangle to show the new viewing area
1523 if (direction
== Dygraph
.HORIZONTAL
) {
1524 if (endX
&& startX
) {
1525 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1526 ctx
.fillRect(Math
.min(startX
, endX
), this.layout_
.getPlotArea().y
,
1527 Math
.abs(endX
- startX
), this.layout_
.getPlotArea().h
);
1529 } else if (direction
== Dygraph
.VERTICAL
) {
1530 if (endY
&& startY
) {
1531 ctx
.fillStyle
= "rgba(128,128,128,0.33)";
1532 ctx
.fillRect(this.layout_
.getPlotArea().x
, Math
.min(startY
, endY
),
1533 this.layout_
.getPlotArea().w
, Math
.abs(endY
- startY
));
1539 * Clear the zoom rectangle (and perform no zoom).
1542 Dygraph
.prototype.clearZoomRect_
= function() {
1543 this.currentZoomRectArgs_
= null;
1544 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
1548 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1549 * the canvas. The exact zoom window may be slightly larger if there are no data
1550 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1551 * which accepts dates that match the raw data. This function redraws the graph.
1553 * @param {number} lowX The leftmost pixel value that should be visible.
1554 * @param {number} highX The rightmost pixel value that should be visible.
1557 Dygraph
.prototype.doZoomX_
= function(lowX
, highX
) {
1558 this.currentZoomRectArgs_
= null;
1559 // Find the earliest and latest dates contained in this canvasx range.
1560 // Convert the call to date ranges of the raw data.
1561 var minDate
= this.toDataXCoord(lowX
);
1562 var maxDate
= this.toDataXCoord(highX
);
1563 this.doZoomXDates_(minDate
, maxDate
);
1567 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1568 * method with doZoomX which accepts pixel coordinates. This function redraws
1571 * @param {number} minDate The minimum date that should be visible.
1572 * @param {number} maxDate The maximum date that should be visible.
1575 Dygraph
.prototype.doZoomXDates_
= function(minDate
, maxDate
) {
1576 // TODO(danvk): when xAxisRange is null (i.e. "fit to data", the animation
1577 // can produce strange effects. Rather than the x-axis transitioning slowly
1578 // between values, it can jerk around.)
1579 var old_window
= this.xAxisRange();
1580 var new_window
= [minDate
, maxDate
];
1581 this.zoomed_x_
= true;
1583 this.doAnimatedZoom(old_window
, new_window
, null, null, function() {
1584 if (that
.getFunctionOption("zoomCallback")) {
1585 that
.getFunctionOption("zoomCallback").call(that
,
1586 minDate
, maxDate
, that
.yAxisRanges());
1592 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
1593 * the canvas. This function redraws the graph.
1595 * @param {number} lowY The topmost pixel value that should be visible.
1596 * @param {number} highY The lowest pixel value that should be visible.
1599 Dygraph
.prototype.doZoomY_
= function(lowY
, highY
) {
1600 this.currentZoomRectArgs_
= null;
1601 // Find the highest and lowest values in pixel range for each axis.
1602 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1603 // This is because pixels increase as you go down on the screen, whereas data
1604 // coordinates increase as you go up the screen.
1605 var oldValueRanges
= this.yAxisRanges();
1606 var newValueRanges
= [];
1607 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1608 var hi
= this.toDataYCoord(lowY
, i
);
1609 var low
= this.toDataYCoord(highY
, i
);
1610 newValueRanges
.push([low
, hi
]);
1613 this.zoomed_y_
= true;
1615 this.doAnimatedZoom(null, null, oldValueRanges
, newValueRanges
, function() {
1616 if (that
.getFunctionOption("zoomCallback")) {
1617 var xRange
= that
.xAxisRange();
1618 that
.getFunctionOption("zoomCallback").call(that
,
1619 xRange
[0], xRange
[1], that
.yAxisRanges());
1625 * Transition function to use in animations. Returns values between 0.0
1626 * (totally old values) and 1.0 (totally new values) for each frame.
1629 Dygraph
.zoomAnimationFunction
= function(frame
, numFrames
) {
1631 return (1.0 - Math
.pow(k
, -frame
)) / (1.0 - Math
.pow(k
, -numFrames
));
1635 * Reset the zoom to the original view coordinates. This is the same as
1636 * double-clicking on the graph.
1638 Dygraph
.prototype.resetZoom
= function() {
1639 var dirty
= false, dirtyX
= false, dirtyY
= false;
1640 if (this.dateWindow_
!== null) {
1645 for (var i
= 0; i
< this.axes_
.length
; i
++) {
1646 if (typeof(this.axes_
[i
].valueWindow
) !== 'undefined' && this.axes_
[i
].valueWindow
!== null) {
1652 // Clear any selection, since it's likely to be drawn in the wrong place.
1653 this.clearSelection();
1656 this.zoomed_x_
= false;
1657 this.zoomed_y_
= false;
1659 var minDate
= this.rawData_
[0][0];
1660 var maxDate
= this.rawData_
[this.rawData_
.length
- 1][0];
1662 // With only one frame, don't bother calculating extreme ranges.
1663 // TODO(danvk): merge this block w/ the code below
.
1664 if (!this.getBooleanOption("animatedZooms")) {
1665 this.dateWindow_
= null;
1666 for (i
= 0; i
< this.axes_
.length
; i
++) {
1667 if (this.axes_
[i
].valueWindow
!== null) {
1668 delete this.axes_
[i
].valueWindow
;
1672 if (this.getFunctionOption("zoomCallback")) {
1673 this.getFunctionOption("zoomCallback").call(this,
1674 minDate
, maxDate
, this.yAxisRanges());
1679 var oldWindow
=null, newWindow
=null, oldValueRanges
=null, newValueRanges
=null;
1681 oldWindow
= this.xAxisRange();
1682 newWindow
= [minDate
, maxDate
];
1686 oldValueRanges
= this.yAxisRanges();
1687 // TODO(danvk): this is pretty inefficient
1688 var packed
= this.gatherDatasets_(this.rolledSeries_
, null);
1689 var extremes
= packed
.extremes
;
1691 // this has the side-effect of modifying this.axes_.
1692 // this doesn't make much sense in this context, but it's convenient (we
1693 // need this.axes_[*].extremeValues) and not harmful since we'll be
1694 // calling drawGraph_ shortly, which clobbers these values.
1695 this.computeYAxisRanges_(extremes
);
1697 newValueRanges
= [];
1698 for (i
= 0; i
< this.axes_
.length
; i
++) {
1699 var axis
= this.axes_
[i
];
1700 newValueRanges
.push((axis
.valueRange
!== null &&
1701 axis
.valueRange
!== undefined
) ?
1702 axis
.valueRange
: axis
.extremeRange
);
1707 this.doAnimatedZoom(oldWindow
, newWindow
, oldValueRanges
, newValueRanges
,
1709 that
.dateWindow_
= null;
1710 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1711 if (that
.axes_
[i
].valueWindow
!== null) {
1712 delete that
.axes_
[i
].valueWindow
;
1715 if (that
.getFunctionOption("zoomCallback")) {
1716 that
.getFunctionOption("zoomCallback").call(that
,
1717 minDate
, maxDate
, that
.yAxisRanges());
1724 * Combined animation logic for all zoom functions.
1725 * either the x parameters or y parameters may be null.
1728 Dygraph
.prototype.doAnimatedZoom
= function(oldXRange
, newXRange
, oldYRanges
, newYRanges
, callback
) {
1729 var steps
= this.getBooleanOption("animatedZooms") ?
1730 Dygraph
.ANIMATION_STEPS
: 1;
1733 var valueRanges
= [];
1736 if (oldXRange
!== null && newXRange
!== null) {
1737 for (step
= 1; step
<= steps
; step
++) {
1738 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1739 windows
[step
-1] = [oldXRange
[0]*(1-frac
) + frac
*newXRange
[0],
1740 oldXRange
[1]*(1-frac
) + frac
*newXRange
[1]];
1744 if (oldYRanges
!== null && newYRanges
!== null) {
1745 for (step
= 1; step
<= steps
; step
++) {
1746 frac
= Dygraph
.zoomAnimationFunction(step
, steps
);
1748 for (var j
= 0; j
< this.axes_
.length
; j
++) {
1749 thisRange
.push([oldYRanges
[j
][0]*(1-frac
) + frac
*newYRanges
[j
][0],
1750 oldYRanges
[j
][1]*(1-frac
) + frac
*newYRanges
[j
][1]]);
1752 valueRanges
[step
-1] = thisRange
;
1757 Dygraph
.repeatAndCleanup(function(step
) {
1758 if (valueRanges
.length
) {
1759 for (var i
= 0; i
< that
.axes_
.length
; i
++) {
1760 var w
= valueRanges
[step
][i
];
1761 that
.axes_
[i
].valueWindow
= [w
[0], w
[1]];
1764 if (windows
.length
) {
1765 that
.dateWindow_
= windows
[step
];
1768 }, steps
, Dygraph
.ANIMATION_DURATION
/ steps
, callback
);
1772 * Get the current graph's area object.
1774 * Returns: {x, y, w, h}
1776 Dygraph
.prototype.getArea
= function() {
1777 return this.plotter_
.area
;
1781 * Convert a mouse event to DOM coordinates relative to the graph origin.
1783 * Returns a two-element array: [X, Y].
1785 Dygraph
.prototype.eventToDomCoords
= function(event
) {
1786 if (event
.offsetX
&& event
.offsetY
) {
1787 return [ event
.offsetX
, event
.offsetY
];
1789 var eventElementPos
= Dygraph
.findPos(this.mouseEventElement_
);
1790 var canvasx
= Dygraph
.pageX(event
) - eventElementPos
.x
;
1791 var canvasy
= Dygraph
.pageY(event
) - eventElementPos
.y
;
1792 return [canvasx
, canvasy
];
1797 * Given a canvas X coordinate, find the closest row.
1798 * @param {number} domX graph-relative DOM X coordinate
1799 * Returns {number} row number.
1802 Dygraph
.prototype.findClosestRow
= function(domX
) {
1803 var minDistX
= Infinity
;
1804 var closestRow
= -1;
1805 var sets
= this.layout_
.points
;
1806 for (var i
= 0; i
< sets
.length
; i
++) {
1807 var points
= sets
[i
];
1808 var len
= points
.length
;
1809 for (var j
= 0; j
< len
; j
++) {
1810 var point
= points
[j
];
1811 if (!Dygraph
.isValidPoint(point
, true)) continue;
1812 var dist
= Math
.abs(point
.canvasx
- domX
);
1813 if (dist
< minDistX
) {
1815 closestRow
= point
.idx
;
1824 * Given canvas X,Y coordinates, find the closest point.
1826 * This finds the individual data point across all visible series
1827 * that's closest to the supplied DOM coordinates using the standard
1828 * Euclidean X,Y distance.
1830 * @param {number} domX graph-relative DOM X coordinate
1831 * @param {number} domY graph-relative DOM Y coordinate
1832 * Returns: {row, seriesName, point}
1835 Dygraph
.prototype.findClosestPoint
= function(domX
, domY
) {
1836 var minDist
= Infinity
;
1837 var dist
, dx
, dy
, point
, closestPoint
, closestSeries
, closestRow
;
1838 for ( var setIdx
= this.layout_
.points
.length
- 1 ; setIdx
>= 0 ; --setIdx
) {
1839 var points
= this.layout_
.points
[setIdx
];
1840 for (var i
= 0; i
< points
.length
; ++i
) {
1842 if (!Dygraph
.isValidPoint(point
)) continue;
1843 dx
= point
.canvasx
- domX
;
1844 dy
= point
.canvasy
- domY
;
1845 dist
= dx
* dx
+ dy
* dy
;
1846 if (dist
< minDist
) {
1848 closestPoint
= point
;
1849 closestSeries
= setIdx
;
1850 closestRow
= point
.idx
;
1854 var name
= this.layout_
.setNames
[closestSeries
];
1863 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1865 * This first finds the X data point closest to the supplied DOM X coordinate,
1866 * then finds the series which puts the Y coordinate on top of its filled area,
1867 * using linear interpolation between adjacent point pairs.
1869 * @param {number} domX graph-relative DOM X coordinate
1870 * @param {number} domY graph-relative DOM Y coordinate
1871 * Returns: {row, seriesName, point}
1874 Dygraph
.prototype.findStackedPoint
= function(domX
, domY
) {
1875 var row
= this.findClosestRow(domX
);
1876 var closestPoint
, closestSeries
;
1877 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
1878 var boundary
= this.getLeftBoundary_(setIdx
);
1879 var rowIdx
= row
- boundary
;
1880 var points
= this.layout_
.points
[setIdx
];
1881 if (rowIdx
>= points
.length
) continue;
1882 var p1
= points
[rowIdx
];
1883 if (!Dygraph
.isValidPoint(p1
)) continue;
1884 var py
= p1
.canvasy
;
1885 if (domX
> p1
.canvasx
&& rowIdx
+ 1 < points
.length
) {
1886 // interpolate series Y value using next point
1887 var p2
= points
[rowIdx
+ 1];
1888 if (Dygraph
.isValidPoint(p2
)) {
1889 var dx
= p2
.canvasx
- p1
.canvasx
;
1891 var r
= (domX
- p1
.canvasx
) / dx
;
1892 py
+= r
* (p2
.canvasy
- p1
.canvasy
);
1895 } else if (domX
< p1
.canvasx
&& rowIdx
> 0) {
1896 // interpolate series Y value using previous point
1897 var p0
= points
[rowIdx
- 1];
1898 if (Dygraph
.isValidPoint(p0
)) {
1899 var dx
= p1
.canvasx
- p0
.canvasx
;
1901 var r
= (p1
.canvasx
- domX
) / dx
;
1902 py
+= r
* (p0
.canvasy
- p1
.canvasy
);
1906 // Stop if the point (domX, py) is above this series' upper edge
1907 if (setIdx
=== 0 || py
< domY
) {
1909 closestSeries
= setIdx
;
1912 var name
= this.layout_
.setNames
[closestSeries
];
1921 * When the mouse moves in the canvas, display information about a nearby data
1922 * point and draw dots over those points in the data series. This function
1923 * takes care of cleanup of previously-drawn dots.
1924 * @param {Object} event The mousemove event from the browser.
1927 Dygraph
.prototype.mouseMove_
= function(event
) {
1928 // This prevents JS errors when mousing over the canvas before data loads.
1929 var points
= this.layout_
.points
;
1930 if (points
=== undefined
|| points
=== null) return;
1932 var canvasCoords
= this.eventToDomCoords(event
);
1933 var canvasx
= canvasCoords
[0];
1934 var canvasy
= canvasCoords
[1];
1936 var highlightSeriesOpts
= this.getOption("highlightSeriesOpts");
1937 var selectionChanged
= false;
1938 if (highlightSeriesOpts
&& !this.isSeriesLocked()) {
1940 if (this.getBooleanOption("stackedGraph")) {
1941 closest
= this.findStackedPoint(canvasx
, canvasy
);
1943 closest
= this.findClosestPoint(canvasx
, canvasy
);
1945 selectionChanged
= this.setSelection(closest
.row
, closest
.seriesName
);
1947 var idx
= this.findClosestRow(canvasx
);
1948 selectionChanged
= this.setSelection(idx
);
1951 var callback
= this.getFunctionOption("highlightCallback");
1952 if (callback
&& selectionChanged
) {
1953 callback
.call(this, event
,
1957 this.highlightSet_
);
1962 * Fetch left offset from the specified set index or if not passed, the
1963 * first defined boundaryIds record (see bug #236).
1966 Dygraph
.prototype.getLeftBoundary_
= function(setIdx
) {
1967 if (this.boundaryIds_
[setIdx
]) {
1968 return this.boundaryIds_
[setIdx
][0];
1970 for (var i
= 0; i
< this.boundaryIds_
.length
; i
++) {
1971 if (this.boundaryIds_
[i
] !== undefined
) {
1972 return this.boundaryIds_
[i
][0];
1979 Dygraph
.prototype.animateSelection_
= function(direction
) {
1980 var totalSteps
= 10;
1982 if (this.fadeLevel
=== undefined
) this.fadeLevel
= 0;
1983 if (this.animateId
=== undefined
) this.animateId
= 0;
1984 var start
= this.fadeLevel
;
1985 var steps
= direction
< 0 ? start
: totalSteps
- start
;
1987 if (this.fadeLevel
) {
1988 this.updateSelection_(1.0);
1993 var thisId
= ++this.animateId
;
1995 var cleanupIfClearing
= function() {
1996 // if we haven't reached fadeLevel 0 in the max frame time,
1997 // ensure that the clear happens and just go to 0
1998 if (that
.fadeLevel
!== 0 && direction
< 0) {
2000 that
.clearSelection();
2003 Dygraph
.repeatAndCleanup(
2005 // ignore simultaneous animations
2006 if (that
.animateId
!= thisId
) return;
2008 that
.fadeLevel
+= direction
;
2009 if (that
.fadeLevel
=== 0) {
2010 that
.clearSelection();
2012 that
.updateSelection_(that
.fadeLevel
/ totalSteps
);
2015 steps
, millis
, cleanupIfClearing
);
2019 * Draw dots over the selectied points in the data series. This function
2020 * takes care of cleanup of previously-drawn dots.
2023 Dygraph
.prototype.updateSelection_
= function(opt_animFraction
) {
2024 /*var defaultPrevented = */
2025 this.cascadeEvents_('select', {
2026 selectedRow
: this.lastRow_
,
2027 selectedX
: this.lastx_
,
2028 selectedPoints
: this.selPoints_
2030 // TODO(danvk): use defaultPrevented here?
2032 // Clear the previously drawn vertical, if there is one
2034 var ctx
= this.canvas_ctx_
;
2035 if (this.getOption('highlightSeriesOpts')) {
2036 ctx
.clearRect(0, 0, this.width_
, this.height_
);
2037 var alpha
= 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha');
2039 // Activating background fade includes an animation effect for a gradual
2040 // fade. TODO(klausw): make this independently configurable if it causes
2041 // issues? Use a shared preference to control animations?
2042 var animateBackgroundFade
= true;
2043 if (animateBackgroundFade
) {
2044 if (opt_animFraction
=== undefined
) {
2045 // start a new animation
2046 this.animateSelection_(1);
2049 alpha
*= opt_animFraction
;
2051 ctx
.fillStyle
= 'rgba(255,255,255,' + alpha
+ ')';
2052 ctx
.fillRect(0, 0, this.width_
, this.height_
);
2055 // Redraw only the highlighted series in the interactive canvas (not the
2056 // static plot canvas, which is where series are usually drawn).
2057 this.plotter_
._renderLineChart(this.highlightSet_
, ctx
);
2058 } else if (this.previousVerticalX_
>= 0) {
2059 // Determine the maximum highlight circle size.
2060 var maxCircleSize
= 0;
2061 var labels
= this.attr_('labels');
2062 for (i
= 1; i
< labels
.length
; i
++) {
2063 var r
= this.getNumericOption('highlightCircleSize', labels
[i
]);
2064 if (r
> maxCircleSize
) maxCircleSize
= r
;
2066 var px
= this.previousVerticalX_
;
2067 ctx
.clearRect(px
- maxCircleSize
- 1, 0,
2068 2 * maxCircleSize
+ 2, this.height_
);
2071 if (this.selPoints_
.length
> 0) {
2072 // Draw colored circles over the center of each selected point
2073 var canvasx
= this.selPoints_
[0].canvasx
;
2075 for (i
= 0; i
< this.selPoints_
.length
; i
++) {
2076 var pt
= this.selPoints_
[i
];
2077 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
2079 var circleSize
= this.getNumericOption('highlightCircleSize', pt
.name
);
2080 var callback
= this.getFunctionOption("drawHighlightPointCallback", pt
.name
);
2081 var color
= this.plotter_
.colors
[pt
.name
];
2083 callback
= Dygraph
.Circles
.DEFAULT
;
2085 ctx
.lineWidth
= this.getNumericOption('strokeWidth', pt
.name
);
2086 ctx
.strokeStyle
= color
;
2087 ctx
.fillStyle
= color
;
2088 callback
.call(this, this, pt
.name
, ctx
, canvasx
, pt
.canvasy
,
2089 color
, circleSize
, pt
.idx
);
2093 this.previousVerticalX_
= canvasx
;
2098 * Manually set the selected points and display information about them in the
2099 * legend. The selection can be cleared using clearSelection() and queried
2100 * using getSelection().
2101 * @param {number} row Row number that should be highlighted (i.e. appear with
2102 * hover dots on the chart).
2103 * @param {seriesName} optional series name to highlight that series with the
2104 * the highlightSeriesOpts setting.
2105 * @param { locked } optional If true, keep seriesName selected when mousing
2106 * over the graph, disabling closest-series highlighting. Call clearSelection()
2109 Dygraph
.prototype.setSelection
= function(row
, opt_seriesName
, opt_locked
) {
2110 // Extract the points we've selected
2111 this.selPoints_
= [];
2113 var changed
= false;
2114 if (row
!== false && row
>= 0) {
2115 if (row
!= this.lastRow_
) changed
= true;
2116 this.lastRow_
= row
;
2117 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; ++setIdx
) {
2118 var points
= this.layout_
.points
[setIdx
];
2119 // Check if the point at the appropriate index is the point we're looking
2120 // for. If it is, just use it, otherwise search the array for a point
2121 // in the proper place.
2122 var setRow
= row
- this.getLeftBoundary_(setIdx
);
2123 if (setRow
< points
.length
&& points
[setRow
].idx
== row
) {
2124 var point
= points
[setRow
];
2125 if (point
.yval
!== null) this.selPoints_
.push(point
);
2127 for (var pointIdx
= 0; pointIdx
< points
.length
; ++pointIdx
) {
2128 var point
= points
[pointIdx
];
2129 if (point
.idx
== row
) {
2130 if (point
.yval
!== null) {
2131 this.selPoints_
.push(point
);
2139 if (this.lastRow_
>= 0) changed
= true;
2143 if (this.selPoints_
.length
) {
2144 this.lastx_
= this.selPoints_
[0].xval
;
2149 if (opt_seriesName
!== undefined
) {
2150 if (this.highlightSet_
!== opt_seriesName
) changed
= true;
2151 this.highlightSet_
= opt_seriesName
;
2154 if (opt_locked
!== undefined
) {
2155 this.lockedSet_
= opt_locked
;
2159 this.updateSelection_(undefined
);
2165 * The mouse has left the canvas. Clear out whatever artifacts remain
2166 * @param {Object} event the mouseout event from the browser.
2169 Dygraph
.prototype.mouseOut_
= function(event
) {
2170 if (this.getFunctionOption("unhighlightCallback")) {
2171 this.getFunctionOption("unhighlightCallback").call(this, event
);
2174 if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_
) {
2175 this.clearSelection();
2180 * Clears the current selection (i.e. points that were highlighted by moving
2181 * the mouse over the chart).
2183 Dygraph
.prototype.clearSelection
= function() {
2184 this.cascadeEvents_('deselect', {});
2186 this.lockedSet_
= false;
2187 // Get rid of the overlay data
2188 if (this.fadeLevel
) {
2189 this.animateSelection_(-1);
2192 this.canvas_ctx_
.clearRect(0, 0, this.width_
, this.height_
);
2194 this.selPoints_
= [];
2197 this.highlightSet_
= null;
2201 * Returns the number of the currently selected row. To get data for this row,
2202 * you can use the getValue method.
2203 * @return {number} row number, or -1 if nothing is selected
2205 Dygraph
.prototype.getSelection
= function() {
2206 if (!this.selPoints_
|| this.selPoints_
.length
< 1) {
2210 for (var setIdx
= 0; setIdx
< this.layout_
.points
.length
; setIdx
++) {
2211 var points
= this.layout_
.points
[setIdx
];
2212 for (var row
= 0; row
< points
.length
; row
++) {
2213 if (points
[row
].x
== this.selPoints_
[0].x
) {
2214 return points
[row
].idx
;
2222 * Returns the name of the currently-highlighted series.
2223 * Only available when the highlightSeriesOpts option is in use.
2225 Dygraph
.prototype.getHighlightSeries
= function() {
2226 return this.highlightSet_
;
2230 * Returns true if the currently-highlighted series was locked
2231 * via setSelection(..., seriesName, true).
2233 Dygraph
.prototype.isSeriesLocked
= function() {
2234 return this.lockedSet_
;
2238 * Fires when there's data available to be graphed.
2239 * @param {string} data Raw CSV data to be plotted
2242 Dygraph
.prototype.loadedEvent_
= function(data
) {
2243 this.rawData_
= this.parseCSV_(data
);
2244 this.cascadeDataDidUpdateEvent_();
2249 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2252 Dygraph
.prototype.addXTicks_
= function() {
2253 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2255 if (this.dateWindow_
) {
2256 range
= [this.dateWindow_
[0], this.dateWindow_
[1]];
2258 range
= this.xAxisExtremes();
2261 var xAxisOptionsView
= this.optionsViewForAxis_('x');
2262 var xTicks
= xAxisOptionsView('ticker')(
2265 this.plotter_
.area
.w
, // TODO(danvk): should be area.width
2268 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2269 // console.log(msg);
2270 this.layout_
.setXTicks(xTicks
);
2274 * Returns the correct handler class for the currently set options.
2277 Dygraph
.prototype.getHandlerClass_
= function() {
2279 if (this.attr_('dataHandler')) {
2280 handlerClass
= this.attr_('dataHandler');
2281 } else if (this.fractions_
) {
2282 if (this.getBooleanOption('errorBars')) {
2283 handlerClass
= Dygraph
.DataHandlers
.FractionsBarsHandler
;
2285 handlerClass
= Dygraph
.DataHandlers
.DefaultFractionHandler
;
2287 } else if (this.getBooleanOption('customBars')) {
2288 handlerClass
= Dygraph
.DataHandlers
.CustomBarsHandler
;
2289 } else if (this.getBooleanOption('errorBars')) {
2290 handlerClass
= Dygraph
.DataHandlers
.ErrorBarsHandler
;
2292 handlerClass
= Dygraph
.DataHandlers
.DefaultHandler
;
2294 return handlerClass
;
2299 * This function is called once when the chart's data is changed or the options
2300 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2301 * idea is that values derived from the chart's data can be computed here,
2302 * rather than every time the chart is drawn. This includes things like the
2303 * number of axes, rolling averages, etc.
2305 Dygraph
.prototype.predraw_
= function() {
2306 var start
= new Date();
2308 // Create the correct dataHandler
2309 this.dataHandler_
= new (this.getHandlerClass_())();
2311 this.layout_
.computePlotArea();
2313 // TODO(danvk): move more computations out of drawGraph_ and into here.
2314 this.computeYAxes_();
2316 if (!this.is_initial_draw_
) {
2317 this.canvas_ctx_
.restore();
2318 this.hidden_ctx_
.restore();
2321 this.canvas_ctx_
.save();
2322 this.hidden_ctx_
.save();
2324 // Create a new plotter.
2325 this.plotter_
= new DygraphCanvasRenderer(this,
2330 // The roller sits in the bottom left corner of the chart. We don't know where
2331 // this will be until the options are available, so it's positioned here.
2332 this.createRollInterface_();
2334 this.cascadeEvents_('predraw');
2336 // Convert the raw data (a 2D array) into the internal format and compute
2337 // rolling averages.
2338 this.rolledSeries_
= [null]; // x-axis is the first series and it's special
2339 for (var i
= 1; i
< this.numColumns(); i
++) {
2340 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too
.
2341 var series
= this.dataHandler_
.extractSeries(this.rawData_
, i
, this.attributes_
);
2342 if (this.rollPeriod_
> 1) {
2343 series
= this.dataHandler_
.rollingAverage(series
, this.rollPeriod_
, this.attributes_
);
2346 this.rolledSeries_
.push(series
);
2349 // If the data or options have changed, then we'd better redraw.
2352 // This is used to determine whether to do various animations.
2353 var end
= new Date();
2354 this.drawingTimeMs_
= (end
- start
);
2360 * xval_* and yval_* are the original unscaled data values,
2361 * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
2362 * yval_stacked is the cumulative Y value used for stacking graphs,
2363 * and bottom/top/minus/plus are used for error bar graphs.
2370 * y_bottom: ?number,
2372 * y_stacked: ?number,
2374 * yval_minus: ?number,
2376 * yval_plus: ?number,
2380 Dygraph
.PointType
= undefined
;
2383 * Calculates point stacking for stackedGraph=true.
2385 * For stacking purposes, interpolate or extend neighboring data across
2386 * NaN values based on stackedGraphNaNFill settings. This is for display
2387 * only, the underlying data value as shown in the legend remains NaN.
2389 * @param {Array.<Dygraph.PointType>} points Point array for a single series.
2390 * Updates each Point's yval_stacked property.
2391 * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
2392 * values for the series seen so far. Index is the row number. Updated
2393 * based on the current series's values.
2394 * @param {Array.<number>} seriesExtremes Min and max values, updated
2395 * to reflect the stacked values.
2396 * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
2400 Dygraph
.stackPoints_
= function(
2401 points
, cumulativeYval
, seriesExtremes
, fillMethod
) {
2402 var lastXval
= null;
2403 var prevPoint
= null;
2404 var nextPoint
= null;
2405 var nextPointIdx
= -1;
2407 // Find the next stackable point starting from the given index.
2408 var updateNextPoint
= function(idx
) {
2409 // If we've previously found a non-NaN point and haven't gone past it yet,
2411 if (nextPointIdx
>= idx
) return;
2413 // We haven't found a non-NaN point yet or have moved past it,
2414 // look towards the right to find a non-NaN point.
2415 for (var j
= idx
; j
< points
.length
; ++j
) {
2416 // Clear out a previously-found point (if any) since it's no longer
2417 // valid, we shouldn't use it for interpolation anymore.
2419 if (!isNaN(points
[j
].yval
) && points
[j
].yval
!== null) {
2421 nextPoint
= points
[j
];
2427 for (var i
= 0; i
< points
.length
; ++i
) {
2428 var point
= points
[i
];
2429 var xval
= point
.xval
;
2430 if (cumulativeYval
[xval
] === undefined
) {
2431 cumulativeYval
[xval
] = 0;
2434 var actualYval
= point
.yval
;
2435 if (isNaN(actualYval
) || actualYval
=== null) {
2436 if(fillMethod
== 'none') {
2439 // Interpolate/extend
for stacking purposes
if possible
.
2441 if (prevPoint
&& nextPoint
&& fillMethod
!= 'none') {
2442 // Use linear interpolation between prevPoint and nextPoint.
2443 actualYval
= prevPoint
.yval
+ (nextPoint
.yval
- prevPoint
.yval
) *
2444 ((xval
- prevPoint
.xval
) / (nextPoint
.xval
- prevPoint
.xval
));
2445 } else if (prevPoint
&& fillMethod
== 'all') {
2446 actualYval
= prevPoint
.yval
;
2447 } else if (nextPoint
&& fillMethod
== 'all') {
2448 actualYval
= nextPoint
.yval
;
2457 var stackedYval
= cumulativeYval
[xval
];
2458 if (lastXval
!= xval
) {
2459 // If an x-value is repeated, we ignore the duplicates.
2460 stackedYval
+= actualYval
;
2461 cumulativeYval
[xval
] = stackedYval
;
2465 point
.yval_stacked
= stackedYval
;
2467 if (stackedYval
> seriesExtremes
[1]) {
2468 seriesExtremes
[1] = stackedYval
;
2470 if (stackedYval
< seriesExtremes
[0]) {
2471 seriesExtremes
[0] = stackedYval
;
2478 * Loop over all fields and create datasets, calculating extreme y-values for
2479 * each series and extreme x-indices as we go.
2481 * dateWindow is passed in as an explicit parameter so that we can compute
2482 * extreme values "speculatively", i.e. without actually setting state on the
2485 * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
2486 * rolledSeries[seriesIndex][row] = raw point, where
2487 * seriesIndex is the column number starting with 1, and
2488 * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
2489 * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
2491 * points: Array.<Array.<Dygraph.PointType>>,
2492 * seriesExtremes: Array.<Array.<number>>,
2493 * boundaryIds: Array.<number>}}
2496 Dygraph
.prototype.gatherDatasets_
= function(rolledSeries
, dateWindow
) {
2497 var boundaryIds
= [];
2499 var cumulativeYval
= []; // For stacked series.
2500 var extremes
= {}; // series name -> [low, high]
2501 var seriesIdx
, sampleIdx
;
2502 var firstIdx
, lastIdx
;
2505 // Loop over the fields (series). Go from the last to the first,
2506 // because if they're stacked that's how we accumulate the values.
2507 var num_series
= rolledSeries
.length
- 1;
2509 for (seriesIdx
= num_series
; seriesIdx
>= 1; seriesIdx
--) {
2510 if (!this.visibility()[seriesIdx
- 1]) continue;
2512 // Prune down to the desired range, if necessary (for zooming)
2513 // Because there can be lines going to points outside of the visible area,
2514 // we actually prune to visible points, plus one on either side.
2516 series
= rolledSeries
[seriesIdx
];
2517 var low
= dateWindow
[0];
2518 var high
= dateWindow
[1];
2520 // TODO(danvk): do binary search instead of linear search.
2521 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2524 for (sampleIdx
= 0; sampleIdx
< series
.length
; sampleIdx
++) {
2525 if (series
[sampleIdx
][0] >= low
&& firstIdx
=== null) {
2526 firstIdx
= sampleIdx
;
2528 if (series
[sampleIdx
][0] <= high
) {
2529 lastIdx
= sampleIdx
;
2533 if (firstIdx
=== null) firstIdx
= 0;
2534 var correctedFirstIdx
= firstIdx
;
2535 var isInvalidValue
= true;
2536 while (isInvalidValue
&& correctedFirstIdx
> 0) {
2537 correctedFirstIdx
--;
2538 // check if the y value is null.
2539 isInvalidValue
= series
[correctedFirstIdx
][1] === null;
2542 if (lastIdx
=== null) lastIdx
= series
.length
- 1;
2543 var correctedLastIdx
= lastIdx
;
2544 isInvalidValue
= true;
2545 while (isInvalidValue
&& correctedLastIdx
< series
.length
- 1) {
2547 isInvalidValue
= series
[correctedLastIdx
][1] === null;
2550 if (correctedFirstIdx
!==firstIdx
) {
2551 firstIdx
= correctedFirstIdx
;
2553 if (correctedLastIdx
!== lastIdx
) {
2554 lastIdx
= correctedLastIdx
;
2557 boundaryIds
[seriesIdx
-1] = [firstIdx
, lastIdx
];
2559 // .slice's end is exclusive, we want to include lastIdx.
2560 series
= series
.slice(firstIdx
, lastIdx
+ 1);
2562 series
= rolledSeries
[seriesIdx
];
2563 boundaryIds
[seriesIdx
-1] = [0, series
.length
-1];
2566 var seriesName
= this.attr_("labels")[seriesIdx
];
2567 var seriesExtremes
= this.dataHandler_
.getExtremeYValues(series
,
2568 dateWindow
, this.getBooleanOption("stepPlot",seriesName
));
2570 var seriesPoints
= this.dataHandler_
.seriesToPoints(series
,
2571 seriesName
, boundaryIds
[seriesIdx
-1][0]);
2573 if (this.getBooleanOption("stackedGraph")) {
2574 axisIdx
= this.attributes_
.axisForSeries(seriesName
);
2575 if (cumulativeYval
[axisIdx
] === undefined
) {
2576 cumulativeYval
[axisIdx
] = [];
2578 Dygraph
.stackPoints_(seriesPoints
, cumulativeYval
[axisIdx
], seriesExtremes
,
2579 this.getBooleanOption("stackedGraphNaNFill"));
2582 extremes
[seriesName
] = seriesExtremes
;
2583 points
[seriesIdx
] = seriesPoints
;
2586 return { points
: points
, extremes
: extremes
, boundaryIds
: boundaryIds
};
2590 * Update the graph with new data. This method is called when the viewing area
2591 * has changed. If the underlying data or options have changed, predraw_ will
2592 * be called before drawGraph_ is called.
2596 Dygraph
.prototype.drawGraph_
= function() {
2597 var start
= new Date();
2599 // This is used to set the second parameter to drawCallback, below.
2600 var is_initial_draw
= this.is_initial_draw_
;
2601 this.is_initial_draw_
= false;
2603 this.layout_
.removeAllDatasets();
2605 this.attrs_
.pointSize
= 0.5 * this.getNumericOption('highlightCircleSize');
2607 var packed
= this.gatherDatasets_(this.rolledSeries_
, this.dateWindow_
);
2608 var points
= packed
.points
;
2609 var extremes
= packed
.extremes
;
2610 this.boundaryIds_
= packed
.boundaryIds
;
2612 this.setIndexByName_
= {};
2613 var labels
= this.attr_("labels");
2614 if (labels
.length
> 0) {
2615 this.setIndexByName_
[labels
[0]] = 0;
2618 for (var i
= 1; i
< points
.length
; i
++) {
2619 this.setIndexByName_
[labels
[i
]] = i
;
2620 if (!this.visibility()[i
- 1]) continue;
2621 this.layout_
.addDataset(labels
[i
], points
[i
]);
2622 this.datasetIndex_
[i
] = dataIdx
++;
2625 this.computeYAxisRanges_(extremes
);
2626 this.layout_
.setYAxes(this.axes_
);
2630 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2631 var tmp_zoomed_x
= this.zoomed_x_
;
2632 // Tell PlotKit to use this new data and render itself
2633 this.zoomed_x_
= tmp_zoomed_x
;
2634 this.layout_
.evaluate();
2635 this.renderGraph_(is_initial_draw
);
2637 if (this.getStringOption("timingName")) {
2638 var end
= new Date();
2639 console
.log(this.getStringOption("timingName") + " - drawGraph: " + (end
- start
) + "ms");
2644 * This does the work of drawing the chart. It assumes that the layout and axis
2645 * scales have already been set (e.g. by predraw_).
2649 Dygraph
.prototype.renderGraph_
= function(is_initial_draw
) {
2650 this.cascadeEvents_('clearChart');
2651 this.plotter_
.clear();
2653 if (this.getFunctionOption('underlayCallback')) {
2654 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2655 // users who expect a deprecated form of this callback.
2656 this.getFunctionOption('underlayCallback').call(this,
2657 this.hidden_ctx_
, this.layout_
.getPlotArea(), this, this);
2661 canvas
: this.hidden_
,
2662 drawingContext
: this.hidden_ctx_
2664 this.cascadeEvents_('willDrawChart', e
);
2665 this.plotter_
.render();
2666 this.cascadeEvents_('didDrawChart', e
);
2667 this.lastRow_
= -1; // because plugins/legend.js clears the legend
2669 // TODO(danvk): is this a performance bottleneck when panning?
2670 // The interaction canvas should already be empty in that situation.
2671 this.canvas_
.getContext('2d').clearRect(0, 0, this.width_
, this.height_
);
2673 if (this.getFunctionOption("drawCallback") !== null) {
2674 this.getFunctionOption("drawCallback")(this, is_initial_draw
);
2676 if (is_initial_draw
) {
2677 this.readyFired_
= true;
2678 while (this.readyFns_
.length
> 0) {
2679 var fn
= this.readyFns_
.pop();
2687 * Determine properties of the y-axes which are independent of the data
2688 * currently being displayed. This includes things like the number of axes and
2689 * the style of the axes. It does not include the range of each axis and its
2691 * This fills in this.axes_.
2692 * axes_ = [ { options } ]
2693 * indices are into the axes_ array.
2695 Dygraph
.prototype.computeYAxes_
= function() {
2696 // Preserve valueWindow settings if they exist, and if the user hasn't
2697 // specified a new valueRange.
2698 var valueWindows
, axis
, index
, opts
, v
;
2699 if (this.axes_
!== undefined
&& this.user_attrs_
.hasOwnProperty("valueRange") === false) {
2701 for (index
= 0; index
< this.axes_
.length
; index
++) {
2702 valueWindows
.push(this.axes_
[index
].valueWindow
);
2706 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2707 // data computation as well as options storage.
2708 // Go through once and add all the axes.
2711 for (axis
= 0; axis
< this.attributes_
.numAxes(); axis
++) {
2712 // Add a new axis, making a copy of its per-axis options.
2713 opts
= { g
: this };
2714 Dygraph
.update(opts
, this.attributes_
.axisOptions(axis
));
2715 this.axes_
[axis
] = opts
;
2719 // Copy global valueRange option over to the first axis.
2720 // NOTE(konigsberg): Are these two statements necessary?
2721 // I tried removing it. The automated tests pass, and manually
2722 // messing with tests/zoom
.html showed no trouble
.
2723 v
= this.attr_('valueRange');
2724 if (v
) this.axes_
[0].valueRange
= v
;
2726 if (valueWindows
!== undefined
) {
2727 // Restore valueWindow settings.
2729 // When going from two axes back to one, we only restore
2731 var idxCount
= Math
.min(valueWindows
.length
, this.axes_
.length
);
2733 for (index
= 0; index
< idxCount
; index
++) {
2734 this.axes_
[index
].valueWindow
= valueWindows
[index
];
2738 for (axis
= 0; axis
< this.axes_
.length
; axis
++) {
2740 opts
= this.optionsViewForAxis_('y' + (axis
? '2' : ''));
2741 v
= opts("valueRange");
2742 if (v
) this.axes_
[axis
].valueRange
= v
;
2743 } else { // To keep old behavior
2744 var axes
= this.user_attrs_
.axes
;
2745 if (axes
&& axes
.y2
) {
2746 v
= axes
.y2
.valueRange
;
2747 if (v
) this.axes_
[axis
].valueRange
= v
;
2754 * Returns the number of y-axes on the chart.
2755 * @return {number} the number of axes.
2757 Dygraph
.prototype.numAxes
= function() {
2758 return this.attributes_
.numAxes();
2763 * Returns axis properties for the given series.
2764 * @param {string} setName The name of the series for which to get axis
2765 * properties, e.g. 'Y1'.
2766 * @return {Object} The axis properties.
2768 Dygraph
.prototype.axisPropertiesForSeries
= function(series
) {
2769 // TODO(danvk): handle errors.
2770 return this.axes_
[this.attributes_
.axisForSeries(series
)];
2775 * Determine the value range and tick marks for each axis.
2776 * @param {Object} extremes A mapping from seriesName -> [low, high]
2777 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2779 Dygraph
.prototype.computeYAxisRanges_
= function(extremes
) {
2780 var isNullUndefinedOrNaN
= function(num
) {
2781 return isNaN(parseFloat(num
));
2783 var numAxes
= this.attributes_
.numAxes();
2784 var ypadCompat
, span
, series
, ypad
;
2788 // Compute extreme values, a span and tick marks for each axis.
2789 for (var i
= 0; i
< numAxes
; i
++) {
2790 var axis
= this.axes_
[i
];
2791 var logscale
= this.attributes_
.getForAxis("logscale", i
);
2792 var includeZero
= this.attributes_
.getForAxis("includeZero", i
);
2793 var independentTicks
= this.attributes_
.getForAxis("independentTicks", i
);
2794 series
= this.attributes_
.seriesForAxis(i
);
2796 // Add some padding. This supports two Y padding operation modes:
2798 // - backwards compatible (yRangePad not set):
2799 // 10% padding for automatic Y ranges, but not for user-supplied
2800 // ranges, and move a close-to-zero edge to zero except if
2801 // avoidMinZero is set, since drawing at the edge results in
2802 // invisible lines. Unfortunately lines drawn at the edge of a
2803 // user-supplied range will still be invisible. If logscale is
2804 // set, add a variable amount of padding at the top but
2805 // none at the bottom.
2807 // - new-style (yRangePad set by the user):
2808 // always add the specified Y padding.
2811 ypad
= 0.1; // add 10%
2812 if (this.getNumericOption('yRangePad') !== null) {
2814 // Convert pixel padding to ratio
2815 ypad
= this.getNumericOption('yRangePad') / this.plotter_
.area
.h
;
2818 if (series
.length
=== 0) {
2819 // If no series are defined or visible then use a reasonable default
2820 axis
.extremeRange
= [0, 1];
2822 // Calculate the extremes of extremes.
2823 var minY
= Infinity
; // extremes[series[0]][0];
2824 var maxY
= -Infinity
; // extremes[series[0]][1];
2825 var extremeMinY
, extremeMaxY
;
2827 for (var j
= 0; j
< series
.length
; j
++) {
2828 // this skips invisible series
2829 if (!extremes
.hasOwnProperty(series
[j
])) continue;
2831 // Only use valid extremes to stop null data series' from corrupting the scale.
2832 extremeMinY
= extremes
[series
[j
]][0];
2833 if (extremeMinY
!== null) {
2834 minY
= Math
.min(extremeMinY
, minY
);
2836 extremeMaxY
= extremes
[series
[j
]][1];
2837 if (extremeMaxY
!== null) {
2838 maxY
= Math
.max(extremeMaxY
, maxY
);
2842 // Include zero if requested by the user.
2843 if (includeZero
&& !logscale
) {
2844 if (minY
> 0) minY
= 0;
2845 if (maxY
< 0) maxY
= 0;
2848 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2849 if (minY
== Infinity
) minY
= 0;
2850 if (maxY
== -Infinity
) maxY
= 1;
2853 // special case: if we have no sense of scale, center on the sole value.
2856 span
= Math
.abs(maxY
);
2858 // ... and if the sole value is zero, use range 0-1.
2864 var maxAxisY
, minAxisY
;
2867 maxAxisY
= maxY
+ ypad
* span
;
2870 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2871 maxAxisY
= maxY
* logpad
;
2872 minAxisY
= minY
/ logpad
;
2875 maxAxisY
= maxY
+ ypad
* span
;
2876 minAxisY
= minY
- ypad
* span
;
2878 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2879 // close to zero, but not if avoidMinZero is set.
2880 if (ypadCompat
&& !this.getBooleanOption("avoidMinZero")) {
2881 if (minAxisY
< 0 && minY
>= 0) minAxisY
= 0;
2882 if (maxAxisY
> 0 && maxY
<= 0) maxAxisY
= 0;
2885 axis
.extremeRange
= [minAxisY
, maxAxisY
];
2887 if (axis
.valueWindow
) {
2888 // This is only set if the user has zoomed on the y-axis. It is never set
2889 // by a user. It takes precedence over axis.valueRange because, if you set
2890 // valueRange, you'd still expect to be able to pan.
2891 axis
.computedValueRange
= [axis
.valueWindow
[0], axis
.valueWindow
[1]];
2892 } else if (axis
.valueRange
) {
2893 // This is a user-set value range for this axis.
2894 var y0
= isNullUndefinedOrNaN(axis
.valueRange
[0]) ? axis
.extremeRange
[0] : axis
.valueRange
[0];
2895 var y1
= isNullUndefinedOrNaN(axis
.valueRange
[1]) ? axis
.extremeRange
[1] : axis
.valueRange
[1];
2897 if (axis
.logscale
) {
2898 var logpad
= Math
.exp(Math
.log(span
) * ypad
);
2907 axis
.computedValueRange
= [y0
, y1
];
2909 axis
.computedValueRange
= axis
.extremeRange
;
2913 if (independentTicks
) {
2914 axis
.independentTicks
= independentTicks
;
2915 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2916 var ticker
= opts('ticker');
2917 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2918 axis
.computedValueRange
[1],
2919 this.plotter_
.area
.h
,
2922 // Define the first independent axis as primary axis.
2923 if (!p_axis
) p_axis
= axis
;
2926 if (p_axis
=== undefined
) {
2927 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
2929 // Add ticks. By default, all axes inherit the tick positions of the
2930 // primary axis. However, if an axis is specifically marked as having
2931 // independent ticks, then that is permissible as well.
2932 for (var i
= 0; i
< numAxes
; i
++) {
2933 var axis
= this.axes_
[i
];
2935 if (!axis
.independentTicks
) {
2936 var opts
= this.optionsViewForAxis_('y' + (i
? '2' : ''));
2937 var ticker
= opts('ticker');
2938 var p_ticks
= p_axis
.ticks
;
2939 var p_scale
= p_axis
.computedValueRange
[1] - p_axis
.computedValueRange
[0];
2940 var scale
= axis
.computedValueRange
[1] - axis
.computedValueRange
[0];
2941 var tick_values
= [];
2942 for (var k
= 0; k
< p_ticks
.length
; k
++) {
2943 var y_frac
= (p_ticks
[k
].v
- p_axis
.computedValueRange
[0]) / p_scale
;
2944 var y_val
= axis
.computedValueRange
[0] + y_frac
* scale
;
2945 tick_values
.push(y_val
);
2948 axis
.ticks
= ticker(axis
.computedValueRange
[0],
2949 axis
.computedValueRange
[1],
2950 this.plotter_
.area
.h
,
2959 * Detects the type of the str (date or numeric) and sets the various
2960 * formatting attributes in this.attrs_ based on this type.
2961 * @param {string} str An x value.
2964 Dygraph
.prototype.detectTypeFromString_
= function(str
) {
2966 var dashPos
= str
.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2967 if ((dashPos
> 0 && (str
[dashPos
-1] != 'e' && str
[dashPos
-1] != 'E')) ||
2968 str
.indexOf('/') >= 0 ||
2969 isNaN(parseFloat(str
))) {
2971 } else if (str
.length
== 8 && str
> '19700101' && str
< '20371231') {
2972 // TODO(danvk): remove support for this format.
2976 this.setXAxisOptions_(isDate
);
2979 Dygraph
.prototype.setXAxisOptions_
= function(isDate
) {
2981 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
2982 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateValueFormatter
;
2983 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
2984 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisLabelFormatter
;
2986 /** @private (shut up, jsdoc!) */
2987 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
2988 // TODO(danvk): use Dygraph.numberValueFormatter here?
2989 /** @private (shut up, jsdoc!) */
2990 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
2991 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
2992 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
2998 * Parses a string in a special csv format. We expect a csv file where each
2999 * line is a date point, and the first field in each line is the date string.
3000 * We also expect that all remaining fields represent series.
3001 * if the errorBars attribute is set, then interpret the fields as:
3002 * date, series1, stddev1, series2, stddev2, ...
3003 * @param {[Object]} data See above.
3005 * @return [Object] An array with one entry for each row. These entries
3006 * are an array of cells in that row. The first entry is the parsed x-value for
3007 * the row. The second, third, etc. are the y-values. These can take on one of
3008 * three forms, depending on the CSV and constructor parameters:
3010 * 2. [ value, stddev ]
3011 * 3. [ low value, center value, high value ]
3013 Dygraph
.prototype.parseCSV_
= function(data
) {
3015 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3016 var lines
= data
.split(line_delimiter
|| "\n");
3019 // Use the default delimiter or fall back to a tab if that makes sense.
3020 var delim
= this.getStringOption('delimiter');
3021 if (lines
[0].indexOf(delim
) == -1 && lines
[0].indexOf('\t') >= 0) {
3026 if (!('labels' in this.user_attrs_
)) {
3027 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3029 this.attrs_
.labels
= lines
[0].split(delim
); // NOTE: _not_ user_attrs_.
3030 this.attributes_
.reparseSeries();
3035 var defaultParserSet
= false; // attempt to auto-detect x value type
3036 var expectedCols
= this.attr_("labels").length
;
3037 var outOfOrder
= false;
3038 for (var i
= start
; i
< lines
.length
; i
++) {
3039 var line
= lines
[i
];
3041 if (line
.length
=== 0) continue; // skip blank lines
3042 if (line
[0] == '#') continue; // skip comment lines
3043 var inFields
= line
.split(delim
);
3044 if (inFields
.length
< 2) continue;
3047 if (!defaultParserSet
) {
3048 this.detectTypeFromString_(inFields
[0]);
3049 xParser
= this.getFunctionOption("xValueParser");
3050 defaultParserSet
= true;
3052 fields
[0] = xParser(inFields
[0], this);
3054 // If fractions are expected, parse the numbers as "A/B
"
3055 if (this.fractions_) {
3056 for (j = 1; j < inFields.length; j++) {
3057 // TODO(danvk): figure out an appropriate way to flag parse errors.
3058 vals = inFields[j].split("/");
3059 if (vals.length != 2) {
3060 console.error('Expected fractional "num
/den
" values in CSV data ' +
3061 "but found a value
'" + inFields[j] + "' on line
" +
3062 (1 + i) + " ('" + line + "') which is not of
this form
.");
3065 fields[j] = [Dygraph.parseFloat_(vals[0], i, line),
3066 Dygraph.parseFloat_(vals[1], i, line)];
3069 } else if (this.getBooleanOption("errorBars
")) {
3070 // If there are error bars, values are (value, stddev) pairs
3071 if (inFields.length % 2 != 1) {
3072 console.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3073 'but line ' + (1 + i) + ' has an odd number of values (' +
3074 (inFields.length - 1) + "): '" + line + "'");
3076 for (j = 1; j < inFields.length; j += 2) {
3077 fields[(j + 1) / 2] = [Dygraph.parseFloat_(inFields[j], i, line),
3078 Dygraph.parseFloat_(inFields[j + 1], i, line)];
3080 } else if (this.getBooleanOption("customBars
")) {
3081 // Bars are a low;center;high tuple
3082 for (j = 1; j < inFields.length; j++) {
3083 var val = inFields[j];
3084 if (/^ *$/.test(val)) {
3085 fields[j] = [null, null, null];
3087 vals = val.split(";");
3088 if (vals.length == 3) {
3089 fields[j] = [ Dygraph.parseFloat_(vals[0], i, line),
3090 Dygraph.parseFloat_(vals[1], i, line),
3091 Dygraph.parseFloat_(vals[2], i, line) ];
3093 console.warn('When using customBars, values must be either blank ' +
3094 'or "low
;center
;high
" tuples (got "' + val +
3095 '" on line ' + (1+i));
3100 // Values are just numbers
3101 for (j = 1; j < inFields.length; j++) {
3102 fields[j] = Dygraph.parseFloat_(inFields[j], i, line);
3105 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3109 if (fields.length != expectedCols) {
3110 console.error("Number of columns
in line
" + i + " (" + fields.length +
3111 ") does not agree
with number of
labels (" + expectedCols +
3115 // If the user specified the 'labels' option and none of the cells of the
3116 // first row parsed correctly, then they probably double-specified the
3117 // labels. We go with the values set in the option, discard this row and
3118 // log a warning to the JS console.
3119 if (i === 0 && this.attr_('labels')) {
3120 var all_null = true;
3121 for (j = 0; all_null && j < fields.length; j++) {
3122 if (fields[j]) all_null = false;
3125 console.warn("The dygraphs
'labels' option is set
, but the first row
" +
3126 "of CSV
data ('" + line + "') appears to also contain
" +
3127 "labels
. Will drop the CSV labels and
use the option
" +
3136 console.warn("CSV is out of order
; order it correctly to speed loading
.");
3137 ret.sort(function(a,b) { return a[0] - b[0]; });
3144 * The user has provided their data as a pre-packaged JS array. If the x values
3145 * are numeric, this is the same as dygraphs' internal format. If the x values
3146 * are dates, we need to convert them from Date objects to ms since epoch.
3147 * @param {!Array} data
3148 * @return {Object} data with numeric x values.
3151 Dygraph.prototype.parseArray_ = function(data) {
3152 // Peek at the first x value to see if it's numeric.
3153 if (data.length === 0) {
3154 console.error("Can
't plot empty data set");
3157 if (data[0].length === 0) {
3158 console.error("Data set cannot contain an empty row");
3163 if (this.attr_("labels") === null) {
3164 console.warn("Using default labels. Set labels explicitly via 'labels
' " +
3165 "in the options parameter");
3166 this.attrs_.labels = [ "X" ];
3167 for (i = 1; i < data[0].length; i++) {
3168 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
3170 this.attributes_.reparseSeries();
3172 var num_labels = this.attr_("labels");
3173 if (num_labels.length != data[0].length) {
3174 console.error("Mismatch between number of labels (" + num_labels + ")" +
3175 " and number of columns in array (" + data[0].length + ")");
3180 if (Dygraph.isDateLike(data[0][0])) {
3181 // Some intelligent defaults for a date x-axis.
3182 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
3183 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3184 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
3186 // Assume they're all dates
.
3187 var parsedData
= Dygraph
.clone(data
);
3188 for (i
= 0; i
< data
.length
; i
++) {
3189 if (parsedData
[i
].length
=== 0) {
3190 console
.error("Row " + (1 + i
) + " of data is empty");
3193 if (parsedData
[i
][0] === null ||
3194 typeof(parsedData
[i
][0].getTime
) != 'function' ||
3195 isNaN(parsedData
[i
][0].getTime())) {
3196 console
.error("x value in row " + (1 + i
) + " is not a Date");
3199 parsedData
[i
][0] = parsedData
[i
][0].getTime();
3203 // Some intelligent defaults for a numeric x-axis.
3204 /** @private (shut up, jsdoc!) */
3205 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3206 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
3207 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.numberAxisLabelFormatter
;
3213 * Parses a DataTable object from gviz.
3214 * The data is expected to have a first column that is either a date or a
3215 * number. All subsequent columns must be numbers. If there is a clear mismatch
3216 * between this.xValueParser_ and the type of the first column, it will be
3217 * fixed. Fills out rawData_.
3218 * @param {!google.visualization.DataTable} data See above.
3221 Dygraph
.prototype.parseDataTable_
= function(data
) {
3222 var shortTextForAnnotationNum
= function(num
) {
3223 // converts [0-9]+ [A-Z][a-z]*
3224 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3225 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3226 var shortText
= String
.fromCharCode(65 /* A */ + num
% 26);
3227 num
= Math
.floor(num
/ 26);
3229 shortText
= String
.fromCharCode(65 /* A */ + (num
- 1) % 26 ) + shortText
.toLowerCase();
3230 num
= Math
.floor((num
- 1) / 26);
3235 var cols
= data
.getNumberOfColumns();
3236 var rows
= data
.getNumberOfRows();
3238 var indepType
= data
.getColumnType(0);
3239 if (indepType
== 'date' || indepType
== 'datetime') {
3240 this.attrs_
.xValueParser
= Dygraph
.dateParser
;
3241 this.attrs_
.axes
.x
.valueFormatter
= Dygraph
.dateValueFormatter
;
3242 this.attrs_
.axes
.x
.ticker
= Dygraph
.dateTicker
;
3243 this.attrs_
.axes
.x
.axisLabelFormatter
= Dygraph
.dateAxisLabelFormatter
;
3244 } else if (indepType
== 'number') {
3245 this.attrs_
.xValueParser
= function(x
) { return parseFloat(x
); };
3246 this.attrs_
.axes
.x
.valueFormatter
= function(x
) { return x
; };
3247 this.attrs_
.axes
.x
.ticker
= Dygraph
.numericTicks
;
3248 this.attrs_
.axes
.x
.axisLabelFormatter
= this.attrs_
.axes
.x
.valueFormatter
;
3251 "only 'date', 'datetime' and 'number' types are supported " +
3252 "for column 1 of DataTable input (Got '" + indepType
+ "')");
3255 // Array of the column indices which contain data (and not annotations).
3257 var annotationCols
= {}; // data index -> [annotation cols]
3258 var hasAnnotations
= false;
3260 for (i
= 1; i
< cols
; i
++) {
3261 var type
= data
.getColumnType(i
);
3262 if (type
== 'number') {
3264 } else if (type
== 'string' && this.getBooleanOption('displayAnnotations')) {
3265 // This is OK -- it's an annotation column.
3266 var dataIdx
= colIdx
[colIdx
.length
- 1];
3267 if (!annotationCols
.hasOwnProperty(dataIdx
)) {
3268 annotationCols
[dataIdx
] = [i
];
3270 annotationCols
[dataIdx
].push(i
);
3272 hasAnnotations
= true;
3275 "Only 'number' is supported as a dependent type with Gviz." +
3276 " 'string' is only supported if displayAnnotations is true");
3280 // Read column labels
3281 // TODO(danvk): add support back for errorBars
3282 var labels
= [data
.getColumnLabel(0)];
3283 for (i
= 0; i
< colIdx
.length
; i
++) {
3284 labels
.push(data
.getColumnLabel(colIdx
[i
]));
3285 if (this.getBooleanOption("errorBars")) i
+= 1;
3287 this.attrs_
.labels
= labels
;
3288 cols
= labels
.length
;
3291 var outOfOrder
= false;
3292 var annotations
= [];
3293 for (i
= 0; i
< rows
; i
++) {
3295 if (typeof(data
.getValue(i
, 0)) === 'undefined' ||
3296 data
.getValue(i
, 0) === null) {
3297 console
.warn("Ignoring row " + i
+
3298 " of DataTable because of undefined or null first column.");
3302 if (indepType
== 'date' || indepType
== 'datetime') {
3303 row
.push(data
.getValue(i
, 0).getTime());
3305 row
.push(data
.getValue(i
, 0));
3307 if (!this.getBooleanOption("errorBars")) {
3308 for (j
= 0; j
< colIdx
.length
; j
++) {
3309 var col
= colIdx
[j
];
3310 row
.push(data
.getValue(i
, col
));
3311 if (hasAnnotations
&&
3312 annotationCols
.hasOwnProperty(col
) &&
3313 data
.getValue(i
, annotationCols
[col
][0]) !== null) {
3315 ann
.series
= data
.getColumnLabel(col
);
3317 ann
.shortText
= shortTextForAnnotationNum(annotations
.length
);
3319 for (var k
= 0; k
< annotationCols
[col
].length
; k
++) {
3320 if (k
) ann
.text
+= "\n";
3321 ann
.text
+= data
.getValue(i
, annotationCols
[col
][k
]);
3323 annotations
.push(ann
);
3327 // Strip out infinities, which give dygraphs problems later on.
3328 for (j
= 0; j
< row
.length
; j
++) {
3329 if (!isFinite(row
[j
])) row
[j
] = null;
3332 for (j
= 0; j
< cols
- 1; j
++) {
3333 row
.push([ data
.getValue(i
, 1 + 2 * j
), data
.getValue(i
, 2 + 2 * j
) ]);
3336 if (ret
.length
> 0 && row
[0] < ret
[ret
.length
- 1][0]) {
3343 console
.warn("DataTable is out of order; order it correctly to speed loading.");
3344 ret
.sort(function(a
,b
) { return a
[0] - b
[0]; });
3346 this.rawData_
= ret
;
3348 if (annotations
.length
> 0) {
3349 this.setAnnotations(annotations
, true);
3351 this.attributes_
.reparseSeries();
3355 * Signals to plugins that the chart data has updated.
3356 * This happens after the data has updated but before the chart has redrawn.
3358 Dygraph
.prototype.cascadeDataDidUpdateEvent_
= function() {
3359 // TODO(danvk): there are some issues checking xAxisRange() and using
3360 // toDomCoords from handlers of this event. The visible range should be set
3361 // when the chart is drawn, not derived from the data.
3362 this.cascadeEvents_('dataDidUpdate', {});
3366 * Get the CSV data. If it's in a function, call that function. If it's in a
3367 * file, do an XMLHttpRequest to get it.
3370 Dygraph
.prototype.start_
= function() {
3371 var data
= this.file_
;
3373 // Functions can return references of all other types.
3374 if (typeof data
== 'function') {
3378 if (Dygraph
.isArrayLike(data
)) {
3379 this.rawData_
= this.parseArray_(data
);
3380 this.cascadeDataDidUpdateEvent_();
3382 } else if (typeof data
== 'object' &&
3383 typeof data
.getColumnRange
== 'function') {
3384 // must be a DataTable from gviz.
3385 this.parseDataTable_(data
);
3386 this.cascadeDataDidUpdateEvent_();
3388 } else if (typeof data
== 'string') {
3389 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3390 var line_delimiter
= Dygraph
.detectLineDelimiter(data
);
3391 if (line_delimiter
) {
3392 this.loadedEvent_(data
);
3396 if (window
.XMLHttpRequest
) {
3397 // Firefox, Opera, IE7, and other browsers will use the native object
3398 req
= new XMLHttpRequest();
3400 // IE 5 and 6 will use the ActiveX control
3401 req
= new ActiveXObject("Microsoft.XMLHTTP");
3405 req
.onreadystatechange
= function () {
3406 if (req
.readyState
== 4) {
3407 if (req
.status
=== 200 || // Normal http
3408 req
.status
=== 0) { // Chrome w/ --allow
-file
-access
-from
-files
3409 caller
.loadedEvent_(req
.responseText
);
3414 req
.open("GET", data
, true);
3418 console
.error("Unknown data format: " + (typeof data
));
3423 * Changes various properties of the graph. These can include:
3425 * <li>file: changes the source data for the graph</li>
3426 * <li>errorBars: changes whether the data contains stddev</li>
3429 * There's a huge variety of options that can be passed to this method. For a
3430 * full list, see http://dygraphs.com/options.html.
3432 * @param {Object} input_attrs The new properties and values
3433 * @param {boolean} block_redraw Usually the chart is redrawn after every
3434 * call to updateOptions(). If you know better, you can pass true to
3435 * explicitly block the redraw. This can be useful for chaining
3436 * updateOptions() calls, avoiding the occasional infinite loop and
3437 * preventing redraws when it's not necessary (e.g. when updating a
3440 Dygraph
.prototype.updateOptions
= function(input_attrs
, block_redraw
) {
3441 if (typeof(block_redraw
) == 'undefined') block_redraw
= false;
3443 // copyUserAttrs_ drops the "file" parameter as a convenience to us.
3444 var file
= input_attrs
.file
;
3445 var attrs
= Dygraph
.copyUserAttrs_(input_attrs
);
3447 // TODO(danvk): this is a mess. Move these options into attr_.
3448 if ('rollPeriod' in attrs
) {
3449 this.rollPeriod_
= attrs
.rollPeriod
;
3451 if ('dateWindow' in attrs
) {
3452 this.dateWindow_
= attrs
.dateWindow
;
3453 if (!('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3454 this.zoomed_x_
= (attrs
.dateWindow
!== null);
3457 if ('valueRange' in attrs
&& !('isZoomedIgnoreProgrammaticZoom' in attrs
)) {
3458 this.zoomed_y_
= (attrs
.valueRange
!== null);
3461 // TODO(danvk): validate per-series options.
3466 // highlightCircleSize
3468 // Check if this set options will require new points.
3469 var requiresNewPoints
= Dygraph
.isPixelChangingOptionList(this.attr_("labels"), attrs
);
3471 Dygraph
.updateDeep(this.user_attrs_
, attrs
);
3473 this.attributes_
.reparseSeries();
3476 // This event indicates that the data is about to change, but hasn't yet.
3477 // TODO(danvk): support cancelation of the update via this event.
3478 this.cascadeEvents_('dataWillUpdate', {});
3481 if (!block_redraw
) this.start_();
3483 if (!block_redraw
) {
3484 if (requiresNewPoints
) {
3487 this.renderGraph_(false);
3494 * Make a copy of input attributes, removing file as a convenience.
3496 Dygraph
.copyUserAttrs_
= function(attrs
) {
3498 for (var k
in attrs
) {
3499 if (!attrs
.hasOwnProperty(k
)) continue;
3500 if (k
== 'file') continue;
3501 if (attrs
.hasOwnProperty(k
)) my_attrs
[k
] = attrs
[k
];
3507 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3508 * containing div (which has presumably changed size since the dygraph was
3509 * instantiated. If the width/height are specified, the div will be resized.
3511 * This is far more efficient than destroying and re-instantiating a
3512 * Dygraph, since it doesn't have to reparse the underlying data.
3514 * @param {number} width Width (in pixels)
3515 * @param {number} height Height (in pixels)
3517 Dygraph
.prototype.resize
= function(width
, height
) {
3518 if (this.resize_lock
) {
3521 this.resize_lock
= true;
3523 if ((width
=== null) != (height
=== null)) {
3524 console
.warn("Dygraph.resize() should be called with zero parameters or " +
3525 "two non-NULL parameters. Pretending it was zero.");
3526 width
= height
= null;
3529 var old_width
= this.width_
;
3530 var old_height
= this.height_
;
3533 this.maindiv_
.style
.width
= width
+ "px";
3534 this.maindiv_
.style
.height
= height
+ "px";
3535 this.width_
= width
;
3536 this.height_
= height
;
3538 this.width_
= this.maindiv_
.clientWidth
;
3539 this.height_
= this.maindiv_
.clientHeight
;
3542 if (old_width
!= this.width_
|| old_height
!= this.height_
) {
3543 // Resizing a canvas erases it, even when the size doesn't change, so
3544 // any resize needs to be followed by a redraw.
3545 this.resizeElements_();
3549 this.resize_lock
= false;
3553 * Adjusts the number of points in the rolling average. Updates the graph to
3554 * reflect the new averaging period.
3555 * @param {number} length Number of points over which to average the data.
3557 Dygraph
.prototype.adjustRoll
= function(length
) {
3558 this.rollPeriod_
= length
;
3563 * Returns a boolean array of visibility statuses.
3565 Dygraph
.prototype.visibility
= function() {
3566 // Do lazy-initialization, so that this happens after we know the number of
3568 if (!this.getOption("visibility")) {
3569 this.attrs_
.visibility
= [];
3571 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs
.
3572 while (this.getOption("visibility").length
< this.numColumns() - 1) {
3573 this.attrs_
.visibility
.push(true);
3575 return this.getOption("visibility");
3579 * Changes the visibility of one or more series.
3581 * @param {number|number[]} num the series index or an array of series indices
3582 * @param {boolean} value true or false, identifying the visibility.
3584 Dygraph
.prototype.setVisibility
= function(num
, value
) {
3585 var x
= this.visibility();
3587 if (num
.constructor
!== Array
) num
= [num
];
3589 for (var i
= 0; i
< num
.length
; i
++) {
3590 if (num
[i
] < 0 || num
[i
] >= x
.length
) {
3591 console
.warn("invalid series number in setVisibility: " + num
[i
]);
3601 * How large of an area will the dygraph render itself in?
3602 * This is used for testing.
3603 * @return A {width: w, height: h} object.
3606 Dygraph
.prototype.size
= function() {
3607 return { width
: this.width_
, height
: this.height_
};
3611 * Update the list of annotations and redraw the chart.
3612 * See dygraphs.com/annotations.html for more info on how to use annotations.
3613 * @param ann {Array} An array of annotation objects.
3614 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3616 Dygraph
.prototype.setAnnotations
= function(ann
, suppressDraw
) {
3617 // Only add the annotation CSS rule once we know it will be used.
3618 Dygraph
.addAnnotationRule();
3619 this.annotations_
= ann
;
3620 if (!this.layout_
) {
3621 console
.warn("Tried to setAnnotations before dygraph was ready. " +
3622 "Try setting them in a ready() block. See " +
3623 "dygraphs.com/tests/annotation.html");
3627 this.layout_
.setAnnotations(this.annotations_
);
3628 if (!suppressDraw
) {
3634 * Return the list of annotations.
3636 Dygraph
.prototype.annotations
= function() {
3637 return this.annotations_
;
3641 * Get the list of label names for this graph. The first column is the
3642 * x-axis, so the data series names start at index 1.
3644 * Returns null when labels have not yet been defined.
3646 Dygraph
.prototype.getLabels
= function() {
3647 var labels
= this.attr_("labels");
3648 return labels
? labels
.slice() : null;
3652 * Get the index of a series (column) given its name. The first column is the
3653 * x-axis, so the data series start with index 1.
3655 Dygraph
.prototype.indexFromSetName
= function(name
) {
3656 return this.setIndexByName_
[name
];
3660 * Find the row number corresponding to the given x-value.
3661 * Returns null if there is no such x-value in the data.
3662 * If there are multiple rows with the same x-value, this will return the
3664 * @param {number} xVal The x-value to look for (e.g. millis since epoch).
3665 * @return {?number} The row number, which you can pass to getValue(), or null.
3667 Dygraph
.prototype.getRowForX
= function(xVal
) {
3669 high
= this.numRows() - 1;
3671 while (low
<= high
) {
3672 var idx
= (high
+ low
) >> 1;
3673 var x
= this.getValue(idx
, 0);
3676 } else if (x
> xVal
) {
3678 } else if (low
!= idx
) { // equal, but there may be an earlier match.
3689 * Trigger a callback when the dygraph has drawn itself and is ready to be
3690 * manipulated. This is primarily useful when dygraphs has to do an XHR for the
3691 * data (i.e. a URL is passed as the data source) and the chart is drawn
3692 * asynchronously. If the chart has already drawn, the callback will fire
3695 * This is a good place to call setAnnotation().
3697 * @param {function(!Dygraph)} callback The callback to trigger when the chart
3700 Dygraph
.prototype.ready
= function(callback
) {
3701 if (this.is_initial_draw_
) {
3702 this.readyFns_
.push(callback
);
3704 callback
.call(this, this);
3710 * Adds a default style for the annotation CSS classes to the document. This is
3711 * only executed when annotations are actually used. It is designed to only be
3712 * called once -- all calls after the first will return immediately.
3714 Dygraph
.addAnnotationRule
= function() {
3715 // TODO(danvk): move this function into plugins/annotations.js
?
3716 if (Dygraph
.addedAnnotationCSS
) return;
3718 var rule
= "border: 1px solid black; " +
3719 "background-color: white; " +
3720 "text-align: center;";
3722 var styleSheetElement
= document
.createElement("style");
3723 styleSheetElement
.type
= "text/css";
3724 document
.getElementsByTagName("head")[0].appendChild(styleSheetElement
);
3726 // Find the first style sheet that we can access.
3727 // We may not add a rule to a style sheet from another domain for security
3728 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3729 // adds its own style sheets from google.com.
3730 for (var i
= 0; i
< document
.styleSheets
.length
; i
++) {
3731 if (document
.styleSheets
[i
].disabled
) continue;
3732 var mysheet
= document
.styleSheets
[i
];
3734 if (mysheet
.insertRule
) { // Firefox
3735 var idx
= mysheet
.cssRules
? mysheet
.cssRules
.length
: 0;
3736 mysheet
.insertRule(".dygraphDefaultAnnotation { " + rule
+ " }", idx
);
3737 } else if (mysheet
.addRule
) { // IE
3738 mysheet
.addRule(".dygraphDefaultAnnotation", rule
);
3740 Dygraph
.addedAnnotationCSS
= true;
3743 // Was likely a security exception.
3747 console
.warn("Unable to add default annotation CSS rule; display may be off.");
3750 if (typeof exports
=== "object" && typeof module
!== "undefined") {
3751 module
.exports
= Dygraph
;