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