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