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