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