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