Provide local test execution by function reference, which is much
[dygraphs.git] / dygraph.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
5 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
6 * string. Dygraph can handle multiple series with or without error bars. The
7 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
8 * <canvas> tag, so it only works in FF1.5+.
9 * @author danvdk@gmail.com (Dan Vanderkam)
10
11 Usage:
12 <div id="graphdiv" style="width:800px; height:500px;"></div>
13 <script type="text/javascript">
285a6bda
DV
14 new Dygraph(document.getElementById("graphdiv"),
15 "datafile.csv", // CSV file with headers
16 { }); // options
6a1aa64f
DV
17 </script>
18
19 The CSV file is of the form
20
285a6bda 21 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
22 YYYYMMDD,A1,B1,C1
23 YYYYMMDD,A2,B2,C2
24
6a1aa64f
DV
25 If the 'errorBars' option is set in the constructor, the input should be of
26 the form
285a6bda 27 Date,SeriesA,SeriesB,...
6a1aa64f
DV
28 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
29 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
30
31 If the 'fractions' option is set, the input should be of the form:
32
285a6bda 33 Date,SeriesA,SeriesB,...
6a1aa64f
DV
34 YYYYMMDD,A1/B1,A2/B2,...
35 YYYYMMDD,A1/B1,A2/B2,...
36
37 And error bars will be calculated automatically using a binomial distribution.
38
727439b4 39 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
40
41 */
42
43/**
629a09ae
DV
44 * Creates an interactive, zoomable chart.
45 *
46 * @constructor
47 * @param {div | String} div A div or the id of a div into which to construct
48 * the chart.
49 * @param {String | Function} file A file containing CSV data or a function
50 * that returns this data. The most basic expected format for each line is
51 * "YYYY/MM/DD,val1,val2,...". For more information, see
52 * http://dygraphs.com/data.html.
6a1aa64f 53 * @param {Object} attrs Various other attributes, e.g. errorBars determines
629a09ae
DV
54 * whether the input data contains error ranges. For a complete list of
55 * options, see http://dygraphs.com/options.html.
6a1aa64f 56 */
285a6bda
DV
57Dygraph = function(div, data, opts) {
58 if (arguments.length > 0) {
59 if (arguments.length == 4) {
60 // Old versions of dygraphs took in the series labels as a constructor
61 // parameter. This doesn't make sense anymore, but it's easy to continue
62 // to support this usage.
63 this.warn("Using deprecated four-argument dygraph constructor");
64 this.__old_init__(div, data, arguments[2], arguments[3]);
65 } else {
66 this.__init__(div, data, opts);
67 }
68 }
6a1aa64f
DV
69};
70
285a6bda
DV
71Dygraph.NAME = "Dygraph";
72Dygraph.VERSION = "1.2";
73Dygraph.__repr__ = function() {
6a1aa64f
DV
74 return "[" + this.NAME + " " + this.VERSION + "]";
75};
629a09ae
DV
76
77/**
78 * Returns information about the Dygraph class.
79 */
285a6bda 80Dygraph.toString = function() {
6a1aa64f
DV
81 return this.__repr__();
82};
83
84// Various default values
285a6bda
DV
85Dygraph.DEFAULT_ROLL_PERIOD = 1;
86Dygraph.DEFAULT_WIDTH = 480;
87Dygraph.DEFAULT_HEIGHT = 320;
6a1aa64f 88
8e4a6af3 89// Default attribute values.
285a6bda 90Dygraph.DEFAULT_ATTRS = {
a9fc39ab 91 highlightCircleSize: 3,
8e4a6af3 92 pixelsPerXLabel: 60,
c6336f04 93 pixelsPerYLabel: 30,
285a6bda 94
8e4a6af3
DV
95 labelsDivWidth: 250,
96 labelsDivStyles: {
97 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
98 },
99 labelsSeparateLines: false,
bcd3ebf0 100 labelsShowZeroValues: true,
285a6bda 101 labelsKMB: false,
afefbcdb 102 labelsKMG2: false,
d160cc3b 103 showLabelsOnHighlight: true,
12e4c741 104
2e1fcf1a
DV
105 yValueFormatter: function(a,b) { return Dygraph.numberFormatter(a,b); },
106 digitsAfterDecimal: 2,
107 maxNumberWidth: 6,
19589a3e 108 sigFigs: null,
285a6bda
DV
109
110 strokeWidth: 1.0,
8e4a6af3 111
8846615a
DV
112 axisTickSize: 3,
113 axisLabelFontSize: 14,
114 xAxisLabelWidth: 50,
115 yAxisLabelWidth: 50,
bf640e56 116 xAxisLabelFormatter: Dygraph.dateAxisFormatter,
8846615a 117 rightGap: 5,
285a6bda
DV
118
119 showRoller: false,
120 xValueFormatter: Dygraph.dateString_,
121 xValueParser: Dygraph.dateParser,
122 xTicker: Dygraph.dateTicker,
123
3d67f03b
DV
124 delimiter: ',',
125
285a6bda
DV
126 sigma: 2.0,
127 errorBars: false,
128 fractions: false,
129 wilsonInterval: true, // only relevant if fractions is true
5954ef32 130 customBars: false,
43af96e7
NK
131 fillGraph: false,
132 fillAlpha: 0.15,
f032c51d 133 connectSeparatedPoints: false,
43af96e7
NK
134
135 stackedGraph: false,
afdc483f
NN
136 hideOverlayOnMouseOut: true,
137
2fccd3dc
DV
138 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
139 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
140
00c281d4 141 stepPlot: false,
062ef401
JB
142 avoidMinZero: false,
143
ad1798c2 144 // Sizes of the various chart labels.
b4202b3d 145 titleHeight: 28,
86cce9e8
DV
146 xLabelHeight: 18,
147 yLabelWidth: 18,
ad1798c2 148
423f5ed3
DV
149 drawXAxis: true,
150 drawYAxis: true,
151 axisLineColor: "black",
990d6a35
DV
152 axisLineWidth: 0.3,
153 gridLineWidth: 0.3,
154 axisLabelColor: "black",
155 axisLabelFont: "Arial", // TODO(danvk): is this implemented?
156 axisLabelWidth: 50,
157 drawYGrid: true,
158 drawXGrid: true,
159 gridLineColor: "rgb(128,128,128)",
423f5ed3 160
846f3d2d 161 interactionModel: null // will be set to Dygraph.Interaction.defaultModel
285a6bda
DV
162};
163
39b0e098
RK
164// Directions for panning and zooming. Use bit operations when combined
165// values are possible.
166Dygraph.HORIZONTAL = 1;
167Dygraph.VERTICAL = 2;
168
5c528fa2
DV
169// Used for initializing annotation CSS rules only once.
170Dygraph.addedAnnotationCSS = false;
171
285a6bda
DV
172Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
173 // Labels is no longer a constructor parameter, since it's typically set
174 // directly from the data source. It also conains a name for the x-axis,
175 // which the previous constructor form did not.
176 if (labels != null) {
177 var new_labels = ["Date"];
178 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 179 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
180 }
181 this.__init__(div, file, attrs);
8e4a6af3
DV
182};
183
6a1aa64f 184/**
285a6bda 185 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
7aedf6fe 186 * and context &lt;canvas&gt; inside of it. See the constructor for details.
6a1aa64f 187 * on the parameters.
12e4c741 188 * @param {Element} div the Element to render the graph into.
6a1aa64f 189 * @param {String | Function} file Source data
6a1aa64f
DV
190 * @param {Object} attrs Miscellaneous other options
191 * @private
192 */
285a6bda 193Dygraph.prototype.__init__ = function(div, file, attrs) {
a2c8fff4
DV
194 // Hack for IE: if we're using excanvas and the document hasn't finished
195 // loading yet (and hence may not have initialized whatever it needs to
196 // initialize), then keep calling this routine periodically until it has.
197 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
198 typeof(G_vmlCanvasManager) != 'undefined' &&
199 document.readyState != 'complete') {
200 var self = this;
201 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
202 }
203
285a6bda
DV
204 // Support two-argument constructor
205 if (attrs == null) { attrs = {}; }
206
6a1aa64f 207 // Copy the important bits into the object
32988383 208 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 209 this.maindiv_ = div;
6a1aa64f 210 this.file_ = file;
285a6bda 211 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 212 this.previousVerticalX_ = -1;
6a1aa64f 213 this.fractions_ = attrs.fractions || false;
6a1aa64f 214 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 215
6a1aa64f 216 this.wilsonInterval_ = attrs.wilsonInterval || true;
fe0b7c03 217 this.is_initial_draw_ = true;
5c528fa2 218 this.annotations_ = [];
7aedf6fe 219
45f2c689 220 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
57baab03
NN
221 this.zoomed_x_ = false;
222 this.zoomed_y_ = false;
45f2c689 223
f7d6278e
DV
224 // Clear the div. This ensure that, if multiple dygraphs are passed the same
225 // div, then only one will be drawn.
226 div.innerHTML = "";
227
0cb9bd91
DV
228 // For historical reasons, the 'width' and 'height' options trump all CSS
229 // rules _except_ for an explicit 'width' or 'height' on the div.
230 // As an added convenience, if the div has zero height (like <div></div> does
231 // without any styles), then we use a default height/width.
232 if (div.style.width == '' && attrs.width) {
233 div.style.width = attrs.width + "px";
285a6bda 234 }
0cb9bd91
DV
235 if (div.style.height == '' && attrs.height) {
236 div.style.height = attrs.height + "px";
32988383 237 }
fffad740 238 if (div.style.height == '' && div.offsetHeight == 0) {
0cb9bd91
DV
239 div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
240 if (div.style.width == '') {
241 div.style.width = Dygraph.DEFAULT_WIDTH + "px";
242 }
c21d2c2d 243 }
fffad740 244 // these will be zero if the dygraph's div is hidden.
0cb9bd91
DV
245 this.width_ = div.offsetWidth;
246 this.height_ = div.offsetHeight;
32988383 247
344ba8c0 248 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
43af96e7
NK
249 if (attrs['stackedGraph']) {
250 attrs['fillGraph'] = true;
251 // TODO(nikhilk): Add any other stackedGraph checks here.
252 }
253
285a6bda
DV
254 // Dygraphs has many options, some of which interact with one another.
255 // To keep track of everything, we maintain two sets of options:
256 //
c21d2c2d 257 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
258 // this.attrs_ defaults, options derived from user_attrs_, data.
259 //
260 // Options are then accessed this.attr_('attr'), which first looks at
261 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
262 // defaults without overriding behavior that the user specifically asks for.
263 this.user_attrs_ = {};
fc80a396 264 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 265
285a6bda 266 this.attrs_ = {};
fc80a396 267 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 268
16269f6e 269 this.boundaryIds_ = [];
6a1aa64f 270
6a1aa64f
DV
271 // Create the containing DIV and other interactive elements
272 this.createInterface_();
273
738fc797 274 this.start_();
6a1aa64f
DV
275};
276
dcb25130
NN
277/**
278 * Returns the zoomed status of the chart for one or both axes.
279 *
280 * Axis is an optional parameter. Can be set to 'x' or 'y'.
281 *
282 * The zoomed status for an axis is set whenever a user zooms using the mouse
e5152598 283 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
dcb25130
NN
284 * option is also specified).
285 */
57baab03
NN
286Dygraph.prototype.isZoomed = function(axis) {
287 if (axis == null) return this.zoomed_x_ || this.zoomed_y_;
288 if (axis == 'x') return this.zoomed_x_;
289 if (axis == 'y') return this.zoomed_y_;
290 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
291};
292
629a09ae
DV
293/**
294 * Returns information about the Dygraph object, including its containing ID.
295 */
22bd1dfb
RK
296Dygraph.prototype.toString = function() {
297 var maindiv = this.maindiv_;
298 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
299 return "[Dygraph " + id + "]";
300}
301
629a09ae
DV
302/**
303 * @private
304 * Returns the value of an option. This may be set by the user (either in the
305 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
306 * per-series value.
307 * @param { String } name The name of the option, e.g. 'rollPeriod'.
308 * @param { String } [seriesName] The name of the series to which the option
309 * will be applied. If no per-series value of this option is available, then
310 * the global value is returned. This is optional.
311 * @return { ... } The value of the option.
312 */
227b93cc 313Dygraph.prototype.attr_ = function(name, seriesName) {
028ddf8a
DV
314// <REMOVE_FOR_COMBINED>
315 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
316 this.error('Must include options reference JS for testing');
317 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
318 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
319 'in the Dygraphs.OPTIONS_REFERENCE listing.');
320 // Only log this error once.
321 Dygraph.OPTIONS_REFERENCE[name] = true;
322 }
323// </REMOVE_FOR_COMBINED>
227b93cc
DV
324 if (seriesName &&
325 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
326 this.user_attrs_[seriesName] != null &&
327 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
328 return this.user_attrs_[seriesName][name];
450fe64b 329 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
285a6bda
DV
330 return this.user_attrs_[name];
331 } else if (typeof(this.attrs_[name]) != 'undefined') {
332 return this.attrs_[name];
333 } else {
334 return null;
335 }
336};
337
6a1aa64f
DV
338/**
339 * Returns the current rolling period, as set by the user or an option.
6faebb69 340 * @return {Number} The number of points in the rolling window
6a1aa64f 341 */
285a6bda 342Dygraph.prototype.rollPeriod = function() {
6a1aa64f 343 return this.rollPeriod_;
76171648
DV
344};
345
599fb4ad
DV
346/**
347 * Returns the currently-visible x-range. This can be affected by zooming,
348 * panning or a call to updateOptions.
349 * Returns a two-element array: [left, right].
350 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
351 */
352Dygraph.prototype.xAxisRange = function() {
4cac8c7a
RK
353 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
354};
599fb4ad 355
4cac8c7a
RK
356/**
357 * Returns the lower- and upper-bound x-axis values of the
358 * data set.
359 */
360Dygraph.prototype.xAxisExtremes = function() {
599fb4ad
DV
361 var left = this.rawData_[0][0];
362 var right = this.rawData_[this.rawData_.length - 1][0];
363 return [left, right];
364};
365
3230c662 366/**
d58ae307
DV
367 * Returns the currently-visible y-range for an axis. This can be affected by
368 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
369 * called with no arguments, returns the range of the first axis.
3230c662
DV
370 * Returns a two-element array: [bottom, top].
371 */
d58ae307 372Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 373 if (typeof(idx) == "undefined") idx = 0;
d64b8fea
RK
374 if (idx < 0 || idx >= this.axes_.length) {
375 return null;
376 }
377 var axis = this.axes_[idx];
378 return [ axis.computedValueRange[0], axis.computedValueRange[1] ];
d58ae307
DV
379};
380
381/**
382 * Returns the currently-visible y-ranges for each axis. This can be affected by
383 * zooming, panning, calls to updateOptions, etc.
384 * Returns an array of [bottom, top] pairs, one for each y-axis.
385 */
386Dygraph.prototype.yAxisRanges = function() {
387 var ret = [];
388 for (var i = 0; i < this.axes_.length; i++) {
389 ret.push(this.yAxisRange(i));
390 }
391 return ret;
3230c662
DV
392};
393
d58ae307 394// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
395/**
396 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
397 * If specified, do this conversion for the coordinate system of a particular
398 * axis. Uses the first axis by default.
3230c662 399 * Returns a two-element array: [X, Y]
ff022deb 400 *
0747928a 401 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
ff022deb 402 * instead of toDomCoords(null, y, axis).
3230c662 403 */
d58ae307 404Dygraph.prototype.toDomCoords = function(x, y, axis) {
ff022deb
RK
405 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
406};
407
408/**
409 * Convert from data x coordinates to canvas/div X coordinate.
410 * If specified, do this conversion for the coordinate system of a particular
0037b2a4
RK
411 * axis.
412 * Returns a single value or null if x is null.
ff022deb
RK
413 */
414Dygraph.prototype.toDomXCoord = function(x) {
415 if (x == null) {
416 return null;
417 };
418
3230c662 419 var area = this.plotter_.area;
ff022deb
RK
420 var xRange = this.xAxisRange();
421 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
422}
3230c662 423
ff022deb
RK
424/**
425 * Convert from data x coordinates to canvas/div Y coordinate and optional
426 * axis. Uses the first axis by default.
427 *
428 * returns a single value or null if y is null.
429 */
430Dygraph.prototype.toDomYCoord = function(y, axis) {
0747928a 431 var pct = this.toPercentYCoord(y, axis);
3230c662 432
ff022deb
RK
433 if (pct == null) {
434 return null;
435 }
e4416fb9 436 var area = this.plotter_.area;
ff022deb
RK
437 return area.y + pct * area.h;
438}
3230c662
DV
439
440/**
441 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
442 * If specified, do this conversion for the coordinate system of a particular
443 * axis. Uses the first axis by default.
ff022deb
RK
444 * Returns a two-element array: [X, Y].
445 *
0747928a 446 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
ff022deb 447 * instead of toDataCoords(null, y, axis).
3230c662 448 */
d58ae307 449Dygraph.prototype.toDataCoords = function(x, y, axis) {
ff022deb
RK
450 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
451};
452
453/**
454 * Convert from canvas/div x coordinate to data coordinate.
455 *
456 * If x is null, this returns null.
457 */
458Dygraph.prototype.toDataXCoord = function(x) {
459 if (x == null) {
460 return null;
3230c662
DV
461 }
462
ff022deb
RK
463 var area = this.plotter_.area;
464 var xRange = this.xAxisRange();
465 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
466};
467
468/**
469 * Convert from canvas/div y coord to value.
470 *
471 * If y is null, this returns null.
472 * if axis is null, this uses the first axis.
473 */
474Dygraph.prototype.toDataYCoord = function(y, axis) {
475 if (y == null) {
476 return null;
3230c662
DV
477 }
478
ff022deb
RK
479 var area = this.plotter_.area;
480 var yRange = this.yAxisRange(axis);
481
b70247dc
RK
482 if (typeof(axis) == "undefined") axis = 0;
483 if (!this.axes_[axis].logscale) {
d9816e62 484 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
ff022deb
RK
485 } else {
486 // Computing the inverse of toDomCoord.
487 var pct = (y - area.y) / area.h
488
489 // Computing the inverse of toPercentYCoord. The function was arrived at with
490 // the following steps:
491 //
492 // Original calcuation:
d59b6f34 493 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
494 //
495 // Move denominator to both sides:
d59b6f34 496 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
ff022deb
RK
497 //
498 // subtract logr1, and take the negative value.
d59b6f34 499 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
ff022deb
RK
500 //
501 // Swap both sides of the equation, and we can compute the log of the
502 // return value. Which means we just need to use that as the exponent in
503 // e^exponent.
d59b6f34 504 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
ff022deb 505
d59b6f34
RK
506 var logr1 = Dygraph.log10(yRange[1]);
507 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
508 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
ff022deb
RK
509 return value;
510 }
3230c662
DV
511};
512
e99fde05 513/**
ff022deb 514 * Converts a y for an axis to a percentage from the top to the
4cac8c7a 515 * bottom of the drawing area.
ff022deb
RK
516 *
517 * If the coordinate represents a value visible on the canvas, then
518 * the value will be between 0 and 1, where 0 is the top of the canvas.
519 * However, this method will return values outside the range, as
520 * values can fall outside the canvas.
521 *
522 * If y is null, this returns null.
523 * if axis is null, this uses the first axis.
629a09ae
DV
524 *
525 * @param { Number } y The data y-coordinate.
526 * @param { Number } [axis] The axis number on which the data coordinate lives.
527 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
ff022deb
RK
528 */
529Dygraph.prototype.toPercentYCoord = function(y, axis) {
530 if (y == null) {
531 return null;
532 }
7d0e7a0d 533 if (typeof(axis) == "undefined") axis = 0;
ff022deb
RK
534
535 var area = this.plotter_.area;
536 var yRange = this.yAxisRange(axis);
537
538 var pct;
7d0e7a0d 539 if (!this.axes_[axis].logscale) {
4cac8c7a
RK
540 // yRange[1] - y is unit distance from the bottom.
541 // yRange[1] - yRange[0] is the scale of the range.
ff022deb
RK
542 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
543 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
544 } else {
d59b6f34
RK
545 var logr1 = Dygraph.log10(yRange[1]);
546 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
547 }
548 return pct;
549}
550
551/**
4cac8c7a
RK
552 * Converts an x value to a percentage from the left to the right of
553 * the drawing area.
554 *
555 * If the coordinate represents a value visible on the canvas, then
556 * the value will be between 0 and 1, where 0 is the left of the canvas.
557 * However, this method will return values outside the range, as
558 * values can fall outside the canvas.
559 *
560 * If x is null, this returns null.
629a09ae
DV
561 * @param { Number } x The data x-coordinate.
562 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
4cac8c7a
RK
563 */
564Dygraph.prototype.toPercentXCoord = function(x) {
565 if (x == null) {
566 return null;
567 }
568
4cac8c7a 569 var xRange = this.xAxisRange();
965a030e 570 return (x - xRange[0]) / (xRange[1] - xRange[0]);
629a09ae 571};
4cac8c7a
RK
572
573/**
e99fde05 574 * Returns the number of columns (including the independent variable).
629a09ae 575 * @return { Integer } The number of columns.
e99fde05
DV
576 */
577Dygraph.prototype.numColumns = function() {
578 return this.rawData_[0].length;
579};
580
581/**
582 * Returns the number of rows (excluding any header/label row).
629a09ae 583 * @return { Integer } The number of rows, less any header.
e99fde05
DV
584 */
585Dygraph.prototype.numRows = function() {
586 return this.rawData_.length;
587};
588
589/**
590 * Returns the value in the given row and column. If the row and column exceed
591 * the bounds on the data, returns null. Also returns null if the value is
592 * missing.
629a09ae
DV
593 * @param { Number} row The row number of the data (0-based). Row 0 is the
594 * first row of data, not a header row.
595 * @param { Number} col The column number of the data (0-based)
596 * @return { Number } The value in the specified cell or null if the row/col
597 * were out of range.
e99fde05
DV
598 */
599Dygraph.prototype.getValue = function(row, col) {
600 if (row < 0 || row > this.rawData_.length) return null;
601 if (col < 0 || col > this.rawData_[row].length) return null;
602
603 return this.rawData_[row][col];
604};
605
629a09ae 606/**
285a6bda 607 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 608 * display the current point, and a textbox to adjust the rolling average
697e70b2 609 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
610 * @private
611 */
285a6bda 612Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
613 // Create the all-enclosing graph div
614 var enclosing = this.maindiv_;
615
b0c3b730
DV
616 this.graphDiv = document.createElement("div");
617 this.graphDiv.style.width = this.width_ + "px";
618 this.graphDiv.style.height = this.height_ + "px";
619 enclosing.appendChild(this.graphDiv);
620
621 // Create the canvas for interactive parts of the chart.
f8cfec73 622 this.canvas_ = Dygraph.createCanvas();
b0c3b730
DV
623 this.canvas_.style.position = "absolute";
624 this.canvas_.width = this.width_;
625 this.canvas_.height = this.height_;
f8cfec73
DV
626 this.canvas_.style.width = this.width_ + "px"; // for IE
627 this.canvas_.style.height = this.height_ + "px"; // for IE
b0c3b730 628
2cf95fff
RK
629 this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
630
b0c3b730 631 // ... and for static parts of the chart.
6a1aa64f 632 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
2cf95fff 633 this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
76171648 634
eb7bf005
EC
635 // The interactive parts of the graph are drawn on top of the chart.
636 this.graphDiv.appendChild(this.hidden_);
637 this.graphDiv.appendChild(this.canvas_);
638 this.mouseEventElement_ = this.canvas_;
639
76171648 640 var dygraph = this;
eb7bf005 641 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
76171648
DV
642 dygraph.mouseMove_(e);
643 });
eb7bf005 644 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
76171648
DV
645 dygraph.mouseOut_(e);
646 });
697e70b2
DV
647
648 // Create the grapher
b2c9222a 649 this.layout_ = new DygraphLayout(this);
697e70b2 650
697e70b2 651 this.createStatusMessage_();
697e70b2 652 this.createDragInterface_();
4cfcc38c
DV
653};
654
655/**
656 * Detach DOM elements in the dygraph and null out all data references.
657 * Calling this when you're done with a dygraph can dramatically reduce memory
658 * usage. See, e.g., the tests/perf.html example.
659 */
660Dygraph.prototype.destroy = function() {
661 var removeRecursive = function(node) {
662 while (node.hasChildNodes()) {
663 removeRecursive(node.firstChild);
664 node.removeChild(node.firstChild);
665 }
666 };
667 removeRecursive(this.maindiv_);
668
669 var nullOut = function(obj) {
670 for (var n in obj) {
671 if (typeof(obj[n]) === 'object') {
672 obj[n] = null;
673 }
674 }
675 };
676
677 // These may not all be necessary, but it can't hurt...
678 nullOut(this.layout_);
679 nullOut(this.plotter_);
680 nullOut(this);
681};
6a1aa64f
DV
682
683/**
629a09ae
DV
684 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
685 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
686 * or the zoom rectangles) is done on this.canvas_.
8846615a 687 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
688 * @return {Object} The newly-created canvas
689 * @private
690 */
285a6bda 691Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 692 var h = Dygraph.createCanvas();
6a1aa64f 693 h.style.position = "absolute";
9ac5e4ae
DV
694 // TODO(danvk): h should be offset from canvas. canvas needs to include
695 // some extra area to make it easier to zoom in on the far left and far
696 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
697 h.style.top = canvas.style.top;
698 h.style.left = canvas.style.left;
699 h.width = this.width_;
700 h.height = this.height_;
f8cfec73
DV
701 h.style.width = this.width_ + "px"; // for IE
702 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
703 return h;
704};
705
629a09ae 706/**
6a1aa64f
DV
707 * Generate a set of distinct colors for the data series. This is done with a
708 * color wheel. Saturation/Value are customizable, and the hue is
709 * equally-spaced around the color wheel. If a custom set of colors is
710 * specified, that is used instead.
6a1aa64f
DV
711 * @private
712 */
285a6bda 713Dygraph.prototype.setColors_ = function() {
285a6bda 714 var num = this.attr_("labels").length - 1;
6a1aa64f 715 this.colors_ = [];
285a6bda
DV
716 var colors = this.attr_('colors');
717 if (!colors) {
718 var sat = this.attr_('colorSaturation') || 1.0;
719 var val = this.attr_('colorValue') || 0.5;
2aa21213 720 var half = Math.ceil(num / 2);
6a1aa64f 721 for (var i = 1; i <= num; i++) {
ec1959eb 722 if (!this.visibility()[i-1]) continue;
43af96e7 723 // alternate colors for high contrast.
2aa21213 724 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
43af96e7
NK
725 var hue = (1.0 * idx/ (1 + num));
726 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
6a1aa64f
DV
727 }
728 } else {
729 for (var i = 0; i < num; i++) {
ec1959eb 730 if (!this.visibility()[i]) continue;
285a6bda 731 var colorStr = colors[i % colors.length];
f474c2a3 732 this.colors_.push(colorStr);
6a1aa64f
DV
733 }
734 }
600d841a
DV
735
736 this.plotter_.setColors(this.colors_);
629a09ae 737};
6a1aa64f 738
43af96e7
NK
739/**
740 * Return the list of colors. This is either the list of colors passed in the
629a09ae 741 * attributes or the autogenerated list of rgb(r,g,b) strings.
43af96e7
NK
742 * @return {Array<string>} The list of colors.
743 */
744Dygraph.prototype.getColors = function() {
745 return this.colors_;
746};
747
6a1aa64f
DV
748/**
749 * Create the div that contains information on the selected point(s)
750 * This goes in the top right of the canvas, unless an external div has already
751 * been specified.
752 * @private
753 */
fedbd797 754Dygraph.prototype.createStatusMessage_ = function() {
755 var userLabelsDiv = this.user_attrs_["labelsDiv"];
756 if (userLabelsDiv && null != userLabelsDiv
757 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
758 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
759 }
285a6bda
DV
760 if (!this.attr_("labelsDiv")) {
761 var divWidth = this.attr_('labelsDivWidth');
b0c3b730 762 var messagestyle = {
6a1aa64f
DV
763 "position": "absolute",
764 "fontSize": "14px",
765 "zIndex": 10,
766 "width": divWidth + "px",
767 "top": "0px",
8846615a 768 "left": (this.width_ - divWidth - 2) + "px",
6a1aa64f
DV
769 "background": "white",
770 "textAlign": "left",
b0c3b730 771 "overflow": "hidden"};
fc80a396 772 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
b0c3b730
DV
773 var div = document.createElement("div");
774 for (var name in messagestyle) {
85b99f0b
DV
775 if (messagestyle.hasOwnProperty(name)) {
776 div.style[name] = messagestyle[name];
777 }
b0c3b730
DV
778 }
779 this.graphDiv.appendChild(div);
285a6bda 780 this.attrs_.labelsDiv = div;
6a1aa64f
DV
781 }
782};
783
784/**
ad1798c2
DV
785 * Position the labels div so that:
786 * - its right edge is flush with the right edge of the charting area
787 * - its top edge is flush with the top edge of the charting area
629a09ae 788 * @private
0abfbd7e
DV
789 */
790Dygraph.prototype.positionLabelsDiv_ = function() {
791 // Don't touch a user-specified labelsDiv.
792 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
793
794 var area = this.plotter_.area;
795 var div = this.attr_("labelsDiv");
8c21adcf 796 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
ad1798c2 797 div.style.top = area.y + "px";
0abfbd7e
DV
798};
799
800/**
6a1aa64f 801 * Create the text box to adjust the averaging period
6a1aa64f
DV
802 * @private
803 */
285a6bda 804Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
805 // Create a roller if one doesn't exist already.
806 if (!this.roller_) {
807 this.roller_ = document.createElement("input");
808 this.roller_.type = "text";
809 this.roller_.style.display = "none";
810 this.graphDiv.appendChild(this.roller_);
811 }
812
813 var display = this.attr_('showRoller') ? 'block' : 'none';
26ca7938 814
0c38f187 815 var area = this.plotter_.area;
b0c3b730
DV
816 var textAttr = { "position": "absolute",
817 "zIndex": 10,
0c38f187
DV
818 "top": (area.y + area.h - 25) + "px",
819 "left": (area.x + 1) + "px",
b0c3b730 820 "display": display
6a1aa64f 821 };
8c69de65
DV
822 this.roller_.size = "2";
823 this.roller_.value = this.rollPeriod_;
b0c3b730 824 for (var name in textAttr) {
85b99f0b 825 if (textAttr.hasOwnProperty(name)) {
8c69de65 826 this.roller_.style[name] = textAttr[name];
85b99f0b 827 }
b0c3b730
DV
828 }
829
76171648 830 var dygraph = this;
8c69de65 831 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
832};
833
629a09ae
DV
834/**
835 * @private
629a09ae
DV
836 * Converts page the x-coordinate of the event to pixel x-coordinates on the
837 * canvas (i.e. DOM Coords).
838 */
062ef401
JB
839Dygraph.prototype.dragGetX_ = function(e, context) {
840 return Dygraph.pageX(e) - context.px
841};
bce01b0f 842
629a09ae
DV
843/**
844 * @private
845 * Converts page the y-coordinate of the event to pixel y-coordinates on the
846 * canvas (i.e. DOM Coords).
847 */
062ef401
JB
848Dygraph.prototype.dragGetY_ = function(e, context) {
849 return Dygraph.pageY(e) - context.py
850};
ee672584 851
629a09ae 852/**
062ef401
JB
853 * Set up all the mouse handlers needed to capture dragging behavior for zoom
854 * events.
855 * @private
856 */
857Dygraph.prototype.createDragInterface_ = function() {
858 var context = {
859 // Tracks whether the mouse is down right now
860 isZooming: false,
861 isPanning: false, // is this drag part of a pan?
862 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
8442269f
RK
863 dragStartX: null, // pixel coordinates
864 dragStartY: null, // pixel coordinates
865 dragEndX: null, // pixel coordinates
866 dragEndY: null, // pixel coordinates
062ef401 867 dragDirection: null,
8442269f
RK
868 prevEndX: null, // pixel coordinates
869 prevEndY: null, // pixel coordinates
062ef401
JB
870 prevDragDirection: null,
871
ec291cbe
RK
872 // The value on the left side of the graph when a pan operation starts.
873 initialLeftmostDate: null,
874
875 // The number of units each pixel spans. (This won't be valid for log
876 // scales)
877 xUnitsPerPixel: null,
062ef401
JB
878
879 // TODO(danvk): update this comment
880 // The range in second/value units that the viewport encompasses during a
881 // panning operation.
882 dateRange: null,
883
8442269f
RK
884 // Top-left corner of the canvas, in DOM coords
885 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
062ef401
JB
886 px: 0,
887 py: 0,
888
965a030e 889 // Values for use with panEdgeFraction, which limit how far outside the
4cac8c7a
RK
890 // graph's data boundaries it can be panned.
891 boundedDates: null, // [minDate, maxDate]
892 boundedValues: null, // [[minValue, maxValue] ...]
893
062ef401
JB
894 initializeMouseDown: function(event, g, context) {
895 // prevents mouse drags from selecting page text.
896 if (event.preventDefault) {
897 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 898 } else {
062ef401
JB
899 event.returnValue = false; // IE
900 event.cancelBubble = true;
6a1aa64f
DV
901 }
902
062ef401
JB
903 context.px = Dygraph.findPosX(g.canvas_);
904 context.py = Dygraph.findPosY(g.canvas_);
905 context.dragStartX = g.dragGetX_(event, context);
906 context.dragStartY = g.dragGetY_(event, context);
6a1aa64f 907 }
062ef401 908 };
2b188b3d 909
062ef401 910 var interactionModel = this.attr_("interactionModel");
8b83c6cc 911
062ef401
JB
912 // Self is the graph.
913 var self = this;
6faebb69 914
062ef401
JB
915 // Function that binds the graph and context to the handler.
916 var bindHandler = function(handler) {
917 return function(event) {
918 handler(event, self, context);
919 };
920 };
921
922 for (var eventName in interactionModel) {
923 if (!interactionModel.hasOwnProperty(eventName)) continue;
924 Dygraph.addEvent(this.mouseEventElement_, eventName,
925 bindHandler(interactionModel[eventName]));
926 }
927
928 // If the user releases the mouse button during a drag, but not over the
929 // canvas, then it doesn't count as a zooming action.
930 Dygraph.addEvent(document, 'mouseup', function(event) {
931 if (context.isZooming || context.isPanning) {
932 context.isZooming = false;
933 context.dragStartX = null;
934 context.dragStartY = null;
935 }
936
937 if (context.isPanning) {
938 context.isPanning = false;
939 context.draggingDate = null;
940 context.dateRange = null;
941 for (var i = 0; i < self.axes_.length; i++) {
942 delete self.axes_[i].draggingValue;
943 delete self.axes_[i].dragValueRange;
944 }
945 }
6a1aa64f
DV
946 });
947};
948
062ef401 949
6a1aa64f
DV
950/**
951 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
952 * up any previous zoom rectangles that were drawn. This could be optimized to
953 * avoid extra redrawing, but it's tricky to avoid interactions with the status
954 * dots.
8b83c6cc 955 *
39b0e098
RK
956 * @param {Number} direction the direction of the zoom rectangle. Acceptable
957 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
6a1aa64f
DV
958 * @param {Number} startX The X position where the drag started, in canvas
959 * coordinates.
960 * @param {Number} endX The current X position of the drag, in canvas coords.
8b83c6cc
RK
961 * @param {Number} startY The Y position where the drag started, in canvas
962 * coordinates.
963 * @param {Number} endY The current Y position of the drag, in canvas coords.
39b0e098 964 * @param {Number} prevDirection the value of direction on the previous call to
8b83c6cc 965 * this function. Used to avoid excess redrawing
6a1aa64f
DV
966 * @param {Number} prevEndX The value of endX on the previous call to this
967 * function. Used to avoid excess redrawing
8b83c6cc
RK
968 * @param {Number} prevEndY The value of endY on the previous call to this
969 * function. Used to avoid excess redrawing
6a1aa64f
DV
970 * @private
971 */
7201b11e
JB
972Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
973 endY, prevDirection, prevEndX,
974 prevEndY) {
2cf95fff 975 var ctx = this.canvas_ctx_;
6a1aa64f
DV
976
977 // Clean up from the previous rect if necessary
39b0e098 978 if (prevDirection == Dygraph.HORIZONTAL) {
6a1aa64f
DV
979 ctx.clearRect(Math.min(startX, prevEndX), 0,
980 Math.abs(startX - prevEndX), this.height_);
39b0e098 981 } else if (prevDirection == Dygraph.VERTICAL){
8b83c6cc
RK
982 ctx.clearRect(0, Math.min(startY, prevEndY),
983 this.width_, Math.abs(startY - prevEndY));
6a1aa64f
DV
984 }
985
986 // Draw a light-grey rectangle to show the new viewing area
39b0e098 987 if (direction == Dygraph.HORIZONTAL) {
8b83c6cc
RK
988 if (endX && startX) {
989 ctx.fillStyle = "rgba(128,128,128,0.33)";
990 ctx.fillRect(Math.min(startX, endX), 0,
991 Math.abs(endX - startX), this.height_);
992 }
993 }
39b0e098 994 if (direction == Dygraph.VERTICAL) {
8b83c6cc
RK
995 if (endY && startY) {
996 ctx.fillStyle = "rgba(128,128,128,0.33)";
997 ctx.fillRect(0, Math.min(startY, endY),
998 this.width_, Math.abs(endY - startY));
999 }
6a1aa64f
DV
1000 }
1001};
1002
1003/**
8b83c6cc
RK
1004 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1005 * the canvas. The exact zoom window may be slightly larger if there are no data
1006 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1007 * which accepts dates that match the raw data. This function redraws the graph.
d58ae307 1008 *
6a1aa64f
DV
1009 * @param {Number} lowX The leftmost pixel value that should be visible.
1010 * @param {Number} highX The rightmost pixel value that should be visible.
1011 * @private
1012 */
8b83c6cc 1013Dygraph.prototype.doZoomX_ = function(lowX, highX) {
6a1aa64f 1014 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1015 // Convert the call to date ranges of the raw data.
ff022deb
RK
1016 var minDate = this.toDataXCoord(lowX);
1017 var maxDate = this.toDataXCoord(highX);
8b83c6cc
RK
1018 this.doZoomXDates_(minDate, maxDate);
1019};
6a1aa64f 1020
8b83c6cc
RK
1021/**
1022 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1023 * method with doZoomX which accepts pixel coordinates. This function redraws
1024 * the graph.
d58ae307 1025 *
8b83c6cc
RK
1026 * @param {Number} minDate The minimum date that should be visible.
1027 * @param {Number} maxDate The maximum date that should be visible.
1028 * @private
1029 */
1030Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
6a1aa64f 1031 this.dateWindow_ = [minDate, maxDate];
57baab03 1032 this.zoomed_x_ = true;
26ca7938 1033 this.drawGraph_();
285a6bda 1034 if (this.attr_("zoomCallback")) {
ac139d19 1035 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc
RK
1036 }
1037};
1038
1039/**
1040 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1041 * the canvas. This function redraws the graph.
1042 *
8b83c6cc
RK
1043 * @param {Number} lowY The topmost pixel value that should be visible.
1044 * @param {Number} highY The lowest pixel value that should be visible.
1045 * @private
1046 */
1047Dygraph.prototype.doZoomY_ = function(lowY, highY) {
d58ae307
DV
1048 // Find the highest and lowest values in pixel range for each axis.
1049 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1050 // This is because pixels increase as you go down on the screen, whereas data
1051 // coordinates increase as you go up the screen.
1052 var valueRanges = [];
1053 for (var i = 0; i < this.axes_.length; i++) {
ff022deb
RK
1054 var hi = this.toDataYCoord(lowY, i);
1055 var low = this.toDataYCoord(highY, i);
1056 this.axes_[i].valueWindow = [low, hi];
1057 valueRanges.push([low, hi]);
d58ae307 1058 }
8b83c6cc 1059
57baab03 1060 this.zoomed_y_ = true;
66c380c4 1061 this.drawGraph_();
8b83c6cc 1062 if (this.attr_("zoomCallback")) {
d58ae307 1063 var xRange = this.xAxisRange();
45f2c689 1064 var yRange = this.yAxisRange();
d58ae307 1065 this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges());
8b83c6cc
RK
1066 }
1067};
1068
1069/**
1070 * Reset the zoom to the original view coordinates. This is the same as
1071 * double-clicking on the graph.
d58ae307 1072 *
8b83c6cc
RK
1073 * @private
1074 */
1075Dygraph.prototype.doUnzoom_ = function() {
d58ae307 1076 var dirty = false;
8b83c6cc 1077 if (this.dateWindow_ != null) {
d58ae307 1078 dirty = true;
8b83c6cc
RK
1079 this.dateWindow_ = null;
1080 }
d58ae307
DV
1081
1082 for (var i = 0; i < this.axes_.length; i++) {
1083 if (this.axes_[i].valueWindow != null) {
1084 dirty = true;
1085 delete this.axes_[i].valueWindow;
1086 }
8b83c6cc
RK
1087 }
1088
da1369a5
DV
1089 // Clear any selection, since it's likely to be drawn in the wrong place.
1090 this.clearSelection();
1091
8b83c6cc 1092 if (dirty) {
437c0979
RK
1093 // Putting the drawing operation before the callback because it resets
1094 // yAxisRange.
57baab03
NN
1095 this.zoomed_x_ = false;
1096 this.zoomed_y_ = false;
66c380c4 1097 this.drawGraph_();
8b83c6cc
RK
1098 if (this.attr_("zoomCallback")) {
1099 var minDate = this.rawData_[0][0];
1100 var maxDate = this.rawData_[this.rawData_.length - 1][0];
d58ae307 1101 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc 1102 }
67e650dc 1103 }
6a1aa64f
DV
1104};
1105
1106/**
1107 * When the mouse moves in the canvas, display information about a nearby data
1108 * point and draw dots over those points in the data series. This function
1109 * takes care of cleanup of previously-drawn dots.
1110 * @param {Object} event The mousemove event from the browser.
1111 * @private
1112 */
285a6bda 1113Dygraph.prototype.mouseMove_ = function(event) {
e863a17d 1114 // This prevents JS errors when mousing over the canvas before data loads.
4cac8c7a 1115 var points = this.layout_.points;
685ebbb3 1116 if (points === undefined) return;
e863a17d 1117
4cac8c7a
RK
1118 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
1119
6a1aa64f
DV
1120 var lastx = -1;
1121 var lasty = -1;
1122
1123 // Loop through all the points and find the date nearest to our current
1124 // location.
1125 var minDist = 1e+100;
1126 var idx = -1;
1127 for (var i = 0; i < points.length; i++) {
8a7cc60e
RK
1128 var point = points[i];
1129 if (point == null) continue;
062ef401 1130 var dist = Math.abs(point.canvasx - canvasx);
f032c51d 1131 if (dist > minDist) continue;
6a1aa64f
DV
1132 minDist = dist;
1133 idx = i;
1134 }
1135 if (idx >= 0) lastx = points[idx].xval;
6a1aa64f
DV
1136
1137 // Extract the points we've selected
b258a3da 1138 this.selPoints_ = [];
50360fd0 1139 var l = points.length;
416b05ad
NK
1140 if (!this.attr_("stackedGraph")) {
1141 for (var i = 0; i < l; i++) {
1142 if (points[i].xval == lastx) {
1143 this.selPoints_.push(points[i]);
1144 }
1145 }
1146 } else {
354e15ab
DE
1147 // Need to 'unstack' points starting from the bottom
1148 var cumulative_sum = 0;
416b05ad
NK
1149 for (var i = l - 1; i >= 0; i--) {
1150 if (points[i].xval == lastx) {
354e15ab 1151 var p = {}; // Clone the point since we modify it
d4139cd8
NK
1152 for (var k in points[i]) {
1153 p[k] = points[i][k];
50360fd0
NK
1154 }
1155 p.yval -= cumulative_sum;
1156 cumulative_sum += p.yval;
d4139cd8 1157 this.selPoints_.push(p);
12e4c741 1158 }
6a1aa64f 1159 }
354e15ab 1160 this.selPoints_.reverse();
6a1aa64f
DV
1161 }
1162
b258a3da 1163 if (this.attr_("highlightCallback")) {
a4c6a67c 1164 var px = this.lastx_;
dd082dda 1165 if (px !== null && lastx != px) {
344ba8c0 1166 // only fire if the selected point has changed.
2ddb1197 1167 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
43af96e7 1168 }
12e4c741 1169 }
43af96e7 1170
239c712d
NAG
1171 // Save last x position for callbacks.
1172 this.lastx_ = lastx;
50360fd0 1173
239c712d
NAG
1174 this.updateSelection_();
1175};
b258a3da 1176
239c712d 1177/**
1903f1e4 1178 * Transforms layout_.points index into data row number.
2ddb1197 1179 * @param int layout_.points index
1903f1e4 1180 * @return int row number, or -1 if none could be found.
2ddb1197
SC
1181 * @private
1182 */
1183Dygraph.prototype.idxToRow_ = function(idx) {
1903f1e4 1184 if (idx < 0) return -1;
2ddb1197 1185
1903f1e4
DV
1186 for (var i in this.layout_.datasets) {
1187 if (idx < this.layout_.datasets[i].length) {
1188 return this.boundaryIds_[0][0]+idx;
1189 }
1190 idx -= this.layout_.datasets[i].length;
1191 }
1192 return -1;
1193};
2ddb1197 1194
629a09ae
DV
1195/**
1196 * @private
629a09ae
DV
1197 * Generates HTML for the legend which is displayed when hovering over the
1198 * chart. If no selected points are specified, a default legend is returned
1199 * (this may just be the empty string).
1200 * @param { Number } [x] The x-value of the selected points.
1201 * @param { [Object] } [sel_points] List of selected points for the given
1202 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1203 */
e9fe4a2f 1204Dygraph.prototype.generateLegendHTML_ = function(x, sel_points) {
2fccd3dc
DV
1205 // If no points are selected, we display a default legend. Traditionally,
1206 // this has been blank. But a better default would be a conventional legend,
1207 // which provides essential information for a non-interactive chart.
1208 if (typeof(x) === 'undefined') {
1209 if (this.attr_('legend') != 'always') return '';
1210
1211 var sepLines = this.attr_('labelsSeparateLines');
1212 var labels = this.attr_('labels');
1213 var html = '';
1214 for (var i = 1; i < labels.length; i++) {
352c8310 1215 if (!this.visibility()[i - 1]) continue;
bafe040e 1216 var c = this.plotter_.colors[labels[i]];
352c8310 1217 if (html != '') html += (sepLines ? '<br/>' : ' ');
bafe040e
DV
1218 html += "<b><span style='color: " + c + ";'>&mdash;" + labels[i] +
1219 "</span></b>";
2fccd3dc
DV
1220 }
1221 return html;
1222 }
1223
032e4c1d 1224 var html = this.attr_('xValueFormatter')(x) + ":";
e9fe4a2f
DV
1225
1226 var fmtFunc = this.attr_('yValueFormatter');
1227 var showZeros = this.attr_("labelsShowZeroValues");
1228 var sepLines = this.attr_("labelsSeparateLines");
1229 for (var i = 0; i < this.selPoints_.length; i++) {
1230 var pt = this.selPoints_[i];
1231 if (pt.yval == 0 && !showZeros) continue;
1232 if (!Dygraph.isOK(pt.canvasy)) continue;
1233 if (sepLines) html += "<br/>";
1234
bafe040e 1235 var c = this.plotter_.colors[pt.name];
91c10d9c 1236 var yval = fmtFunc(pt.yval, this);
2fccd3dc 1237 // TODO(danvk): use a template string here and make it an attribute.
bafe040e
DV
1238 html += " <b><span style='color: " + c + ";'>"
1239 + pt.name + "</span></b>:"
e9fe4a2f
DV
1240 + yval;
1241 }
1242 return html;
1243};
1244
629a09ae
DV
1245/**
1246 * @private
1247 * Displays information about the selected points in the legend. If there is no
1248 * selection, the legend will be cleared.
1249 * @param { Number } [x] The x-value of the selected points.
1250 * @param { [Object] } [sel_points] List of selected points for the given
1251 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1252 */
91c10d9c
DV
1253Dygraph.prototype.setLegendHTML_ = function(x, sel_points) {
1254 var html = this.generateLegendHTML_(x, sel_points);
1255 var labelsDiv = this.attr_("labelsDiv");
1256 if (labelsDiv !== null) {
1257 labelsDiv.innerHTML = html;
1258 } else {
1259 if (typeof(this.shown_legend_error_) == 'undefined') {
1260 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1261 this.shown_legend_error_ = true;
1262 }
1263 }
1264};
1265
2ddb1197 1266/**
239c712d
NAG
1267 * Draw dots over the selectied points in the data series. This function
1268 * takes care of cleanup of previously-drawn dots.
1269 * @private
1270 */
1271Dygraph.prototype.updateSelection_ = function() {
6a1aa64f 1272 // Clear the previously drawn vertical, if there is one
2cf95fff 1273 var ctx = this.canvas_ctx_;
6a1aa64f 1274 if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
1275 // Determine the maximum highlight circle size.
1276 var maxCircleSize = 0;
227b93cc
DV
1277 var labels = this.attr_('labels');
1278 for (var i = 1; i < labels.length; i++) {
1279 var r = this.attr_('highlightCircleSize', labels[i]);
46dde5f9
DV
1280 if (r > maxCircleSize) maxCircleSize = r;
1281 }
6a1aa64f 1282 var px = this.previousVerticalX_;
46dde5f9
DV
1283 ctx.clearRect(px - maxCircleSize - 1, 0,
1284 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
1285 }
1286
d160cc3b 1287 if (this.selPoints_.length > 0) {
6a1aa64f 1288 // Set the status message to indicate the selected point(s)
d160cc3b 1289 if (this.attr_('showLabelsOnHighlight')) {
91c10d9c 1290 this.setLegendHTML_(this.lastx_, this.selPoints_);
6a1aa64f 1291 }
6a1aa64f 1292
6a1aa64f 1293 // Draw colored circles over the center of each selected point
e9fe4a2f 1294 var canvasx = this.selPoints_[0].canvasx;
43af96e7 1295 ctx.save();
b258a3da 1296 for (var i = 0; i < this.selPoints_.length; i++) {
e9fe4a2f
DV
1297 var pt = this.selPoints_[i];
1298 if (!Dygraph.isOK(pt.canvasy)) continue;
1299
1300 var circleSize = this.attr_('highlightCircleSize', pt.name);
6a1aa64f 1301 ctx.beginPath();
e9fe4a2f
DV
1302 ctx.fillStyle = this.plotter_.colors[pt.name];
1303 ctx.arc(canvasx, pt.canvasy, circleSize, 0, 2 * Math.PI, false);
6a1aa64f
DV
1304 ctx.fill();
1305 }
1306 ctx.restore();
1307
1308 this.previousVerticalX_ = canvasx;
1309 }
1310};
1311
1312/**
629a09ae
DV
1313 * Manually set the selected points and display information about them in the
1314 * legend. The selection can be cleared using clearSelection() and queried
1315 * using getSelection().
1316 * @param { Integer } row number that should be highlighted (i.e. appear with
1317 * hover dots on the chart). Set to false to clear any selection.
239c712d
NAG
1318 */
1319Dygraph.prototype.setSelection = function(row) {
1320 // Extract the points we've selected
1321 this.selPoints_ = [];
1322 var pos = 0;
50360fd0 1323
239c712d 1324 if (row !== false) {
16269f6e
NAG
1325 row = row-this.boundaryIds_[0][0];
1326 }
50360fd0 1327
16269f6e 1328 if (row !== false && row >= 0) {
239c712d 1329 for (var i in this.layout_.datasets) {
16269f6e 1330 if (row < this.layout_.datasets[i].length) {
38f33a44 1331 var point = this.layout_.points[pos+row];
1332
1333 if (this.attr_("stackedGraph")) {
8c03ba63 1334 point = this.layout_.unstackPointAtIndex(pos+row);
38f33a44 1335 }
1336
1337 this.selPoints_.push(point);
16269f6e 1338 }
239c712d
NAG
1339 pos += this.layout_.datasets[i].length;
1340 }
16269f6e 1341 }
50360fd0 1342
16269f6e 1343 if (this.selPoints_.length) {
239c712d
NAG
1344 this.lastx_ = this.selPoints_[0].xval;
1345 this.updateSelection_();
1346 } else {
239c712d
NAG
1347 this.clearSelection();
1348 }
1349
1350};
1351
1352/**
6a1aa64f
DV
1353 * The mouse has left the canvas. Clear out whatever artifacts remain
1354 * @param {Object} event the mouseout event from the browser.
1355 * @private
1356 */
285a6bda 1357Dygraph.prototype.mouseOut_ = function(event) {
a4c6a67c
AV
1358 if (this.attr_("unhighlightCallback")) {
1359 this.attr_("unhighlightCallback")(event);
1360 }
1361
43af96e7 1362 if (this.attr_("hideOverlayOnMouseOut")) {
239c712d 1363 this.clearSelection();
43af96e7 1364 }
6a1aa64f
DV
1365};
1366
239c712d 1367/**
629a09ae
DV
1368 * Clears the current selection (i.e. points that were highlighted by moving
1369 * the mouse over the chart).
239c712d
NAG
1370 */
1371Dygraph.prototype.clearSelection = function() {
1372 // Get rid of the overlay data
2cf95fff 1373 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
91c10d9c 1374 this.setLegendHTML_();
239c712d
NAG
1375 this.selPoints_ = [];
1376 this.lastx_ = -1;
1377}
1378
103b7292 1379/**
629a09ae
DV
1380 * Returns the number of the currently selected row. To get data for this row,
1381 * you can use the getValue method.
1382 * @return { Integer } row number, or -1 if nothing is selected
103b7292
NAG
1383 */
1384Dygraph.prototype.getSelection = function() {
1385 if (!this.selPoints_ || this.selPoints_.length < 1) {
1386 return -1;
1387 }
50360fd0 1388
103b7292
NAG
1389 for (var row=0; row<this.layout_.points.length; row++ ) {
1390 if (this.layout_.points[row].x == this.selPoints_[0].x) {
16269f6e 1391 return row + this.boundaryIds_[0][0];
103b7292
NAG
1392 }
1393 }
1394 return -1;
2e1fcf1a 1395};
103b7292 1396
19589a3e 1397/**
629a09ae 1398 * @private
2e1fcf1a
DV
1399 * Return a string version of a number. This respects the digitsAfterDecimal
1400 * and maxNumberWidth options.
1401 * @param {Number} x The number to be formatted
1402 * @param {Dygraph} g The dygraph object
1403 */
1404Dygraph.numberFormatter = function(x, g) {
19589a3e
DV
1405 var sigFigs = g.attr_('sigFigs');
1406
1407 if (sigFigs !== null) {
1408 // User has opted for a fixed number of significant figures.
1409 return Dygraph.floatFormat(x, sigFigs);
1410 }
1411
2e1fcf1a
DV
1412 var digits = g.attr_('digitsAfterDecimal');
1413 var maxNumberWidth = g.attr_('maxNumberWidth');
1414
19589a3e
DV
1415 // switch to scientific notation if we underflow or overflow fixed display.
1416 if (x !== 0.0 &&
1417 (Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
1418 Math.abs(x) < Math.pow(10, -digits))) {
1419 return x.toExponential(digits);
2e1fcf1a
DV
1420 } else {
1421 return '' + Dygraph.round_(x, digits);
1422 }
1423};
32988383 1424
629a09ae 1425/**
bf640e56
AV
1426 * Convert a JS date to a string appropriate to display on an axis that
1427 * is displaying values at the stated granularity.
1428 * @param {Date} date The date to format
1429 * @param {Number} granularity One of the Dygraph granularity constants
1430 * @return {String} The formatted date
1431 * @private
1432 */
1433Dygraph.dateAxisFormatter = function(date, granularity) {
062ef401
JB
1434 if (granularity >= Dygraph.DECADAL) {
1435 return date.strftime('%Y');
1436 } else if (granularity >= Dygraph.MONTHLY) {
bf640e56
AV
1437 return date.strftime('%b %y');
1438 } else {
31eddad3 1439 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
bf640e56
AV
1440 if (frac == 0 || granularity >= Dygraph.DAILY) {
1441 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
1442 } else {
1443 return Dygraph.hmsString_(date.getTime());
1444 }
1445 }
2e1fcf1a 1446};
bf640e56
AV
1447
1448/**
6a1aa64f
DV
1449 * Fires when there's data available to be graphed.
1450 * @param {String} data Raw CSV data to be plotted
1451 * @private
1452 */
285a6bda 1453Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 1454 this.rawData_ = this.parseCSV_(data);
26ca7938 1455 this.predraw_();
6a1aa64f
DV
1456};
1457
285a6bda 1458Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
8846615a 1459 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
285a6bda 1460Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
6a1aa64f
DV
1461
1462/**
1463 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1464 * @private
1465 */
285a6bda 1466Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 1467 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 1468 var range;
6a1aa64f 1469 if (this.dateWindow_) {
7201b11e 1470 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 1471 } else {
7201b11e
JB
1472 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
1473 }
1474
032e4c1d 1475 var xTicks = this.attr_('xTicker')(range[0], range[1], this);
b2c9222a 1476 this.layout_.setXTicks(xTicks);
32988383
DV
1477};
1478
1479// Time granularity enumeration
285a6bda 1480Dygraph.SECONDLY = 0;
20a41c17
DV
1481Dygraph.TWO_SECONDLY = 1;
1482Dygraph.FIVE_SECONDLY = 2;
1483Dygraph.TEN_SECONDLY = 3;
1484Dygraph.THIRTY_SECONDLY = 4;
1485Dygraph.MINUTELY = 5;
1486Dygraph.TWO_MINUTELY = 6;
1487Dygraph.FIVE_MINUTELY = 7;
1488Dygraph.TEN_MINUTELY = 8;
1489Dygraph.THIRTY_MINUTELY = 9;
1490Dygraph.HOURLY = 10;
1491Dygraph.TWO_HOURLY = 11;
1492Dygraph.SIX_HOURLY = 12;
1493Dygraph.DAILY = 13;
1494Dygraph.WEEKLY = 14;
1495Dygraph.MONTHLY = 15;
1496Dygraph.QUARTERLY = 16;
1497Dygraph.BIANNUAL = 17;
1498Dygraph.ANNUAL = 18;
1499Dygraph.DECADAL = 19;
062ef401
JB
1500Dygraph.CENTENNIAL = 20;
1501Dygraph.NUM_GRANULARITIES = 21;
285a6bda
DV
1502
1503Dygraph.SHORT_SPACINGS = [];
1504Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
20a41c17
DV
1505Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
1506Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
285a6bda
DV
1507Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
1508Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
1509Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
20a41c17
DV
1510Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
1511Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
285a6bda
DV
1512Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
1513Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
1514Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
20a41c17 1515Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
805d5519 1516Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
285a6bda
DV
1517Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
1518Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
32988383 1519
629a09ae
DV
1520/**
1521 * @private
1522 * If we used this time granularity, how many ticks would there be?
1523 * This is only an approximation, but it's generally good enough.
1524 */
285a6bda
DV
1525Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
1526 if (granularity < Dygraph.MONTHLY) {
32988383 1527 // Generate one tick mark for every fixed interval of time.
285a6bda 1528 var spacing = Dygraph.SHORT_SPACINGS[granularity];
32988383
DV
1529 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
1530 } else {
1531 var year_mod = 1; // e.g. to only print one point every 10 years.
1532 var num_months = 12;
285a6bda
DV
1533 if (granularity == Dygraph.QUARTERLY) num_months = 3;
1534 if (granularity == Dygraph.BIANNUAL) num_months = 2;
1535 if (granularity == Dygraph.ANNUAL) num_months = 1;
1536 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
062ef401 1537 if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
32988383
DV
1538
1539 var msInYear = 365.2524 * 24 * 3600 * 1000;
1540 var num_years = 1.0 * (end_time - start_time) / msInYear;
1541 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
1542 }
1543};
1544
629a09ae
DV
1545/**
1546 * @private
1547 *
1548 * Construct an x-axis of nicely-formatted times on meaningful boundaries
1549 * (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1550 *
1551 * Returns an array containing {v: millis, label: label} dictionaries.
1552 */
285a6bda 1553Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
bf640e56 1554 var formatter = this.attr_("xAxisLabelFormatter");
32988383 1555 var ticks = [];
285a6bda 1556 if (granularity < Dygraph.MONTHLY) {
32988383 1557 // Generate one tick mark for every fixed interval of time.
285a6bda 1558 var spacing = Dygraph.SHORT_SPACINGS[granularity];
3d29302c 1559 var format = '%d%b'; // e.g. "1Jan"
076c9622
DV
1560
1561 // Find a time less than start_time which occurs on a "nice" time boundary
1562 // for this granularity.
1563 var g = spacing / 1000;
076c9622
DV
1564 var d = new Date(start_time);
1565 if (g <= 60) { // seconds
1566 var x = d.getSeconds(); d.setSeconds(x - x % g);
1567 } else {
1568 d.setSeconds(0);
1569 g /= 60;
1570 if (g <= 60) { // minutes
1571 var x = d.getMinutes(); d.setMinutes(x - x % g);
1572 } else {
1573 d.setMinutes(0);
1574 g /= 60;
1575
1576 if (g <= 24) { // days
1577 var x = d.getHours(); d.setHours(x - x % g);
1578 } else {
1579 d.setHours(0);
1580 g /= 24;
1581
1582 if (g == 7) { // one week
20a41c17 1583 d.setDate(d.getDate() - d.getDay());
076c9622
DV
1584 }
1585 }
1586 }
328bb812 1587 }
076c9622
DV
1588 start_time = d.getTime();
1589
32988383 1590 for (var t = start_time; t <= end_time; t += spacing) {
bf640e56 1591 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
1592 }
1593 } else {
1594 // Display a tick mark on the first of a set of months of each year.
1595 // Years get a tick mark iff y % year_mod == 0. This is useful for
1596 // displaying a tick mark once every 10 years, say, on long time scales.
1597 var months;
1598 var year_mod = 1; // e.g. to only print one point every 10 years.
1599
285a6bda 1600 if (granularity == Dygraph.MONTHLY) {
32988383 1601 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
285a6bda 1602 } else if (granularity == Dygraph.QUARTERLY) {
32988383 1603 months = [ 0, 3, 6, 9 ];
285a6bda 1604 } else if (granularity == Dygraph.BIANNUAL) {
32988383 1605 months = [ 0, 6 ];
285a6bda 1606 } else if (granularity == Dygraph.ANNUAL) {
32988383 1607 months = [ 0 ];
285a6bda 1608 } else if (granularity == Dygraph.DECADAL) {
32988383
DV
1609 months = [ 0 ];
1610 year_mod = 10;
062ef401
JB
1611 } else if (granularity == Dygraph.CENTENNIAL) {
1612 months = [ 0 ];
1613 year_mod = 100;
1614 } else {
1615 this.warn("Span of dates is too long");
32988383
DV
1616 }
1617
1618 var start_year = new Date(start_time).getFullYear();
1619 var end_year = new Date(end_time).getFullYear();
285a6bda 1620 var zeropad = Dygraph.zeropad;
32988383
DV
1621 for (var i = start_year; i <= end_year; i++) {
1622 if (i % year_mod != 0) continue;
1623 for (var j = 0; j < months.length; j++) {
1624 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
d96b7d1a 1625 var t = Dygraph.dateStrToMillis(date_str);
32988383 1626 if (t < start_time || t > end_time) continue;
bf640e56 1627 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
1628 }
1629 }
1630 }
1631
1632 return ticks;
1633};
1634
6a1aa64f
DV
1635
1636/**
1637 * Add ticks to the x-axis based on a date range.
1638 * @param {Number} startDate Start of the date window (millis since epoch)
1639 * @param {Number} endDate End of the date window (millis since epoch)
629a09ae
DV
1640 * @param {Dygraph} self The dygraph object
1641 * @return { [Object] } Array of {label, value} tuples.
6a1aa64f
DV
1642 * @public
1643 */
285a6bda 1644Dygraph.dateTicker = function(startDate, endDate, self) {
629a09ae 1645 // TODO(danvk): why does this take 'self' as a param?
32988383 1646 var chosen = -1;
285a6bda
DV
1647 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
1648 var num_ticks = self.NumXTicks(startDate, endDate, i);
1649 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
32988383
DV
1650 chosen = i;
1651 break;
2769de62 1652 }
6a1aa64f
DV
1653 }
1654
32988383 1655 if (chosen >= 0) {
285a6bda 1656 return self.GetXAxis(startDate, endDate, chosen);
6a1aa64f 1657 } else {
fffad740
DV
1658 // this can happen if self.width_ is zero.
1659 return [];
6a1aa64f 1660 }
6a1aa64f
DV
1661};
1662
629a09ae
DV
1663/**
1664 * @private
1665 * This is a list of human-friendly values at which to show tick marks on a log
1666 * scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
1667 * ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
1668 * NOTE: this assumes that Dygraph.LOG_SCALE = 10.
1669 */
0cfa06d1 1670Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
6821efbe
RK
1671 var vals = [];
1672 for (var power = -39; power <= 39; power++) {
1673 var range = Math.pow(10, power);
4b467120
RK
1674 for (var mult = 1; mult <= 9; mult++) {
1675 var val = range * mult;
6821efbe
RK
1676 vals.push(val);
1677 }
1678 }
1679 return vals;
1680}();
1681
629a09ae 1682// TODO(konigsberg): Update comment.
6a1aa64f
DV
1683/**
1684 * Add ticks when the x axis has numbers on it (instead of dates)
ff022deb 1685 *
7d0e7a0d
RK
1686 * @param {Number} minV minimum value
1687 * @param {Number} maxV maximum value
84fc6aa7 1688 * @param self
f30cf740 1689 * @param {function} attribute accessor function.
629a09ae 1690 * @return {[Object]} Array of {label, value} tuples.
6a1aa64f 1691 */
0d64e596 1692Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
70c80071
DV
1693 var attr = function(k) {
1694 if (axis_props && axis_props.hasOwnProperty(k)) return axis_props[k];
1695 return self.attr_(k);
1696 };
f09fc545 1697
0d64e596
DV
1698 var ticks = [];
1699 if (vals) {
1700 for (var i = 0; i < vals.length; i++) {
e863a17d 1701 ticks.push({v: vals[i]});
0d64e596 1702 }
f09e46d4 1703 } else {
7d0e7a0d 1704 if (axis_props && attr("logscale")) {
ff022deb 1705 var pixelsPerTick = attr('pixelsPerYLabel');
7d0e7a0d 1706 // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
ff022deb 1707 var nTicks = Math.floor(self.height_ / pixelsPerTick);
0cfa06d1
RK
1708 var minIdx = Dygraph.binarySearch(minV, Dygraph.PREFERRED_LOG_TICK_VALUES, 1);
1709 var maxIdx = Dygraph.binarySearch(maxV, Dygraph.PREFERRED_LOG_TICK_VALUES, -1);
1710 if (minIdx == -1) {
6821efbe
RK
1711 minIdx = 0;
1712 }
0cfa06d1
RK
1713 if (maxIdx == -1) {
1714 maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1;
6821efbe 1715 }
0cfa06d1
RK
1716 // Count the number of tick values would appear, if we can get at least
1717 // nTicks / 4 accept them.
00aa7f61 1718 var lastDisplayed = null;
0cfa06d1 1719 if (maxIdx - minIdx >= nTicks / 4) {
00aa7f61 1720 var axisId = axis_props.yAxisId;
0cfa06d1
RK
1721 for (var idx = maxIdx; idx >= minIdx; idx--) {
1722 var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx];
00aa7f61
RK
1723 var domCoord = axis_props.g.toDomYCoord(tickValue, axisId);
1724 var tick = { v: tickValue };
1725 if (lastDisplayed == null) {
1726 lastDisplayed = {
1727 tickValue : tickValue,
1728 domCoord : domCoord
1729 };
1730 } else {
1731 if (domCoord - lastDisplayed.domCoord >= pixelsPerTick) {
1732 lastDisplayed = {
1733 tickValue : tickValue,
1734 domCoord : domCoord
1735 };
1736 } else {
c1bc242a 1737 tick.label = "";
00aa7f61
RK
1738 }
1739 }
1740 ticks.push(tick);
6821efbe 1741 }
0cfa06d1
RK
1742 // Since we went in backwards order.
1743 ticks.reverse();
6821efbe 1744 }
f09e46d4 1745 }
c1bc242a 1746
6821efbe
RK
1747 // ticks.length won't be 0 if the log scale function finds values to insert.
1748 if (ticks.length == 0) {
ff022deb
RK
1749 // Basic idea:
1750 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
1751 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
1752 // The first spacing greater than pixelsPerYLabel is what we use.
1753 // TODO(danvk): version that works on a log scale.
0d64e596 1754 if (attr("labelsKMG2")) {
ff022deb 1755 var mults = [1, 2, 4, 8];
0d64e596 1756 } else {
ff022deb 1757 var mults = [1, 2, 5];
0d64e596 1758 }
ff022deb
RK
1759 var scale, low_val, high_val, nTicks;
1760 // TODO(danvk): make it possible to set this for x- and y-axes independently.
1761 var pixelsPerTick = attr('pixelsPerYLabel');
1762 for (var i = -10; i < 50; i++) {
1763 if (attr("labelsKMG2")) {
1764 var base_scale = Math.pow(16, i);
1765 } else {
1766 var base_scale = Math.pow(10, i);
1767 }
1768 for (var j = 0; j < mults.length; j++) {
1769 scale = base_scale * mults[j];
1770 low_val = Math.floor(minV / scale) * scale;
1771 high_val = Math.ceil(maxV / scale) * scale;
1772 nTicks = Math.abs(high_val - low_val) / scale;
1773 var spacing = self.height_ / nTicks;
1774 // wish I could break out of both loops at once...
1775 if (spacing > pixelsPerTick) break;
1776 }
0d64e596
DV
1777 if (spacing > pixelsPerTick) break;
1778 }
0d64e596 1779
ff022deb
RK
1780 // Construct the set of ticks.
1781 // Allow reverse y-axis if it's explicitly requested.
1782 if (low_val > high_val) scale *= -1;
1783 for (var i = 0; i < nTicks; i++) {
1784 var tickV = low_val + i * scale;
1785 ticks.push( {v: tickV} );
1786 }
0d64e596 1787 }
6a1aa64f
DV
1788 }
1789
0d64e596 1790 // Add formatted labels to the ticks.
ed11be50
DV
1791 var k;
1792 var k_labels = [];
f09fc545 1793 if (attr("labelsKMB")) {
ed11be50
DV
1794 k = 1000;
1795 k_labels = [ "K", "M", "B", "T" ];
1796 }
f09fc545 1797 if (attr("labelsKMG2")) {
ed11be50
DV
1798 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1799 k = 1024;
1800 k_labels = [ "k", "M", "G", "T" ];
1801 }
3c1d225b
JB
1802 var formatter = attr('yAxisLabelFormatter') ?
1803 attr('yAxisLabelFormatter') : attr('yValueFormatter');
1804
0cfa06d1 1805 // Add labels to the ticks.
0d64e596 1806 for (var i = 0; i < ticks.length; i++) {
e863a17d 1807 if (ticks[i].label !== undefined) continue; // Use current label.
0d64e596 1808 var tickV = ticks[i].v;
0af6e346 1809 var absTickV = Math.abs(tickV);
2e1fcf1a 1810 var label = formatter(tickV, self);
3c1d225b 1811 if (k_labels.length > 0) {
ed11be50
DV
1812 // Round up to an appropriate unit.
1813 var n = k*k*k*k;
1814 for (var j = 3; j >= 0; j--, n /= k) {
1815 if (absTickV >= n) {
17d0210c 1816 label = Dygraph.round_(tickV / n, attr('digitsAfterDecimal')) + k_labels[j];
ed11be50
DV
1817 break;
1818 }
afefbcdb 1819 }
6a1aa64f 1820 }
d916677a 1821 ticks[i].label = label;
6a1aa64f 1822 }
d916677a 1823
032e4c1d 1824 return ticks;
6a1aa64f
DV
1825};
1826
629a09ae
DV
1827/**
1828 * @private
1829 * Computes the range of the data series (including confidence intervals).
1830 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
1831 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
1832 * @return [low, high]
1833 */
5011e7a1
DV
1834Dygraph.prototype.extremeValues_ = function(series) {
1835 var minY = null, maxY = null;
1836
9922b78b 1837 var bars = this.attr_("errorBars") || this.attr_("customBars");
5011e7a1
DV
1838 if (bars) {
1839 // With custom bars, maxY is the max of the high values.
1840 for (var j = 0; j < series.length; j++) {
1841 var y = series[j][1][0];
1842 if (!y) continue;
1843 var low = y - series[j][1][1];
1844 var high = y + series[j][1][2];
1845 if (low > y) low = y; // this can happen with custom bars,
1846 if (high < y) high = y; // e.g. in tests/custom-bars.html
1847 if (maxY == null || high > maxY) {
1848 maxY = high;
1849 }
1850 if (minY == null || low < minY) {
1851 minY = low;
1852 }
1853 }
1854 } else {
1855 for (var j = 0; j < series.length; j++) {
1856 var y = series[j][1];
d12999d3 1857 if (y === null || isNaN(y)) continue;
5011e7a1
DV
1858 if (maxY == null || y > maxY) {
1859 maxY = y;
1860 }
1861 if (minY == null || y < minY) {
1862 minY = y;
1863 }
1864 }
1865 }
1866
1867 return [minY, maxY];
1868};
1869
6a1aa64f 1870/**
629a09ae 1871 * @private
26ca7938
DV
1872 * This function is called once when the chart's data is changed or the options
1873 * dictionary is updated. It is _not_ called when the user pans or zooms. The
1874 * idea is that values derived from the chart's data can be computed here,
1875 * rather than every time the chart is drawn. This includes things like the
1876 * number of axes, rolling averages, etc.
1877 */
1878Dygraph.prototype.predraw_ = function() {
7153e001
DV
1879 var start = new Date();
1880
26ca7938
DV
1881 // TODO(danvk): move more computations out of drawGraph_ and into here.
1882 this.computeYAxes_();
1883
1884 // Create a new plotter.
70c80071 1885 if (this.plotter_) this.plotter_.clear();
26ca7938 1886 this.plotter_ = new DygraphCanvasRenderer(this,
2cf95fff
RK
1887 this.hidden_,
1888 this.hidden_ctx_,
0e23cfc6 1889 this.layout_);
26ca7938 1890
0abfbd7e
DV
1891 // The roller sits in the bottom left corner of the chart. We don't know where
1892 // this will be until the options are available, so it's positioned here.
8c69de65 1893 this.createRollInterface_();
26ca7938 1894
0abfbd7e
DV
1895 // Same thing applies for the labelsDiv. It's right edge should be flush with
1896 // the right edge of the charting area (which may not be the same as the right
1897 // edge of the div, if we have two y-axes.
1898 this.positionLabelsDiv_();
1899
26ca7938
DV
1900 // If the data or options have changed, then we'd better redraw.
1901 this.drawGraph_();
1902};
1903
1904/**
1905 * Update the graph with new data. This method is called when the viewing area
1906 * has changed. If the underlying data or options have changed, predraw_ will
1907 * be called before drawGraph_ is called.
fc4e84fa
RK
1908 *
1909 * clearSelection, when undefined or true, causes this.clearSelection to be
1910 * called at the end of the draw operation. This should rarely be defined,
1911 * and never true (that is it should be undefined most of the time, and
1912 * rarely false.)
1913 *
6a1aa64f
DV
1914 * @private
1915 */
fc4e84fa 1916Dygraph.prototype.drawGraph_ = function(clearSelection) {
7153e001
DV
1917 var start = new Date();
1918
c682f205 1919 if (typeof(clearSelection) === 'undefined') {
fc4e84fa
RK
1920 clearSelection = true;
1921 }
1922
26ca7938
DV
1923 var data = this.rawData_;
1924
fe0b7c03
DV
1925 // This is used to set the second parameter to drawCallback, below.
1926 var is_initial_draw = this.is_initial_draw_;
1927 this.is_initial_draw_ = false;
1928
3bd9c228 1929 var minY = null, maxY = null;
6a1aa64f 1930 this.layout_.removeAllDatasets();
285a6bda 1931 this.setColors_();
9317362d 1932 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
285a6bda 1933
354e15ab
DE
1934 // Loop over the fields (series). Go from the last to the first,
1935 // because if they're stacked that's how we accumulate the values.
43af96e7 1936
354e15ab
DE
1937 var cumulative_y = []; // For stacked series.
1938 var datasets = [];
1939
f09fc545
DV
1940 var extremes = {}; // series name -> [low, high]
1941
354e15ab
DE
1942 // Loop over all fields and create datasets
1943 for (var i = data[0].length - 1; i >= 1; i--) {
1cf11047
DV
1944 if (!this.visibility()[i - 1]) continue;
1945
f09fc545 1946 var seriesName = this.attr_("labels")[i];
450fe64b 1947 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
6e6a2b0a 1948 var logScale = this.attr_('logscale', i);
450fe64b 1949
6a1aa64f
DV
1950 var series = [];
1951 for (var j = 0; j < data.length; j++) {
6e6a2b0a
RK
1952 var date = data[j][0];
1953 var point = data[j][i];
1954 if (logScale) {
1955 // On the log scale, points less than zero do not exist.
1956 // This will create a gap in the chart. Note that this ignores
1957 // connectSeparatedPoints.
e863a17d 1958 if (point <= 0) {
6e6a2b0a
RK
1959 point = null;
1960 }
1961 series.push([date, point]);
1962 } else {
1963 if (point != null || !connectSeparatedPoints) {
1964 series.push([date, point]);
1965 }
f032c51d 1966 }
6a1aa64f 1967 }
2f5e7e1a
DV
1968
1969 // TODO(danvk): move this into predraw_. It's insane to do it here.
6a1aa64f
DV
1970 series = this.rollingAverage(series, this.rollPeriod_);
1971
1972 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
1973 // Because there can be lines going to points outside of the visible area,
1974 // we actually prune to visible points, plus one on either side.
9922b78b 1975 var bars = this.attr_("errorBars") || this.attr_("customBars");
6a1aa64f
DV
1976 if (this.dateWindow_) {
1977 var low = this.dateWindow_[0];
1978 var high= this.dateWindow_[1];
1979 var pruned = [];
1a26f3fb
DV
1980 // TODO(danvk): do binary search instead of linear search.
1981 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
1982 var firstIdx = null, lastIdx = null;
6a1aa64f 1983 for (var k = 0; k < series.length; k++) {
1a26f3fb
DV
1984 if (series[k][0] >= low && firstIdx === null) {
1985 firstIdx = k;
1986 }
1987 if (series[k][0] <= high) {
1988 lastIdx = k;
6a1aa64f
DV
1989 }
1990 }
1a26f3fb
DV
1991 if (firstIdx === null) firstIdx = 0;
1992 if (firstIdx > 0) firstIdx--;
1993 if (lastIdx === null) lastIdx = series.length - 1;
1994 if (lastIdx < series.length - 1) lastIdx++;
16269f6e 1995 this.boundaryIds_[i-1] = [firstIdx, lastIdx];
1a26f3fb
DV
1996 for (var k = firstIdx; k <= lastIdx; k++) {
1997 pruned.push(series[k]);
6a1aa64f
DV
1998 }
1999 series = pruned;
16269f6e
NAG
2000 } else {
2001 this.boundaryIds_[i-1] = [0, series.length-1];
6a1aa64f
DV
2002 }
2003
f09fc545 2004 var seriesExtremes = this.extremeValues_(series);
5011e7a1 2005
6a1aa64f 2006 if (bars) {
354e15ab
DE
2007 for (var j=0; j<series.length; j++) {
2008 val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]];
2009 series[j] = val;
2010 }
43af96e7 2011 } else if (this.attr_("stackedGraph")) {
43af96e7
NK
2012 var l = series.length;
2013 var actual_y;
2014 for (var j = 0; j < l; j++) {
354e15ab
DE
2015 // If one data set has a NaN, let all subsequent stacked
2016 // sets inherit the NaN -- only start at 0 for the first set.
2017 var x = series[j][0];
41b0f691 2018 if (cumulative_y[x] === undefined) {
354e15ab 2019 cumulative_y[x] = 0;
41b0f691 2020 }
43af96e7
NK
2021
2022 actual_y = series[j][1];
354e15ab 2023 cumulative_y[x] += actual_y;
43af96e7 2024
354e15ab 2025 series[j] = [x, cumulative_y[x]]
43af96e7 2026
41b0f691
DV
2027 if (cumulative_y[x] > seriesExtremes[1]) {
2028 seriesExtremes[1] = cumulative_y[x];
2029 }
2030 if (cumulative_y[x] < seriesExtremes[0]) {
2031 seriesExtremes[0] = cumulative_y[x];
2032 }
43af96e7 2033 }
6a1aa64f 2034 }
41b0f691 2035 extremes[seriesName] = seriesExtremes;
354e15ab
DE
2036
2037 datasets[i] = series;
6a1aa64f
DV
2038 }
2039
354e15ab 2040 for (var i = 1; i < datasets.length; i++) {
4523c1f6 2041 if (!this.visibility()[i - 1]) continue;
354e15ab 2042 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
43af96e7
NK
2043 }
2044
6faebb69 2045 this.computeYAxisRanges_(extremes);
b2c9222a
DV
2046 this.layout_.setYAxes(this.axes_);
2047
6a1aa64f
DV
2048 this.addXTicks_();
2049
b2c9222a 2050 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
81856f70 2051 var tmp_zoomed_x = this.zoomed_x_;
6a1aa64f 2052 // Tell PlotKit to use this new data and render itself
b2c9222a 2053 this.layout_.setDateWindow(this.dateWindow_);
81856f70 2054 this.zoomed_x_ = tmp_zoomed_x;
6a1aa64f
DV
2055 this.layout_.evaluateWithError();
2056 this.plotter_.clear();
2057 this.plotter_.render();
f6401bf6 2058 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2f5e7e1a 2059 this.canvas_.height);
599fb4ad 2060
2fccd3dc
DV
2061 if (is_initial_draw) {
2062 // Generate a static legend before any particular point is selected.
91c10d9c 2063 this.setLegendHTML_();
06303c32 2064 } else {
fc4e84fa
RK
2065 if (clearSelection) {
2066 if (typeof(this.selPoints_) !== 'undefined' && this.selPoints_.length) {
2067 // We should select the point nearest the page x/y here, but it's easier
2068 // to just clear the selection. This prevents erroneous hover dots from
2069 // being displayed.
2070 this.clearSelection();
2071 } else {
2072 this.clearSelection();
2073 }
06303c32 2074 }
2fccd3dc
DV
2075 }
2076
599fb4ad 2077 if (this.attr_("drawCallback") !== null) {
fe0b7c03 2078 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 2079 }
7153e001
DV
2080
2081 if (this.attr_("timingName")) {
2082 var end = new Date();
2083 if (console) {
2084 console.log(this.attr_("timingName") + " - drawGraph: " + (end - start) + "ms")
2085 }
2086 }
6a1aa64f
DV
2087};
2088
2089/**
629a09ae 2090 * @private
26ca7938
DV
2091 * Determine properties of the y-axes which are independent of the data
2092 * currently being displayed. This includes things like the number of axes and
2093 * the style of the axes. It does not include the range of each axis and its
2094 * tick marks.
2095 * This fills in this.axes_ and this.seriesToAxisMap_.
2096 * axes_ = [ { options } ]
2097 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2098 * indices are into the axes_ array.
f09fc545 2099 */
26ca7938 2100Dygraph.prototype.computeYAxes_ = function() {
d64b8fea
RK
2101 // Preserve valueWindow settings if they exist, and if the user hasn't
2102 // specified a new valueRange.
2103 var valueWindows;
2104 if (this.axes_ != undefined && this.user_attrs_.hasOwnProperty("valueRange") == false) {
2105 valueWindows = [];
2106 for (var index = 0; index < this.axes_.length; index++) {
2107 valueWindows.push(this.axes_[index].valueWindow);
2108 }
2109 }
2110
2111
00aa7f61 2112 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
26ca7938
DV
2113 this.seriesToAxisMap_ = {};
2114
2115 // Get a list of series names.
2116 var labels = this.attr_("labels");
1c77a3a1 2117 var series = {};
26ca7938 2118 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
f09fc545
DV
2119
2120 // all options which could be applied per-axis:
2121 var axisOptions = [
2122 'includeZero',
2123 'valueRange',
2124 'labelsKMB',
2125 'labelsKMG2',
2126 'pixelsPerYLabel',
2127 'yAxisLabelWidth',
2128 'axisLabelFontSize',
7d0e7a0d
RK
2129 'axisTickSize',
2130 'logscale'
f09fc545
DV
2131 ];
2132
2133 // Copy global axis options over to the first axis.
2134 for (var i = 0; i < axisOptions.length; i++) {
2135 var k = axisOptions[i];
2136 var v = this.attr_(k);
26ca7938 2137 if (v) this.axes_[0][k] = v;
f09fc545
DV
2138 }
2139
2140 // Go through once and add all the axes.
26ca7938
DV
2141 for (var seriesName in series) {
2142 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2143 var axis = this.attr_("axis", seriesName);
2144 if (axis == null) {
26ca7938 2145 this.seriesToAxisMap_[seriesName] = 0;
f09fc545
DV
2146 continue;
2147 }
2148 if (typeof(axis) == 'object') {
2149 // Add a new axis, making a copy of its per-axis options.
2150 var opts = {};
26ca7938 2151 Dygraph.update(opts, this.axes_[0]);
f09fc545 2152 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
00aa7f61
RK
2153 var yAxisId = this.axes_.length;
2154 opts.yAxisId = yAxisId;
2155 opts.g = this;
f09fc545 2156 Dygraph.update(opts, axis);
26ca7938 2157 this.axes_.push(opts);
00aa7f61 2158 this.seriesToAxisMap_[seriesName] = yAxisId;
f09fc545
DV
2159 }
2160 }
2161
2162 // Go through one more time and assign series to an axis defined by another
2163 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
26ca7938
DV
2164 for (var seriesName in series) {
2165 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2166 var axis = this.attr_("axis", seriesName);
2167 if (typeof(axis) == 'string') {
26ca7938 2168 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
f09fc545
DV
2169 this.error("Series " + seriesName + " wants to share a y-axis with " +
2170 "series " + axis + ", which does not define its own axis.");
2171 return null;
2172 }
26ca7938
DV
2173 var idx = this.seriesToAxisMap_[axis];
2174 this.seriesToAxisMap_[seriesName] = idx;
f09fc545
DV
2175 }
2176 }
1c77a3a1
DV
2177
2178 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2179 // this last so that hiding the first series doesn't destroy the axis
2180 // properties of the primary axis.
2181 var seriesToAxisFiltered = {};
2182 var vis = this.visibility();
2183 for (var i = 1; i < labels.length; i++) {
2184 var s = labels[i];
2185 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2186 }
2187 this.seriesToAxisMap_ = seriesToAxisFiltered;
d64b8fea
RK
2188
2189 if (valueWindows != undefined) {
2190 // Restore valueWindow settings.
2191 for (var index = 0; index < valueWindows.length; index++) {
2192 this.axes_[index].valueWindow = valueWindows[index];
2193 }
2194 }
26ca7938
DV
2195};
2196
2197/**
2198 * Returns the number of y-axes on the chart.
2199 * @return {Number} the number of axes.
2200 */
2201Dygraph.prototype.numAxes = function() {
2202 var last_axis = 0;
2203 for (var series in this.seriesToAxisMap_) {
2204 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2205 var idx = this.seriesToAxisMap_[series];
2206 if (idx > last_axis) last_axis = idx;
2207 }
2208 return 1 + last_axis;
2209};
2210
2211/**
629a09ae 2212 * @private
b2c9222a
DV
2213 * Returns axis properties for the given series.
2214 * @param { String } setName The name of the series for which to get axis
2215 * properties, e.g. 'Y1'.
2216 * @return { Object } The axis properties.
2217 */
2218Dygraph.prototype.axisPropertiesForSeries = function(series) {
2219 // TODO(danvk): handle errors.
2220 return this.axes_[this.seriesToAxisMap_[series]];
2221};
2222
2223/**
2224 * @private
26ca7938
DV
2225 * Determine the value range and tick marks for each axis.
2226 * @param {Object} extremes A mapping from seriesName -> [low, high]
2227 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2228 */
2229Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2230 // Build a map from axis number -> [list of series names]
2231 var seriesForAxis = [];
2232 for (var series in this.seriesToAxisMap_) {
2233 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2234 var idx = this.seriesToAxisMap_[series];
2235 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2236 seriesForAxis[idx].push(series);
2237 }
f09fc545
DV
2238
2239 // Compute extreme values, a span and tick marks for each axis.
26ca7938
DV
2240 for (var i = 0; i < this.axes_.length; i++) {
2241 var axis = this.axes_[i];
25f76ae3 2242
06fc69b6
AV
2243 if (!seriesForAxis[i]) {
2244 // If no series are defined or visible then use a reasonable default
2245 axis.extremeRange = [0, 1];
2246 } else {
1c77a3a1 2247 // Calculate the extremes of extremes.
f09fc545
DV
2248 var series = seriesForAxis[i];
2249 var minY = Infinity; // extremes[series[0]][0];
2250 var maxY = -Infinity; // extremes[series[0]][1];
ba049b89 2251 var extremeMinY, extremeMaxY;
f09fc545 2252 for (var j = 0; j < series.length; j++) {
ba049b89
NN
2253 // Only use valid extremes to stop null data series' from corrupting the scale.
2254 extremeMinY = extremes[series[j]][0];
2255 if (extremeMinY != null) {
36dfa958 2256 minY = Math.min(extremeMinY, minY);
ba049b89
NN
2257 }
2258 extremeMaxY = extremes[series[j]][1];
2259 if (extremeMaxY != null) {
36dfa958 2260 maxY = Math.max(extremeMaxY, maxY);
ba049b89 2261 }
f09fc545
DV
2262 }
2263 if (axis.includeZero && minY > 0) minY = 0;
2264
ba049b89 2265 // Ensure we have a valid scale, otherwise defualt to zero for safety.
36dfa958
DV
2266 if (minY == Infinity) minY = 0;
2267 if (maxY == -Infinity) maxY = 0;
ba049b89 2268
f09fc545
DV
2269 // Add some padding and round up to an integer to be human-friendly.
2270 var span = maxY - minY;
2271 // special case: if we have no sense of scale, use +/-10% of the sole value.
2272 if (span == 0) { span = maxY; }
f09fc545 2273
ff022deb
RK
2274 var maxAxisY;
2275 var minAxisY;
7d0e7a0d 2276 if (axis.logscale) {
ff022deb
RK
2277 var maxAxisY = maxY + 0.1 * span;
2278 var minAxisY = minY;
2279 } else {
2280 var maxAxisY = maxY + 0.1 * span;
2281 var minAxisY = minY - 0.1 * span;
f09fc545 2282
ff022deb
RK
2283 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2284 if (!this.attr_("avoidMinZero")) {
2285 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2286 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2287 }
f09fc545 2288
ff022deb
RK
2289 if (this.attr_("includeZero")) {
2290 if (maxY < 0) maxAxisY = 0;
2291 if (minY > 0) minAxisY = 0;
2292 }
f09fc545 2293 }
4cac8c7a
RK
2294 axis.extremeRange = [minAxisY, maxAxisY];
2295 }
2296 if (axis.valueWindow) {
2297 // This is only set if the user has zoomed on the y-axis. It is never set
2298 // by a user. It takes precedence over axis.valueRange because, if you set
2299 // valueRange, you'd still expect to be able to pan.
2300 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2301 } else if (axis.valueRange) {
2302 // This is a user-set value range for this axis.
2303 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
2304 } else {
2305 axis.computedValueRange = axis.extremeRange;
f09fc545
DV
2306 }
2307
0d64e596
DV
2308 // Add ticks. By default, all axes inherit the tick positions of the
2309 // primary axis. However, if an axis is specifically marked as having
2310 // independent ticks, then that is permissible as well.
2311 if (i == 0 || axis.independentTicks) {
032e4c1d 2312 axis.ticks =
0d64e596
DV
2313 Dygraph.numericTicks(axis.computedValueRange[0],
2314 axis.computedValueRange[1],
2315 this,
2316 axis);
2317 } else {
2318 var p_axis = this.axes_[0];
2319 var p_ticks = p_axis.ticks;
2320 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2321 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2322 var tick_values = [];
25f76ae3
DV
2323 for (var k = 0; k < p_ticks.length; k++) {
2324 var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
0d64e596
DV
2325 var y_val = axis.computedValueRange[0] + y_frac * scale;
2326 tick_values.push(y_val);
2327 }
2328
032e4c1d 2329 axis.ticks =
0d64e596
DV
2330 Dygraph.numericTicks(axis.computedValueRange[0],
2331 axis.computedValueRange[1],
2332 this, axis, tick_values);
2333 }
f09fc545 2334 }
f09fc545 2335};
25f76ae3 2336
f09fc545 2337/**
629a09ae 2338 * @private
6a1aa64f
DV
2339 * Calculates the rolling average of a data set.
2340 * If originalData is [label, val], rolls the average of those.
2341 * If originalData is [label, [, it's interpreted as [value, stddev]
2342 * and the roll is returned in the same form, with appropriately reduced
2343 * stddev for each value.
2344 * Note that this is where fractional input (i.e. '5/10') is converted into
2345 * decimal values.
2346 * @param {Array} originalData The data in the appropriate format (see above)
6faebb69
JB
2347 * @param {Number} rollPeriod The number of points over which to average the
2348 * data
6a1aa64f 2349 */
285a6bda 2350Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
2351 if (originalData.length < 2)
2352 return originalData;
2353 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
2354 var rollingData = [];
285a6bda 2355 var sigma = this.attr_("sigma");
6a1aa64f
DV
2356
2357 if (this.fractions_) {
2358 var num = 0;
2359 var den = 0; // numerator/denominator
2360 var mult = 100.0;
2361 for (var i = 0; i < originalData.length; i++) {
2362 num += originalData[i][1][0];
2363 den += originalData[i][1][1];
2364 if (i - rollPeriod >= 0) {
2365 num -= originalData[i - rollPeriod][1][0];
2366 den -= originalData[i - rollPeriod][1][1];
2367 }
2368
2369 var date = originalData[i][0];
2370 var value = den ? num / den : 0.0;
285a6bda 2371 if (this.attr_("errorBars")) {
6a1aa64f
DV
2372 if (this.wilsonInterval_) {
2373 // For more details on this confidence interval, see:
2374 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
2375 if (den) {
2376 var p = value < 0 ? 0 : value, n = den;
2377 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
2378 var denom = 1 + sigma * sigma / den;
2379 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
2380 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
2381 rollingData[i] = [date,
2382 [p * mult, (p - low) * mult, (high - p) * mult]];
2383 } else {
2384 rollingData[i] = [date, [0, 0, 0]];
2385 }
2386 } else {
2387 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
2388 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
2389 }
2390 } else {
2391 rollingData[i] = [date, mult * value];
2392 }
2393 }
9922b78b 2394 } else if (this.attr_("customBars")) {
f6885d6a
DV
2395 var low = 0;
2396 var mid = 0;
2397 var high = 0;
2398 var count = 0;
6a1aa64f
DV
2399 for (var i = 0; i < originalData.length; i++) {
2400 var data = originalData[i][1];
2401 var y = data[1];
2402 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 2403
8b91c51f 2404 if (y != null && !isNaN(y)) {
49a7d0d5
DV
2405 low += data[0];
2406 mid += y;
2407 high += data[2];
2408 count += 1;
2409 }
f6885d6a
DV
2410 if (i - rollPeriod >= 0) {
2411 var prev = originalData[i - rollPeriod];
8b91c51f 2412 if (prev[1][1] != null && !isNaN(prev[1][1])) {
49a7d0d5
DV
2413 low -= prev[1][0];
2414 mid -= prev[1][1];
2415 high -= prev[1][2];
2416 count -= 1;
2417 }
f6885d6a 2418 }
502d5996
DV
2419 if (count) {
2420 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
2421 1.0 * (mid - low) / count,
2422 1.0 * (high - mid) / count ]];
2423 } else {
2424 rollingData[i] = [originalData[i][0], [null, null, null]];
2425 }
2769de62 2426 }
6a1aa64f
DV
2427 } else {
2428 // Calculate the rolling average for the first rollPeriod - 1 points where
6faebb69 2429 // there is not enough data to roll over the full number of points
6a1aa64f 2430 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 2431 if (!this.attr_("errorBars")){
5011e7a1
DV
2432 if (rollPeriod == 1) {
2433 return originalData;
2434 }
2435
2847c1cf 2436 for (var i = 0; i < originalData.length; i++) {
6a1aa64f 2437 var sum = 0;
5011e7a1 2438 var num_ok = 0;
2847c1cf
DV
2439 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2440 var y = originalData[j][1];
8b91c51f 2441 if (y == null || isNaN(y)) continue;
5011e7a1 2442 num_ok++;
2847c1cf 2443 sum += originalData[j][1];
6a1aa64f 2444 }
5011e7a1 2445 if (num_ok) {
2847c1cf 2446 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 2447 } else {
2847c1cf 2448 rollingData[i] = [originalData[i][0], null];
5011e7a1 2449 }
6a1aa64f 2450 }
2847c1cf
DV
2451
2452 } else {
2453 for (var i = 0; i < originalData.length; i++) {
6a1aa64f
DV
2454 var sum = 0;
2455 var variance = 0;
5011e7a1 2456 var num_ok = 0;
2847c1cf 2457 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
5011e7a1 2458 var y = originalData[j][1][0];
8b91c51f 2459 if (y == null || isNaN(y)) continue;
5011e7a1 2460 num_ok++;
6a1aa64f
DV
2461 sum += originalData[j][1][0];
2462 variance += Math.pow(originalData[j][1][1], 2);
2463 }
5011e7a1
DV
2464 if (num_ok) {
2465 var stddev = Math.sqrt(variance) / num_ok;
2466 rollingData[i] = [originalData[i][0],
2467 [sum / num_ok, sigma * stddev, sigma * stddev]];
2468 } else {
2469 rollingData[i] = [originalData[i][0], [null, null, null]];
2470 }
6a1aa64f
DV
2471 }
2472 }
2473 }
2474
2475 return rollingData;
2476};
2477
2478/**
285a6bda
DV
2479 * Detects the type of the str (date or numeric) and sets the various
2480 * formatting attributes in this.attrs_ based on this type.
2481 * @param {String} str An x value.
2482 * @private
2483 */
2484Dygraph.prototype.detectTypeFromString_ = function(str) {
2485 var isDate = false;
ea62df82 2486 if (str.indexOf('-') > 0 ||
285a6bda
DV
2487 str.indexOf('/') >= 0 ||
2488 isNaN(parseFloat(str))) {
2489 isDate = true;
2490 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2491 // TODO(danvk): remove support for this format.
2492 isDate = true;
2493 }
2494
2495 if (isDate) {
2496 this.attrs_.xValueFormatter = Dygraph.dateString_;
2497 this.attrs_.xValueParser = Dygraph.dateParser;
2498 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 2499 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda 2500 } else {
17d0210c 2501 // TODO(danvk): use Dygraph.numberFormatter here?
c39e1d93 2502 /** @private (shut up, jsdoc!) */
032e4c1d 2503 this.attrs_.xValueFormatter = function(x) { return x; };
c39e1d93 2504 /** @private (shut up, jsdoc!) */
285a6bda
DV
2505 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2506 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 2507 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
6a1aa64f 2508 }
6a1aa64f
DV
2509};
2510
2511/**
5cd7ac68
DV
2512 * Parses the value as a floating point number. This is like the parseFloat()
2513 * built-in, but with a few differences:
2514 * - the empty string is parsed as null, rather than NaN.
2515 * - if the string cannot be parsed at all, an error is logged.
2516 * If the string can't be parsed, this method returns null.
2517 * @param {String} x The string to be parsed
2518 * @param {Number} opt_line_no The line number from which the string comes.
2519 * @param {String} opt_line The text of the line from which the string comes.
2520 * @private
2521 */
2522
2523// Parse the x as a float or return null if it's not a number.
2524Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
2525 var val = parseFloat(x);
2526 if (!isNaN(val)) return val;
2527
2528 // Try to figure out what happeend.
2529 // If the value is the empty string, parse it as null.
2530 if (/^ *$/.test(x)) return null;
2531
2532 // If it was actually "NaN", return it as NaN.
2533 if (/^ *nan *$/i.test(x)) return NaN;
2534
2535 // Looks like a parsing error.
2536 var msg = "Unable to parse '" + x + "' as a number";
2537 if (opt_line !== null && opt_line_no !== null) {
2538 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
2539 }
2540 this.error(msg);
2541
2542 return null;
2543};
2544
2545/**
629a09ae 2546 * @private
6a1aa64f
DV
2547 * Parses a string in a special csv format. We expect a csv file where each
2548 * line is a date point, and the first field in each line is the date string.
2549 * We also expect that all remaining fields represent series.
285a6bda 2550 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f 2551 * date, series1, stddev1, series2, stddev2, ...
629a09ae 2552 * @param {[Object]} data See above.
285a6bda 2553 *
629a09ae 2554 * @return [Object] An array with one entry for each row. These entries
285a6bda
DV
2555 * are an array of cells in that row. The first entry is the parsed x-value for
2556 * the row. The second, third, etc. are the y-values. These can take on one of
2557 * three forms, depending on the CSV and constructor parameters:
2558 * 1. numeric value
2559 * 2. [ value, stddev ]
2560 * 3. [ low value, center value, high value ]
6a1aa64f 2561 */
285a6bda 2562Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
2563 var ret = [];
2564 var lines = data.split("\n");
3d67f03b
DV
2565
2566 // Use the default delimiter or fall back to a tab if that makes sense.
2567 var delim = this.attr_('delimiter');
2568 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
2569 delim = '\t';
2570 }
2571
285a6bda 2572 var start = 0;
d7beab6b
DV
2573 if (!('labels' in this.user_attrs_)) {
2574 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
285a6bda 2575 start = 1;
d7beab6b 2576 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
6a1aa64f 2577 }
5cd7ac68 2578 var line_no = 0;
03b522a4 2579
285a6bda
DV
2580 var xParser;
2581 var defaultParserSet = false; // attempt to auto-detect x value type
2582 var expectedCols = this.attr_("labels").length;
987840a2 2583 var outOfOrder = false;
6a1aa64f
DV
2584 for (var i = start; i < lines.length; i++) {
2585 var line = lines[i];
5cd7ac68 2586 line_no = i;
6a1aa64f 2587 if (line.length == 0) continue; // skip blank lines
3d67f03b
DV
2588 if (line[0] == '#') continue; // skip comment lines
2589 var inFields = line.split(delim);
285a6bda 2590 if (inFields.length < 2) continue;
6a1aa64f
DV
2591
2592 var fields = [];
285a6bda
DV
2593 if (!defaultParserSet) {
2594 this.detectTypeFromString_(inFields[0]);
2595 xParser = this.attr_("xValueParser");
2596 defaultParserSet = true;
2597 }
2598 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
2599
2600 // If fractions are expected, parse the numbers as "A/B"
2601 if (this.fractions_) {
2602 for (var j = 1; j < inFields.length; j++) {
2603 // TODO(danvk): figure out an appropriate way to flag parse errors.
2604 var vals = inFields[j].split("/");
7219edb3
DV
2605 if (vals.length != 2) {
2606 this.error('Expected fractional "num/den" values in CSV data ' +
2607 "but found a value '" + inFields[j] + "' on line " +
2608 (1 + i) + " ('" + line + "') which is not of this form.");
2609 fields[j] = [0, 0];
2610 } else {
2611 fields[j] = [this.parseFloat_(vals[0], i, line),
2612 this.parseFloat_(vals[1], i, line)];
2613 }
6a1aa64f 2614 }
285a6bda 2615 } else if (this.attr_("errorBars")) {
6a1aa64f 2616 // If there are error bars, values are (value, stddev) pairs
7219edb3
DV
2617 if (inFields.length % 2 != 1) {
2618 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2619 'but line ' + (1 + i) + ' has an odd number of values (' +
2620 (inFields.length - 1) + "): '" + line + "'");
2621 }
2622 for (var j = 1; j < inFields.length; j += 2) {
5cd7ac68
DV
2623 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2624 this.parseFloat_(inFields[j + 1], i, line)];
7219edb3 2625 }
9922b78b 2626 } else if (this.attr_("customBars")) {
6a1aa64f
DV
2627 // Bars are a low;center;high tuple
2628 for (var j = 1; j < inFields.length; j++) {
327a9279
DV
2629 var val = inFields[j];
2630 if (/^ *$/.test(val)) {
2631 fields[j] = [null, null, null];
2632 } else {
2633 var vals = val.split(";");
2634 if (vals.length == 3) {
2635 fields[j] = [ this.parseFloat_(vals[0], i, line),
2636 this.parseFloat_(vals[1], i, line),
2637 this.parseFloat_(vals[2], i, line) ];
2638 } else {
2639 this.warning('When using customBars, values must be either blank ' +
2640 'or "low;center;high" tuples (got "' + val +
2641 '" on line ' + (1+i));
2642 }
2643 }
6a1aa64f
DV
2644 }
2645 } else {
2646 // Values are just numbers
285a6bda 2647 for (var j = 1; j < inFields.length; j++) {
5cd7ac68 2648 fields[j] = this.parseFloat_(inFields[j], i, line);
285a6bda 2649 }
6a1aa64f 2650 }
987840a2
DV
2651 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2652 outOfOrder = true;
2653 }
285a6bda
DV
2654
2655 if (fields.length != expectedCols) {
2656 this.error("Number of columns in line " + i + " (" + fields.length +
2657 ") does not agree with number of labels (" + expectedCols +
2658 ") " + line);
2659 }
6d0aaa09
DV
2660
2661 // If the user specified the 'labels' option and none of the cells of the
2662 // first row parsed correctly, then they probably double-specified the
2663 // labels. We go with the values set in the option, discard this row and
2664 // log a warning to the JS console.
2665 if (i == 0 && this.attr_('labels')) {
2666 var all_null = true;
2667 for (var j = 0; all_null && j < fields.length; j++) {
2668 if (fields[j]) all_null = false;
2669 }
2670 if (all_null) {
2671 this.warn("The dygraphs 'labels' option is set, but the first row of " +
2672 "CSV data ('" + line + "') appears to also contain labels. " +
2673 "Will drop the CSV labels and use the option labels.");
2674 continue;
2675 }
2676 }
2677 ret.push(fields);
6a1aa64f 2678 }
987840a2
DV
2679
2680 if (outOfOrder) {
2681 this.warn("CSV is out of order; order it correctly to speed loading.");
2682 ret.sort(function(a,b) { return a[0] - b[0] });
2683 }
2684
6a1aa64f
DV
2685 return ret;
2686};
2687
2688/**
629a09ae 2689 * @private
285a6bda
DV
2690 * The user has provided their data as a pre-packaged JS array. If the x values
2691 * are numeric, this is the same as dygraphs' internal format. If the x values
2692 * are dates, we need to convert them from Date objects to ms since epoch.
629a09ae
DV
2693 * @param {[Object]} data
2694 * @return {[Object]} data with numeric x values.
285a6bda
DV
2695 */
2696Dygraph.prototype.parseArray_ = function(data) {
2697 // Peek at the first x value to see if it's numeric.
2698 if (data.length == 0) {
2699 this.error("Can't plot empty data set");
2700 return null;
2701 }
2702 if (data[0].length == 0) {
2703 this.error("Data set cannot contain an empty row");
2704 return null;
2705 }
2706
2707 if (this.attr_("labels") == null) {
2708 this.warn("Using default labels. Set labels explicitly via 'labels' " +
2709 "in the options parameter");
2710 this.attrs_.labels = [ "X" ];
2711 for (var i = 1; i < data[0].length; i++) {
2712 this.attrs_.labels.push("Y" + i);
2713 }
2714 }
2715
2dda3850 2716 if (Dygraph.isDateLike(data[0][0])) {
285a6bda
DV
2717 // Some intelligent defaults for a date x-axis.
2718 this.attrs_.xValueFormatter = Dygraph.dateString_;
bf640e56 2719 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda
DV
2720 this.attrs_.xTicker = Dygraph.dateTicker;
2721
2722 // Assume they're all dates.
e3ab7b40 2723 var parsedData = Dygraph.clone(data);
285a6bda
DV
2724 for (var i = 0; i < data.length; i++) {
2725 if (parsedData[i].length == 0) {
a323ff4a 2726 this.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
2727 return null;
2728 }
2729 if (parsedData[i][0] == null
3a909ec5
DV
2730 || typeof(parsedData[i][0].getTime) != 'function'
2731 || isNaN(parsedData[i][0].getTime())) {
be96a1f5 2732 this.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
2733 return null;
2734 }
2735 parsedData[i][0] = parsedData[i][0].getTime();
2736 }
2737 return parsedData;
2738 } else {
2739 // Some intelligent defaults for a numeric x-axis.
c39e1d93 2740 /** @private (shut up, jsdoc!) */
032e4c1d 2741 this.attrs_.xValueFormatter = function(x) { return x; };
285a6bda
DV
2742 this.attrs_.xTicker = Dygraph.numericTicks;
2743 return data;
2744 }
2745};
2746
2747/**
79420a1e
DV
2748 * Parses a DataTable object from gviz.
2749 * The data is expected to have a first column that is either a date or a
2750 * number. All subsequent columns must be numbers. If there is a clear mismatch
2751 * between this.xValueParser_ and the type of the first column, it will be
a685723c 2752 * fixed. Fills out rawData_.
629a09ae 2753 * @param {[Object]} data See above.
79420a1e
DV
2754 * @private
2755 */
285a6bda 2756Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
2757 var cols = data.getNumberOfColumns();
2758 var rows = data.getNumberOfRows();
2759
d955e223 2760 var indepType = data.getColumnType(0);
4440f6c8 2761 if (indepType == 'date' || indepType == 'datetime') {
285a6bda
DV
2762 this.attrs_.xValueFormatter = Dygraph.dateString_;
2763 this.attrs_.xValueParser = Dygraph.dateParser;
2764 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 2765 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
33127159 2766 } else if (indepType == 'number') {
032e4c1d 2767 this.attrs_.xValueFormatter = function(x) { return x; };
285a6bda
DV
2768 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2769 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 2770 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
285a6bda 2771 } else {
987840a2
DV
2772 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2773 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
2774 return null;
2775 }
2776
a685723c
DV
2777 // Array of the column indices which contain data (and not annotations).
2778 var colIdx = [];
2779 var annotationCols = {}; // data index -> [annotation cols]
2780 var hasAnnotations = false;
2781 for (var i = 1; i < cols; i++) {
2782 var type = data.getColumnType(i);
2783 if (type == 'number') {
2784 colIdx.push(i);
2785 } else if (type == 'string' && this.attr_('displayAnnotations')) {
2786 // This is OK -- it's an annotation column.
2787 var dataIdx = colIdx[colIdx.length - 1];
2788 if (!annotationCols.hasOwnProperty(dataIdx)) {
2789 annotationCols[dataIdx] = [i];
2790 } else {
2791 annotationCols[dataIdx].push(i);
2792 }
2793 hasAnnotations = true;
2794 } else {
2795 this.error("Only 'number' is supported as a dependent type with Gviz." +
2796 " 'string' is only supported if displayAnnotations is true");
2797 }
2798 }
2799
2800 // Read column labels
2801 // TODO(danvk): add support back for errorBars
2802 var labels = [data.getColumnLabel(0)];
2803 for (var i = 0; i < colIdx.length; i++) {
2804 labels.push(data.getColumnLabel(colIdx[i]));
f9348814 2805 if (this.attr_("errorBars")) i += 1;
a685723c
DV
2806 }
2807 this.attrs_.labels = labels;
2808 cols = labels.length;
2809
79420a1e 2810 var ret = [];
987840a2 2811 var outOfOrder = false;
a685723c 2812 var annotations = [];
79420a1e
DV
2813 for (var i = 0; i < rows; i++) {
2814 var row = [];
debe4434
DV
2815 if (typeof(data.getValue(i, 0)) === 'undefined' ||
2816 data.getValue(i, 0) === null) {
129569a5
FD
2817 this.warn("Ignoring row " + i +
2818 " of DataTable because of undefined or null first column.");
debe4434
DV
2819 continue;
2820 }
2821
c21d2c2d 2822 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
2823 row.push(data.getValue(i, 0).getTime());
2824 } else {
2825 row.push(data.getValue(i, 0));
2826 }
3e3f84e4 2827 if (!this.attr_("errorBars")) {
a685723c
DV
2828 for (var j = 0; j < colIdx.length; j++) {
2829 var col = colIdx[j];
2830 row.push(data.getValue(i, col));
2831 if (hasAnnotations &&
2832 annotationCols.hasOwnProperty(col) &&
2833 data.getValue(i, annotationCols[col][0]) != null) {
2834 var ann = {};
2835 ann.series = data.getColumnLabel(col);
2836 ann.xval = row[0];
2837 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
2838 ann.text = '';
2839 for (var k = 0; k < annotationCols[col].length; k++) {
2840 if (k) ann.text += "\n";
2841 ann.text += data.getValue(i, annotationCols[col][k]);
2842 }
2843 annotations.push(ann);
2844 }
3e3f84e4 2845 }
92fd68d8
DV
2846
2847 // Strip out infinities, which give dygraphs problems later on.
2848 for (var j = 0; j < row.length; j++) {
2849 if (!isFinite(row[j])) row[j] = null;
2850 }
3e3f84e4
DV
2851 } else {
2852 for (var j = 0; j < cols - 1; j++) {
2853 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
2854 }
79420a1e 2855 }
987840a2
DV
2856 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
2857 outOfOrder = true;
2858 }
243d96e8 2859 ret.push(row);
79420a1e 2860 }
987840a2
DV
2861
2862 if (outOfOrder) {
2863 this.warn("DataTable is out of order; order it correctly to speed loading.");
2864 ret.sort(function(a,b) { return a[0] - b[0] });
2865 }
a685723c
DV
2866 this.rawData_ = ret;
2867
2868 if (annotations.length > 0) {
2869 this.setAnnotations(annotations, true);
2870 }
79420a1e
DV
2871}
2872
629a09ae 2873/**
6a1aa64f
DV
2874 * Get the CSV data. If it's in a function, call that function. If it's in a
2875 * file, do an XMLHttpRequest to get it.
2876 * @private
2877 */
285a6bda 2878Dygraph.prototype.start_ = function() {
6a1aa64f 2879 if (typeof this.file_ == 'function') {
285a6bda 2880 // CSV string. Pretend we got it via XHR.
6a1aa64f 2881 this.loadedEvent_(this.file_());
2dda3850 2882 } else if (Dygraph.isArrayLike(this.file_)) {
285a6bda 2883 this.rawData_ = this.parseArray_(this.file_);
26ca7938 2884 this.predraw_();
79420a1e
DV
2885 } else if (typeof this.file_ == 'object' &&
2886 typeof this.file_.getColumnRange == 'function') {
2887 // must be a DataTable from gviz.
a685723c 2888 this.parseDataTable_(this.file_);
26ca7938 2889 this.predraw_();
285a6bda
DV
2890 } else if (typeof this.file_ == 'string') {
2891 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2892 if (this.file_.indexOf('\n') >= 0) {
2893 this.loadedEvent_(this.file_);
2894 } else {
2895 var req = new XMLHttpRequest();
2896 var caller = this;
2897 req.onreadystatechange = function () {
2898 if (req.readyState == 4) {
39338e74
DV
2899 if (req.status == 200 || // Normal http
2900 req.status == 0) { // Chrome w/ --allow-file-access-from-files
285a6bda
DV
2901 caller.loadedEvent_(req.responseText);
2902 }
6a1aa64f 2903 }
285a6bda 2904 };
6a1aa64f 2905
285a6bda
DV
2906 req.open("GET", this.file_, true);
2907 req.send(null);
2908 }
2909 } else {
2910 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
2911 }
2912};
2913
2914/**
2915 * Changes various properties of the graph. These can include:
2916 * <ul>
2917 * <li>file: changes the source data for the graph</li>
2918 * <li>errorBars: changes whether the data contains stddev</li>
2919 * </ul>
dcb25130 2920 *
ccfcc169
DV
2921 * There's a huge variety of options that can be passed to this method. For a
2922 * full list, see http://dygraphs.com/options.html.
2923 *
6a1aa64f 2924 * @param {Object} attrs The new properties and values
ccfcc169
DV
2925 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
2926 * call to updateOptions(). If you know better, you can pass true to explicitly
2927 * block the redraw. This can be useful for chaining updateOptions() calls,
2928 * avoiding the occasional infinite loop and preventing redraws when it's not
2929 * necessary (e.g. when updating a callback).
6a1aa64f 2930 */
ccfcc169
DV
2931Dygraph.prototype.updateOptions = function(attrs, block_redraw) {
2932 if (typeof(block_redraw) == 'undefined') block_redraw = false;
2933
2934 // TODO(danvk): this is a mess. Move these options into attr_.
c65f2303 2935 if ('rollPeriod' in attrs) {
6a1aa64f
DV
2936 this.rollPeriod_ = attrs.rollPeriod;
2937 }
c65f2303 2938 if ('dateWindow' in attrs) {
6a1aa64f 2939 this.dateWindow_ = attrs.dateWindow;
e5152598 2940 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
81856f70
NN
2941 this.zoomed_x_ = attrs.dateWindow != null;
2942 }
b7e5862d 2943 }
e5152598 2944 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
b7e5862d 2945 this.zoomed_y_ = attrs.valueRange != null;
6a1aa64f 2946 }
450fe64b
DV
2947
2948 // TODO(danvk): validate per-series options.
46dde5f9
DV
2949 // Supported:
2950 // strokeWidth
2951 // pointSize
2952 // drawPoints
2953 // highlightCircleSize
450fe64b 2954
fc80a396 2955 Dygraph.update(this.user_attrs_, attrs);
285a6bda 2956
5e50289f 2957 if (attrs['file']) {
6a1aa64f 2958 this.file_ = attrs['file'];
ccfcc169 2959 if (!block_redraw) this.start_();
6a1aa64f 2960 } else {
ccfcc169 2961 if (!block_redraw) this.predraw_();
6a1aa64f
DV
2962 }
2963};
2964
2965/**
697e70b2
DV
2966 * Resizes the dygraph. If no parameters are specified, resizes to fill the
2967 * containing div (which has presumably changed size since the dygraph was
2968 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
2969 *
2970 * This is far more efficient than destroying and re-instantiating a
2971 * Dygraph, since it doesn't have to reparse the underlying data.
2972 *
629a09ae
DV
2973 * @param {Number} [width] Width (in pixels)
2974 * @param {Number} [height] Height (in pixels)
697e70b2
DV
2975 */
2976Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
2977 if (this.resize_lock) {
2978 return;
2979 }
2980 this.resize_lock = true;
2981
697e70b2
DV
2982 if ((width === null) != (height === null)) {
2983 this.warn("Dygraph.resize() should be called with zero parameters or " +
2984 "two non-NULL parameters. Pretending it was zero.");
2985 width = height = null;
2986 }
2987
b16e6369 2988 // TODO(danvk): there should be a clear() method.
697e70b2 2989 this.maindiv_.innerHTML = "";
b16e6369
DV
2990 this.attrs_.labelsDiv = null;
2991
697e70b2
DV
2992 if (width) {
2993 this.maindiv_.style.width = width + "px";
2994 this.maindiv_.style.height = height + "px";
2995 this.width_ = width;
2996 this.height_ = height;
2997 } else {
2998 this.width_ = this.maindiv_.offsetWidth;
2999 this.height_ = this.maindiv_.offsetHeight;
3000 }
3001
3002 this.createInterface_();
26ca7938 3003 this.predraw_();
e8c7ef86
DV
3004
3005 this.resize_lock = false;
697e70b2
DV
3006};
3007
3008/**
6faebb69 3009 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3010 * reflect the new averaging period.
6faebb69 3011 * @param {Number} length Number of points over which to average the data.
6a1aa64f 3012 */
285a6bda 3013Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3014 this.rollPeriod_ = length;
26ca7938 3015 this.predraw_();
6a1aa64f 3016};
540d00f1 3017
f8cfec73 3018/**
1cf11047
DV
3019 * Returns a boolean array of visibility statuses.
3020 */
3021Dygraph.prototype.visibility = function() {
3022 // Do lazy-initialization, so that this happens after we know the number of
3023 // data series.
3024 if (!this.attr_("visibility")) {
f38dec01 3025 this.attrs_["visibility"] = [];
1cf11047
DV
3026 }
3027 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
f38dec01 3028 this.attr_("visibility").push(true);
1cf11047
DV
3029 }
3030 return this.attr_("visibility");
3031};
3032
3033/**
3034 * Changes the visiblity of a series.
3035 */
3036Dygraph.prototype.setVisibility = function(num, value) {
3037 var x = this.visibility();
a6c109c1 3038 if (num < 0 || num >= x.length) {
1cf11047
DV
3039 this.warn("invalid series number in setVisibility: " + num);
3040 } else {
3041 x[num] = value;
26ca7938 3042 this.predraw_();
1cf11047
DV
3043 }
3044};
3045
3046/**
0cb9bd91
DV
3047 * How large of an area will the dygraph render itself in?
3048 * This is used for testing.
3049 * @return A {width: w, height: h} object.
3050 * @private
3051 */
3052Dygraph.prototype.size = function() {
3053 return { width: this.width_, height: this.height_ };
3054};
3055
3056/**
5c528fa2
DV
3057 * Update the list of annotations and redraw the chart.
3058 */
a685723c 3059Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3060 // Only add the annotation CSS rule once we know it will be used.
3061 Dygraph.addAnnotationRule();
5c528fa2
DV
3062 this.annotations_ = ann;
3063 this.layout_.setAnnotations(this.annotations_);
a685723c 3064 if (!suppressDraw) {
26ca7938 3065 this.predraw_();
a685723c 3066 }
5c528fa2
DV
3067};
3068
3069/**
3070 * Return the list of annotations.
3071 */
3072Dygraph.prototype.annotations = function() {
3073 return this.annotations_;
3074};
3075
46dde5f9
DV
3076/**
3077 * Get the index of a series (column) given its name. The first column is the
3078 * x-axis, so the data series start with index 1.
3079 */
3080Dygraph.prototype.indexFromSetName = function(name) {
3081 var labels = this.attr_("labels");
3082 for (var i = 0; i < labels.length; i++) {
3083 if (labels[i] == name) return i;
3084 }
3085 return null;
3086};
3087
629a09ae
DV
3088/**
3089 * @private
3090 * Adds a default style for the annotation CSS classes to the document. This is
3091 * only executed when annotations are actually used. It is designed to only be
3092 * called once -- all calls after the first will return immediately.
3093 */
5c528fa2
DV
3094Dygraph.addAnnotationRule = function() {
3095 if (Dygraph.addedAnnotationCSS) return;
3096
5c528fa2
DV
3097 var rule = "border: 1px solid black; " +
3098 "background-color: white; " +
3099 "text-align: center;";
22186871
DV
3100
3101 var styleSheetElement = document.createElement("style");
3102 styleSheetElement.type = "text/css";
3103 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3104
3105 // Find the first style sheet that we can access.
3106 // We may not add a rule to a style sheet from another domain for security
3107 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3108 // adds its own style sheets from google.com.
3109 for (var i = 0; i < document.styleSheets.length; i++) {
3110 if (document.styleSheets[i].disabled) continue;
3111 var mysheet = document.styleSheets[i];
3112 try {
3113 if (mysheet.insertRule) { // Firefox
3114 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3115 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3116 } else if (mysheet.addRule) { // IE
3117 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3118 }
3119 Dygraph.addedAnnotationCSS = true;
3120 return;
3121 } catch(err) {
3122 // Was likely a security exception.
3123 }
5c528fa2
DV
3124 }
3125
22186871 3126 this.warn("Unable to add default annotation CSS rule; display may be off.");
5c528fa2
DV
3127}
3128
285a6bda
DV
3129// Older pages may still use this name.
3130DateGraph = Dygraph;