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