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 | |
27 | ||
285a6bda | 28 | Date,SeriesA,SeriesB,... |
6a1aa64f DV |
29 | YYYYMMDD,A1,sigmaA1,B1,sigmaB1,... |
30 | YYYYMMDD,A2,sigmaA2,B2,sigmaB2,... | |
31 | ||
32 | If the 'fractions' option is set, the input should be of the form: | |
33 | ||
285a6bda | 34 | Date,SeriesA,SeriesB,... |
6a1aa64f DV |
35 | YYYYMMDD,A1/B1,A2/B2,... |
36 | YYYYMMDD,A1/B1,A2/B2,... | |
37 | ||
38 | And error bars will be calculated automatically using a binomial distribution. | |
39 | ||
285a6bda | 40 | For further documentation and examples, see http://www.danvk.org/dygraphs |
6a1aa64f DV |
41 | |
42 | */ | |
43 | ||
44 | /** | |
45 | * An interactive, zoomable graph | |
46 | * @param {String | Function} file A file containing CSV data or a function that | |
47 | * returns this data. The expected format for each line is | |
48 | * YYYYMMDD,val1,val2,... or, if attrs.errorBars is set, | |
49 | * YYYYMMDD,val1,stddev1,val2,stddev2,... | |
6a1aa64f DV |
50 | * @param {Object} attrs Various other attributes, e.g. errorBars determines |
51 | * whether the input data contains error ranges. | |
52 | */ | |
285a6bda DV |
53 | Dygraph = function(div, data, opts) { |
54 | if (arguments.length > 0) { | |
55 | if (arguments.length == 4) { | |
56 | // Old versions of dygraphs took in the series labels as a constructor | |
57 | // parameter. This doesn't make sense anymore, but it's easy to continue | |
58 | // to support this usage. | |
59 | this.warn("Using deprecated four-argument dygraph constructor"); | |
60 | this.__old_init__(div, data, arguments[2], arguments[3]); | |
61 | } else { | |
62 | this.__init__(div, data, opts); | |
63 | } | |
64 | } | |
6a1aa64f DV |
65 | }; |
66 | ||
285a6bda DV |
67 | Dygraph.NAME = "Dygraph"; |
68 | Dygraph.VERSION = "1.2"; | |
69 | Dygraph.__repr__ = function() { | |
6a1aa64f DV |
70 | return "[" + this.NAME + " " + this.VERSION + "]"; |
71 | }; | |
285a6bda | 72 | Dygraph.toString = function() { |
6a1aa64f DV |
73 | return this.__repr__(); |
74 | }; | |
75 | ||
76 | // Various default values | |
285a6bda DV |
77 | Dygraph.DEFAULT_ROLL_PERIOD = 1; |
78 | Dygraph.DEFAULT_WIDTH = 480; | |
79 | Dygraph.DEFAULT_HEIGHT = 320; | |
80 | Dygraph.AXIS_LINE_WIDTH = 0.3; | |
6a1aa64f | 81 | |
8e4a6af3 | 82 | // Default attribute values. |
285a6bda | 83 | Dygraph.DEFAULT_ATTRS = { |
a9fc39ab | 84 | highlightCircleSize: 3, |
8e4a6af3 | 85 | pixelsPerXLabel: 60, |
c6336f04 | 86 | pixelsPerYLabel: 30, |
285a6bda | 87 | |
8e4a6af3 DV |
88 | labelsDivWidth: 250, |
89 | labelsDivStyles: { | |
90 | // TODO(danvk): move defaults from createStatusMessage_ here. | |
285a6bda DV |
91 | }, |
92 | labelsSeparateLines: false, | |
bcd3ebf0 | 93 | labelsShowZeroValues: true, |
285a6bda | 94 | labelsKMB: false, |
afefbcdb | 95 | labelsKMG2: false, |
d160cc3b | 96 | showLabelsOnHighlight: true, |
12e4c741 | 97 | |
029da4b6 | 98 | yValueFormatter: function(x) { return Dygraph.round_(x, 2); }, |
285a6bda DV |
99 | |
100 | strokeWidth: 1.0, | |
8e4a6af3 | 101 | |
8846615a DV |
102 | axisTickSize: 3, |
103 | axisLabelFontSize: 14, | |
104 | xAxisLabelWidth: 50, | |
105 | yAxisLabelWidth: 50, | |
bf640e56 | 106 | xAxisLabelFormatter: Dygraph.dateAxisFormatter, |
8846615a | 107 | rightGap: 5, |
285a6bda DV |
108 | |
109 | showRoller: false, | |
110 | xValueFormatter: Dygraph.dateString_, | |
111 | xValueParser: Dygraph.dateParser, | |
112 | xTicker: Dygraph.dateTicker, | |
113 | ||
3d67f03b DV |
114 | delimiter: ',', |
115 | ||
ff00d3e2 | 116 | logScale: false, |
285a6bda DV |
117 | sigma: 2.0, |
118 | errorBars: false, | |
119 | fractions: false, | |
120 | wilsonInterval: true, // only relevant if fractions is true | |
5954ef32 | 121 | customBars: false, |
43af96e7 NK |
122 | fillGraph: false, |
123 | fillAlpha: 0.15, | |
f032c51d | 124 | connectSeparatedPoints: false, |
43af96e7 NK |
125 | |
126 | stackedGraph: false, | |
afdc483f NN |
127 | hideOverlayOnMouseOut: true, |
128 | ||
129 | stepPlot: false | |
285a6bda DV |
130 | }; |
131 | ||
132 | // Various logging levels. | |
133 | Dygraph.DEBUG = 1; | |
134 | Dygraph.INFO = 2; | |
135 | Dygraph.WARNING = 3; | |
136 | Dygraph.ERROR = 3; | |
137 | ||
5c528fa2 DV |
138 | // Used for initializing annotation CSS rules only once. |
139 | Dygraph.addedAnnotationCSS = false; | |
140 | ||
285a6bda DV |
141 | Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) { |
142 | // Labels is no longer a constructor parameter, since it's typically set | |
143 | // directly from the data source. It also conains a name for the x-axis, | |
144 | // which the previous constructor form did not. | |
145 | if (labels != null) { | |
146 | var new_labels = ["Date"]; | |
147 | for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]); | |
fc80a396 | 148 | Dygraph.update(attrs, { 'labels': new_labels }); |
285a6bda DV |
149 | } |
150 | this.__init__(div, file, attrs); | |
8e4a6af3 DV |
151 | }; |
152 | ||
6a1aa64f | 153 | /** |
285a6bda | 154 | * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit |
6a1aa64f DV |
155 | * and interaction <canvas> inside of it. See the constructor for details |
156 | * on the parameters. | |
12e4c741 | 157 | * @param {Element} div the Element to render the graph into. |
6a1aa64f | 158 | * @param {String | Function} file Source data |
6a1aa64f DV |
159 | * @param {Object} attrs Miscellaneous other options |
160 | * @private | |
161 | */ | |
285a6bda DV |
162 | Dygraph.prototype.__init__ = function(div, file, attrs) { |
163 | // Support two-argument constructor | |
164 | if (attrs == null) { attrs = {}; } | |
165 | ||
6a1aa64f | 166 | // Copy the important bits into the object |
32988383 | 167 | // TODO(danvk): most of these should just stay in the attrs_ dictionary. |
6a1aa64f | 168 | this.maindiv_ = div; |
6a1aa64f | 169 | this.file_ = file; |
285a6bda | 170 | this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD; |
6a1aa64f | 171 | this.previousVerticalX_ = -1; |
6a1aa64f | 172 | this.fractions_ = attrs.fractions || false; |
6a1aa64f DV |
173 | this.dateWindow_ = attrs.dateWindow || null; |
174 | this.valueRange_ = attrs.valueRange || null; | |
6a1aa64f | 175 | this.wilsonInterval_ = attrs.wilsonInterval || true; |
fe0b7c03 | 176 | this.is_initial_draw_ = true; |
5c528fa2 | 177 | this.annotations_ = []; |
8e4a6af3 | 178 | |
f7d6278e DV |
179 | // Clear the div. This ensure that, if multiple dygraphs are passed the same |
180 | // div, then only one will be drawn. | |
181 | div.innerHTML = ""; | |
182 | ||
c21d2c2d | 183 | // If the div isn't already sized then inherit from our attrs or |
184 | // give it a default size. | |
285a6bda | 185 | if (div.style.width == '') { |
c21d2c2d | 186 | div.style.width = attrs.width || Dygraph.DEFAULT_WIDTH + "px"; |
285a6bda DV |
187 | } |
188 | if (div.style.height == '') { | |
c21d2c2d | 189 | div.style.height = attrs.height || Dygraph.DEFAULT_HEIGHT + "px"; |
32988383 | 190 | } |
285a6bda DV |
191 | this.width_ = parseInt(div.style.width, 10); |
192 | this.height_ = parseInt(div.style.height, 10); | |
c21d2c2d | 193 | // The div might have been specified as percent of the current window size, |
194 | // convert that to an appropriate number of pixels. | |
195 | if (div.style.width.indexOf("%") == div.style.width.length - 1) { | |
c6f45033 | 196 | this.width_ = div.offsetWidth; |
c21d2c2d | 197 | } |
198 | if (div.style.height.indexOf("%") == div.style.height.length - 1) { | |
c6f45033 | 199 | this.height_ = div.offsetHeight; |
c21d2c2d | 200 | } |
32988383 | 201 | |
10a6456d DV |
202 | if (this.width_ == 0) { |
203 | this.error("dygraph has zero width. Please specify a width in pixels."); | |
204 | } | |
205 | if (this.height_ == 0) { | |
206 | this.error("dygraph has zero height. Please specify a height in pixels."); | |
207 | } | |
208 | ||
344ba8c0 | 209 | // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_. |
43af96e7 NK |
210 | if (attrs['stackedGraph']) { |
211 | attrs['fillGraph'] = true; | |
212 | // TODO(nikhilk): Add any other stackedGraph checks here. | |
213 | } | |
214 | ||
285a6bda DV |
215 | // Dygraphs has many options, some of which interact with one another. |
216 | // To keep track of everything, we maintain two sets of options: | |
217 | // | |
c21d2c2d | 218 | // this.user_attrs_ only options explicitly set by the user. |
285a6bda DV |
219 | // this.attrs_ defaults, options derived from user_attrs_, data. |
220 | // | |
221 | // Options are then accessed this.attr_('attr'), which first looks at | |
222 | // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent | |
223 | // defaults without overriding behavior that the user specifically asks for. | |
224 | this.user_attrs_ = {}; | |
fc80a396 | 225 | Dygraph.update(this.user_attrs_, attrs); |
6a1aa64f | 226 | |
285a6bda | 227 | this.attrs_ = {}; |
fc80a396 | 228 | Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS); |
6a1aa64f | 229 | |
16269f6e | 230 | this.boundaryIds_ = []; |
6a1aa64f | 231 | |
285a6bda DV |
232 | // Make a note of whether labels will be pulled from the CSV file. |
233 | this.labelsFromCSV_ = (this.attr_("labels") == null); | |
6a1aa64f | 234 | |
5c528fa2 DV |
235 | Dygraph.addAnnotationRule(); |
236 | ||
6a1aa64f DV |
237 | // Create the containing DIV and other interactive elements |
238 | this.createInterface_(); | |
239 | ||
738fc797 | 240 | this.start_(); |
6a1aa64f DV |
241 | }; |
242 | ||
285a6bda DV |
243 | Dygraph.prototype.attr_ = function(name) { |
244 | if (typeof(this.user_attrs_[name]) != 'undefined') { | |
245 | return this.user_attrs_[name]; | |
246 | } else if (typeof(this.attrs_[name]) != 'undefined') { | |
247 | return this.attrs_[name]; | |
248 | } else { | |
249 | return null; | |
250 | } | |
251 | }; | |
252 | ||
253 | // TODO(danvk): any way I can get the line numbers to be this.warn call? | |
254 | Dygraph.prototype.log = function(severity, message) { | |
255 | if (typeof(console) != 'undefined') { | |
256 | switch (severity) { | |
257 | case Dygraph.DEBUG: | |
258 | console.debug('dygraphs: ' + message); | |
259 | break; | |
260 | case Dygraph.INFO: | |
261 | console.info('dygraphs: ' + message); | |
262 | break; | |
263 | case Dygraph.WARNING: | |
264 | console.warn('dygraphs: ' + message); | |
265 | break; | |
266 | case Dygraph.ERROR: | |
267 | console.error('dygraphs: ' + message); | |
268 | break; | |
269 | } | |
270 | } | |
271 | } | |
272 | Dygraph.prototype.info = function(message) { | |
273 | this.log(Dygraph.INFO, message); | |
274 | } | |
275 | Dygraph.prototype.warn = function(message) { | |
276 | this.log(Dygraph.WARNING, message); | |
277 | } | |
278 | Dygraph.prototype.error = function(message) { | |
279 | this.log(Dygraph.ERROR, message); | |
280 | } | |
281 | ||
6a1aa64f DV |
282 | /** |
283 | * Returns the current rolling period, as set by the user or an option. | |
284 | * @return {Number} The number of days in the rolling window | |
285 | */ | |
285a6bda | 286 | Dygraph.prototype.rollPeriod = function() { |
6a1aa64f | 287 | return this.rollPeriod_; |
76171648 DV |
288 | }; |
289 | ||
599fb4ad DV |
290 | /** |
291 | * Returns the currently-visible x-range. This can be affected by zooming, | |
292 | * panning or a call to updateOptions. | |
293 | * Returns a two-element array: [left, right]. | |
294 | * If the Dygraph has dates on the x-axis, these will be millis since epoch. | |
295 | */ | |
296 | Dygraph.prototype.xAxisRange = function() { | |
297 | if (this.dateWindow_) return this.dateWindow_; | |
298 | ||
299 | // The entire chart is visible. | |
300 | var left = this.rawData_[0][0]; | |
301 | var right = this.rawData_[this.rawData_.length - 1][0]; | |
302 | return [left, right]; | |
303 | }; | |
304 | ||
3230c662 DV |
305 | /** |
306 | * Returns the currently-visible y-range. This can be affected by zooming, | |
307 | * panning or a call to updateOptions. | |
308 | * Returns a two-element array: [bottom, top]. | |
309 | */ | |
310 | Dygraph.prototype.yAxisRange = function() { | |
311 | return this.displayedYRange_; | |
312 | }; | |
313 | ||
314 | /** | |
315 | * Convert from data coordinates to canvas/div X/Y coordinates. | |
316 | * Returns a two-element array: [X, Y] | |
317 | */ | |
318 | Dygraph.prototype.toDomCoords = function(x, y) { | |
319 | var ret = [null, null]; | |
320 | var area = this.plotter_.area; | |
321 | if (x !== null) { | |
322 | var xRange = this.xAxisRange(); | |
323 | ret[0] = area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w; | |
324 | } | |
325 | ||
326 | if (y !== null) { | |
327 | var yRange = this.yAxisRange(); | |
891ad846 | 328 | ret[1] = area.y + (yRange[1] - y) / (yRange[1] - yRange[0]) * area.h; |
3230c662 DV |
329 | } |
330 | ||
331 | return ret; | |
332 | }; | |
333 | ||
56623f3b | 334 | // TODO(danvk): use these functions throughout dygraphs. |
3230c662 DV |
335 | /** |
336 | * Convert from canvas/div coords to data coordinates. | |
337 | * Returns a two-element array: [X, Y] | |
338 | */ | |
339 | Dygraph.prototype.toDataCoords = function(x, y) { | |
340 | var ret = [null, null]; | |
341 | var area = this.plotter_.area; | |
342 | if (x !== null) { | |
343 | var xRange = this.xAxisRange(); | |
344 | ret[0] = xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]); | |
345 | } | |
346 | ||
347 | if (y !== null) { | |
348 | var yRange = this.yAxisRange(); | |
349 | ret[1] = yRange[0] + (area.h - y) / area.h * (yRange[1] - yRange[0]); | |
350 | } | |
351 | ||
352 | return ret; | |
353 | }; | |
354 | ||
76171648 DV |
355 | Dygraph.addEvent = function(el, evt, fn) { |
356 | var normed_fn = function(e) { | |
357 | if (!e) var e = window.event; | |
358 | fn(e); | |
359 | }; | |
360 | if (window.addEventListener) { // Mozilla, Netscape, Firefox | |
361 | el.addEventListener(evt, normed_fn, false); | |
362 | } else { // IE | |
363 | el.attachEvent('on' + evt, normed_fn); | |
364 | } | |
365 | }; | |
6a1aa64f | 366 | |
4c47502d DV |
367 | Dygraph.clipCanvas_ = function(cnv, clip) { |
368 | var ctx = cnv.getContext("2d"); | |
369 | ctx.beginPath(); | |
370 | ctx.rect(clip.left, clip.top, clip.width, clip.height); | |
371 | ctx.clip(); | |
372 | }; | |
373 | ||
6a1aa64f | 374 | /** |
285a6bda | 375 | * Generates interface elements for the Dygraph: a containing div, a div to |
6a1aa64f | 376 | * display the current point, and a textbox to adjust the rolling average |
697e70b2 | 377 | * period. Also creates the Renderer/Layout elements. |
6a1aa64f DV |
378 | * @private |
379 | */ | |
285a6bda | 380 | Dygraph.prototype.createInterface_ = function() { |
6a1aa64f DV |
381 | // Create the all-enclosing graph div |
382 | var enclosing = this.maindiv_; | |
383 | ||
b0c3b730 DV |
384 | this.graphDiv = document.createElement("div"); |
385 | this.graphDiv.style.width = this.width_ + "px"; | |
386 | this.graphDiv.style.height = this.height_ + "px"; | |
387 | enclosing.appendChild(this.graphDiv); | |
388 | ||
4c47502d DV |
389 | var clip = { |
390 | top: 0, | |
391 | left: this.attr_("yAxisLabelWidth") + 2 * this.attr_("axisTickSize") | |
392 | }; | |
393 | clip.width = this.width_ - clip.left - this.attr_("rightGap"); | |
394 | clip.height = this.height_ - this.attr_("axisLabelFontSize") | |
395 | - 2 * this.attr_("axisTickSize"); | |
396 | this.clippingArea_ = clip; | |
397 | ||
b0c3b730 | 398 | // Create the canvas for interactive parts of the chart. |
f8cfec73 | 399 | this.canvas_ = Dygraph.createCanvas(); |
b0c3b730 DV |
400 | this.canvas_.style.position = "absolute"; |
401 | this.canvas_.width = this.width_; | |
402 | this.canvas_.height = this.height_; | |
f8cfec73 DV |
403 | this.canvas_.style.width = this.width_ + "px"; // for IE |
404 | this.canvas_.style.height = this.height_ + "px"; // for IE | |
b0c3b730 DV |
405 | |
406 | // ... and for static parts of the chart. | |
6a1aa64f | 407 | this.hidden_ = this.createPlotKitCanvas_(this.canvas_); |
76171648 | 408 | |
eb7bf005 EC |
409 | // The interactive parts of the graph are drawn on top of the chart. |
410 | this.graphDiv.appendChild(this.hidden_); | |
411 | this.graphDiv.appendChild(this.canvas_); | |
412 | this.mouseEventElement_ = this.canvas_; | |
413 | ||
4c47502d DV |
414 | // Make sure we don't overdraw. |
415 | Dygraph.clipCanvas_(this.hidden_, this.clippingArea_); | |
416 | Dygraph.clipCanvas_(this.canvas_, this.clippingArea_); | |
417 | ||
76171648 | 418 | var dygraph = this; |
eb7bf005 | 419 | Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) { |
76171648 DV |
420 | dygraph.mouseMove_(e); |
421 | }); | |
eb7bf005 | 422 | Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) { |
76171648 DV |
423 | dygraph.mouseOut_(e); |
424 | }); | |
697e70b2 DV |
425 | |
426 | // Create the grapher | |
427 | // TODO(danvk): why does the Layout need its own set of options? | |
428 | this.layoutOptions_ = { 'xOriginIsZero': false }; | |
429 | Dygraph.update(this.layoutOptions_, this.attrs_); | |
430 | Dygraph.update(this.layoutOptions_, this.user_attrs_); | |
431 | Dygraph.update(this.layoutOptions_, { | |
432 | 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) }); | |
433 | ||
434 | this.layout_ = new DygraphLayout(this, this.layoutOptions_); | |
435 | ||
436 | // TODO(danvk): why does the Renderer need its own set of options? | |
437 | this.renderOptions_ = { colorScheme: this.colors_, | |
438 | strokeColor: null, | |
439 | axisLineWidth: Dygraph.AXIS_LINE_WIDTH }; | |
440 | Dygraph.update(this.renderOptions_, this.attrs_); | |
441 | Dygraph.update(this.renderOptions_, this.user_attrs_); | |
442 | this.plotter_ = new DygraphCanvasRenderer(this, | |
443 | this.hidden_, this.layout_, | |
444 | this.renderOptions_); | |
445 | ||
446 | this.createStatusMessage_(); | |
447 | this.createRollInterface_(); | |
448 | this.createDragInterface_(); | |
4cfcc38c DV |
449 | }; |
450 | ||
451 | /** | |
452 | * Detach DOM elements in the dygraph and null out all data references. | |
453 | * Calling this when you're done with a dygraph can dramatically reduce memory | |
454 | * usage. See, e.g., the tests/perf.html example. | |
455 | */ | |
456 | Dygraph.prototype.destroy = function() { | |
457 | var removeRecursive = function(node) { | |
458 | while (node.hasChildNodes()) { | |
459 | removeRecursive(node.firstChild); | |
460 | node.removeChild(node.firstChild); | |
461 | } | |
462 | }; | |
463 | removeRecursive(this.maindiv_); | |
464 | ||
465 | var nullOut = function(obj) { | |
466 | for (var n in obj) { | |
467 | if (typeof(obj[n]) === 'object') { | |
468 | obj[n] = null; | |
469 | } | |
470 | } | |
471 | }; | |
472 | ||
473 | // These may not all be necessary, but it can't hurt... | |
474 | nullOut(this.layout_); | |
475 | nullOut(this.plotter_); | |
476 | nullOut(this); | |
477 | }; | |
6a1aa64f DV |
478 | |
479 | /** | |
480 | * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on | |
285a6bda | 481 | * this particular canvas. All Dygraph work is done on this.canvas_. |
8846615a | 482 | * @param {Object} canvas The Dygraph canvas over which to overlay the plot |
6a1aa64f DV |
483 | * @return {Object} The newly-created canvas |
484 | * @private | |
485 | */ | |
285a6bda | 486 | Dygraph.prototype.createPlotKitCanvas_ = function(canvas) { |
f8cfec73 | 487 | var h = Dygraph.createCanvas(); |
6a1aa64f | 488 | h.style.position = "absolute"; |
9ac5e4ae DV |
489 | // TODO(danvk): h should be offset from canvas. canvas needs to include |
490 | // some extra area to make it easier to zoom in on the far left and far | |
491 | // right. h needs to be precisely the plot area, so that clipping occurs. | |
6a1aa64f DV |
492 | h.style.top = canvas.style.top; |
493 | h.style.left = canvas.style.left; | |
494 | h.width = this.width_; | |
495 | h.height = this.height_; | |
f8cfec73 DV |
496 | h.style.width = this.width_ + "px"; // for IE |
497 | h.style.height = this.height_ + "px"; // for IE | |
6a1aa64f DV |
498 | return h; |
499 | }; | |
500 | ||
f474c2a3 DV |
501 | // Taken from MochiKit.Color |
502 | Dygraph.hsvToRGB = function (hue, saturation, value) { | |
503 | var red; | |
504 | var green; | |
505 | var blue; | |
506 | if (saturation === 0) { | |
507 | red = value; | |
508 | green = value; | |
509 | blue = value; | |
510 | } else { | |
511 | var i = Math.floor(hue * 6); | |
512 | var f = (hue * 6) - i; | |
513 | var p = value * (1 - saturation); | |
514 | var q = value * (1 - (saturation * f)); | |
515 | var t = value * (1 - (saturation * (1 - f))); | |
516 | switch (i) { | |
517 | case 1: red = q; green = value; blue = p; break; | |
518 | case 2: red = p; green = value; blue = t; break; | |
519 | case 3: red = p; green = q; blue = value; break; | |
520 | case 4: red = t; green = p; blue = value; break; | |
521 | case 5: red = value; green = p; blue = q; break; | |
522 | case 6: // fall through | |
523 | case 0: red = value; green = t; blue = p; break; | |
524 | } | |
525 | } | |
526 | red = Math.floor(255 * red + 0.5); | |
527 | green = Math.floor(255 * green + 0.5); | |
528 | blue = Math.floor(255 * blue + 0.5); | |
529 | return 'rgb(' + red + ',' + green + ',' + blue + ')'; | |
530 | }; | |
531 | ||
532 | ||
6a1aa64f DV |
533 | /** |
534 | * Generate a set of distinct colors for the data series. This is done with a | |
535 | * color wheel. Saturation/Value are customizable, and the hue is | |
536 | * equally-spaced around the color wheel. If a custom set of colors is | |
537 | * specified, that is used instead. | |
6a1aa64f DV |
538 | * @private |
539 | */ | |
285a6bda DV |
540 | Dygraph.prototype.setColors_ = function() { |
541 | // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do | |
542 | // away with this.renderOptions_. | |
543 | var num = this.attr_("labels").length - 1; | |
6a1aa64f | 544 | this.colors_ = []; |
285a6bda DV |
545 | var colors = this.attr_('colors'); |
546 | if (!colors) { | |
547 | var sat = this.attr_('colorSaturation') || 1.0; | |
548 | var val = this.attr_('colorValue') || 0.5; | |
2aa21213 | 549 | var half = Math.ceil(num / 2); |
6a1aa64f | 550 | for (var i = 1; i <= num; i++) { |
ec1959eb | 551 | if (!this.visibility()[i-1]) continue; |
43af96e7 | 552 | // alternate colors for high contrast. |
2aa21213 | 553 | var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2); |
43af96e7 NK |
554 | var hue = (1.0 * idx/ (1 + num)); |
555 | this.colors_.push(Dygraph.hsvToRGB(hue, sat, val)); | |
6a1aa64f DV |
556 | } |
557 | } else { | |
558 | for (var i = 0; i < num; i++) { | |
ec1959eb | 559 | if (!this.visibility()[i]) continue; |
285a6bda | 560 | var colorStr = colors[i % colors.length]; |
f474c2a3 | 561 | this.colors_.push(colorStr); |
6a1aa64f DV |
562 | } |
563 | } | |
285a6bda | 564 | |
c21d2c2d | 565 | // TODO(danvk): update this w/r/t/ the new options system. |
285a6bda | 566 | this.renderOptions_.colorScheme = this.colors_; |
fc80a396 DV |
567 | Dygraph.update(this.plotter_.options, this.renderOptions_); |
568 | Dygraph.update(this.layoutOptions_, this.user_attrs_); | |
569 | Dygraph.update(this.layoutOptions_, this.attrs_); | |
6a1aa64f DV |
570 | } |
571 | ||
43af96e7 NK |
572 | /** |
573 | * Return the list of colors. This is either the list of colors passed in the | |
574 | * attributes, or the autogenerated list of rgb(r,g,b) strings. | |
575 | * @return {Array<string>} The list of colors. | |
576 | */ | |
577 | Dygraph.prototype.getColors = function() { | |
578 | return this.colors_; | |
579 | }; | |
580 | ||
5e60386d DV |
581 | // The following functions are from quirksmode.org with a modification for Safari from |
582 | // http://blog.firetree.net/2005/07/04/javascript-find-position/ | |
3df0ccf0 DV |
583 | // http://www.quirksmode.org/js/findpos.html |
584 | Dygraph.findPosX = function(obj) { | |
585 | var curleft = 0; | |
5e60386d | 586 | if(obj.offsetParent) |
50360fd0 | 587 | while(1) |
5e60386d | 588 | { |
3df0ccf0 | 589 | curleft += obj.offsetLeft; |
5e60386d DV |
590 | if(!obj.offsetParent) |
591 | break; | |
3df0ccf0 DV |
592 | obj = obj.offsetParent; |
593 | } | |
5e60386d | 594 | else if(obj.x) |
3df0ccf0 DV |
595 | curleft += obj.x; |
596 | return curleft; | |
597 | }; | |
c21d2c2d | 598 | |
3df0ccf0 DV |
599 | Dygraph.findPosY = function(obj) { |
600 | var curtop = 0; | |
5e60386d DV |
601 | if(obj.offsetParent) |
602 | while(1) | |
603 | { | |
3df0ccf0 | 604 | curtop += obj.offsetTop; |
5e60386d DV |
605 | if(!obj.offsetParent) |
606 | break; | |
3df0ccf0 DV |
607 | obj = obj.offsetParent; |
608 | } | |
5e60386d | 609 | else if(obj.y) |
3df0ccf0 DV |
610 | curtop += obj.y; |
611 | return curtop; | |
612 | }; | |
613 | ||
5e60386d | 614 | |
71a11a8e | 615 | |
6a1aa64f DV |
616 | /** |
617 | * Create the div that contains information on the selected point(s) | |
618 | * This goes in the top right of the canvas, unless an external div has already | |
619 | * been specified. | |
620 | * @private | |
621 | */ | |
fedbd797 | 622 | Dygraph.prototype.createStatusMessage_ = function() { |
623 | var userLabelsDiv = this.user_attrs_["labelsDiv"]; | |
624 | if (userLabelsDiv && null != userLabelsDiv | |
625 | && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) { | |
626 | this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv); | |
627 | } | |
285a6bda DV |
628 | if (!this.attr_("labelsDiv")) { |
629 | var divWidth = this.attr_('labelsDivWidth'); | |
b0c3b730 | 630 | var messagestyle = { |
6a1aa64f DV |
631 | "position": "absolute", |
632 | "fontSize": "14px", | |
633 | "zIndex": 10, | |
634 | "width": divWidth + "px", | |
635 | "top": "0px", | |
8846615a | 636 | "left": (this.width_ - divWidth - 2) + "px", |
6a1aa64f DV |
637 | "background": "white", |
638 | "textAlign": "left", | |
b0c3b730 | 639 | "overflow": "hidden"}; |
fc80a396 | 640 | Dygraph.update(messagestyle, this.attr_('labelsDivStyles')); |
b0c3b730 DV |
641 | var div = document.createElement("div"); |
642 | for (var name in messagestyle) { | |
85b99f0b DV |
643 | if (messagestyle.hasOwnProperty(name)) { |
644 | div.style[name] = messagestyle[name]; | |
645 | } | |
b0c3b730 DV |
646 | } |
647 | this.graphDiv.appendChild(div); | |
285a6bda | 648 | this.attrs_.labelsDiv = div; |
6a1aa64f DV |
649 | } |
650 | }; | |
651 | ||
652 | /** | |
653 | * Create the text box to adjust the averaging period | |
654 | * @return {Object} The newly-created text box | |
655 | * @private | |
656 | */ | |
285a6bda | 657 | Dygraph.prototype.createRollInterface_ = function() { |
285a6bda | 658 | var display = this.attr_('showRoller') ? "block" : "none"; |
b0c3b730 DV |
659 | var textAttr = { "position": "absolute", |
660 | "zIndex": 10, | |
661 | "top": (this.plotter_.area.h - 25) + "px", | |
662 | "left": (this.plotter_.area.x + 1) + "px", | |
663 | "display": display | |
6a1aa64f | 664 | }; |
b0c3b730 DV |
665 | var roller = document.createElement("input"); |
666 | roller.type = "text"; | |
667 | roller.size = "2"; | |
668 | roller.value = this.rollPeriod_; | |
669 | for (var name in textAttr) { | |
85b99f0b DV |
670 | if (textAttr.hasOwnProperty(name)) { |
671 | roller.style[name] = textAttr[name]; | |
672 | } | |
b0c3b730 DV |
673 | } |
674 | ||
6a1aa64f | 675 | var pa = this.graphDiv; |
b0c3b730 | 676 | pa.appendChild(roller); |
76171648 DV |
677 | var dygraph = this; |
678 | roller.onchange = function() { dygraph.adjustRoll(roller.value); }; | |
6a1aa64f | 679 | return roller; |
76171648 DV |
680 | }; |
681 | ||
682 | // These functions are taken from MochiKit.Signal | |
683 | Dygraph.pageX = function(e) { | |
684 | if (e.pageX) { | |
685 | return (!e.pageX || e.pageX < 0) ? 0 : e.pageX; | |
686 | } else { | |
687 | var de = document; | |
688 | var b = document.body; | |
689 | return e.clientX + | |
690 | (de.scrollLeft || b.scrollLeft) - | |
691 | (de.clientLeft || 0); | |
692 | } | |
693 | }; | |
694 | ||
695 | Dygraph.pageY = function(e) { | |
696 | if (e.pageY) { | |
697 | return (!e.pageY || e.pageY < 0) ? 0 : e.pageY; | |
698 | } else { | |
699 | var de = document; | |
700 | var b = document.body; | |
701 | return e.clientY + | |
702 | (de.scrollTop || b.scrollTop) - | |
703 | (de.clientTop || 0); | |
704 | } | |
705 | }; | |
6a1aa64f DV |
706 | |
707 | /** | |
708 | * Set up all the mouse handlers needed to capture dragging behavior for zoom | |
27385109 | 709 | * events. |
6a1aa64f DV |
710 | * @private |
711 | */ | |
285a6bda | 712 | Dygraph.prototype.createDragInterface_ = function() { |
6a1aa64f DV |
713 | var self = this; |
714 | ||
715 | // Tracks whether the mouse is down right now | |
bce01b0f | 716 | var isZooming = false; |
c776c216 | 717 | var isPanning = false; |
6a1aa64f DV |
718 | var dragStartX = null; |
719 | var dragStartY = null; | |
720 | var dragEndX = null; | |
721 | var dragEndY = null; | |
722 | var prevEndX = null; | |
bce01b0f DV |
723 | var draggingDate = null; |
724 | var dateRange = null; | |
6a1aa64f DV |
725 | |
726 | // Utility function to convert page-wide coordinates to canvas coords | |
67e650dc DV |
727 | var px = 0; |
728 | var py = 0; | |
76171648 DV |
729 | var getX = function(e) { return Dygraph.pageX(e) - px }; |
730 | var getY = function(e) { return Dygraph.pageX(e) - py }; | |
6a1aa64f DV |
731 | |
732 | // Draw zoom rectangles when the mouse is down and the user moves around | |
eb7bf005 | 733 | Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(event) { |
bce01b0f | 734 | if (isZooming) { |
6a1aa64f DV |
735 | dragEndX = getX(event); |
736 | dragEndY = getY(event); | |
737 | ||
738 | self.drawZoomRect_(dragStartX, dragEndX, prevEndX); | |
739 | prevEndX = dragEndX; | |
bce01b0f DV |
740 | } else if (isPanning) { |
741 | dragEndX = getX(event); | |
742 | dragEndY = getY(event); | |
743 | ||
744 | // Want to have it so that: | |
745 | // 1. draggingDate appears at dragEndX | |
746 | // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered. | |
747 | ||
748 | self.dateWindow_[0] = draggingDate - (dragEndX / self.width_) * dateRange; | |
749 | self.dateWindow_[1] = self.dateWindow_[0] + dateRange; | |
750 | self.drawGraph_(self.rawData_); | |
6a1aa64f DV |
751 | } |
752 | }); | |
753 | ||
754 | // Track the beginning of drag events | |
eb7bf005 | 755 | Dygraph.addEvent(this.mouseEventElement_, 'mousedown', function(event) { |
3df0ccf0 DV |
756 | px = Dygraph.findPosX(self.canvas_); |
757 | py = Dygraph.findPosY(self.canvas_); | |
6a1aa64f DV |
758 | dragStartX = getX(event); |
759 | dragStartY = getY(event); | |
bce01b0f | 760 | |
2dab69c3 | 761 | if (event.altKey || event.shiftKey) { |
d12999d3 | 762 | if (!self.dateWindow_) return; // have to be zoomed in to pan. |
bce01b0f DV |
763 | isPanning = true; |
764 | dateRange = self.dateWindow_[1] - self.dateWindow_[0]; | |
d12999d3 DV |
765 | draggingDate = (dragStartX / self.width_) * dateRange + |
766 | self.dateWindow_[0]; | |
bce01b0f DV |
767 | } else { |
768 | isZooming = true; | |
769 | } | |
6a1aa64f DV |
770 | }); |
771 | ||
772 | // If the user releases the mouse button during a drag, but not over the | |
773 | // canvas, then it doesn't count as a zooming action. | |
76171648 | 774 | Dygraph.addEvent(document, 'mouseup', function(event) { |
bce01b0f DV |
775 | if (isZooming || isPanning) { |
776 | isZooming = false; | |
6a1aa64f DV |
777 | dragStartX = null; |
778 | dragStartY = null; | |
779 | } | |
bce01b0f DV |
780 | |
781 | if (isPanning) { | |
782 | isPanning = false; | |
783 | draggingDate = null; | |
784 | dateRange = null; | |
785 | } | |
6a1aa64f DV |
786 | }); |
787 | ||
788 | // Temporarily cancel the dragging event when the mouse leaves the graph | |
eb7bf005 | 789 | Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(event) { |
bce01b0f | 790 | if (isZooming) { |
6a1aa64f DV |
791 | dragEndX = null; |
792 | dragEndY = null; | |
793 | } | |
794 | }); | |
795 | ||
796 | // If the mouse is released on the canvas during a drag event, then it's a | |
797 | // zoom. Only do the zoom if it's over a large enough area (>= 10 pixels) | |
eb7bf005 | 798 | Dygraph.addEvent(this.mouseEventElement_, 'mouseup', function(event) { |
bce01b0f DV |
799 | if (isZooming) { |
800 | isZooming = false; | |
6a1aa64f DV |
801 | dragEndX = getX(event); |
802 | dragEndY = getY(event); | |
803 | var regionWidth = Math.abs(dragEndX - dragStartX); | |
804 | var regionHeight = Math.abs(dragEndY - dragStartY); | |
805 | ||
806 | if (regionWidth < 2 && regionHeight < 2 && | |
285a6bda | 807 | self.attr_('clickCallback') != null && |
6a1aa64f | 808 | self.lastx_ != undefined) { |
b258a3da DV |
809 | // TODO(danvk): pass along more info about the points. |
810 | self.attr_('clickCallback')(event, self.lastx_, self.selPoints_); | |
6a1aa64f DV |
811 | } |
812 | ||
813 | if (regionWidth >= 10) { | |
814 | self.doZoom_(Math.min(dragStartX, dragEndX), | |
815 | Math.max(dragStartX, dragEndX)); | |
816 | } else { | |
817 | self.canvas_.getContext("2d").clearRect(0, 0, | |
818 | self.canvas_.width, | |
819 | self.canvas_.height); | |
820 | } | |
821 | ||
822 | dragStartX = null; | |
823 | dragStartY = null; | |
824 | } | |
bce01b0f DV |
825 | |
826 | if (isPanning) { | |
827 | isPanning = false; | |
828 | draggingDate = null; | |
829 | dateRange = null; | |
830 | } | |
6a1aa64f DV |
831 | }); |
832 | ||
833 | // Double-clicking zooms back out | |
eb7bf005 | 834 | Dygraph.addEvent(this.mouseEventElement_, 'dblclick', function(event) { |
b258a3da | 835 | if (self.dateWindow_ == null) return; |
6a1aa64f DV |
836 | self.dateWindow_ = null; |
837 | self.drawGraph_(self.rawData_); | |
838 | var minDate = self.rawData_[0][0]; | |
839 | var maxDate = self.rawData_[self.rawData_.length - 1][0]; | |
285a6bda DV |
840 | if (self.attr_("zoomCallback")) { |
841 | self.attr_("zoomCallback")(minDate, maxDate); | |
67e650dc | 842 | } |
6a1aa64f DV |
843 | }); |
844 | }; | |
845 | ||
846 | /** | |
847 | * Draw a gray zoom rectangle over the desired area of the canvas. Also clears | |
848 | * up any previous zoom rectangles that were drawn. This could be optimized to | |
849 | * avoid extra redrawing, but it's tricky to avoid interactions with the status | |
850 | * dots. | |
851 | * @param {Number} startX The X position where the drag started, in canvas | |
852 | * coordinates. | |
853 | * @param {Number} endX The current X position of the drag, in canvas coords. | |
854 | * @param {Number} prevEndX The value of endX on the previous call to this | |
855 | * function. Used to avoid excess redrawing | |
856 | * @private | |
857 | */ | |
285a6bda | 858 | Dygraph.prototype.drawZoomRect_ = function(startX, endX, prevEndX) { |
6a1aa64f DV |
859 | var ctx = this.canvas_.getContext("2d"); |
860 | ||
861 | // Clean up from the previous rect if necessary | |
862 | if (prevEndX) { | |
863 | ctx.clearRect(Math.min(startX, prevEndX), 0, | |
864 | Math.abs(startX - prevEndX), this.height_); | |
865 | } | |
866 | ||
867 | // Draw a light-grey rectangle to show the new viewing area | |
868 | if (endX && startX) { | |
869 | ctx.fillStyle = "rgba(128,128,128,0.33)"; | |
870 | ctx.fillRect(Math.min(startX, endX), 0, | |
871 | Math.abs(endX - startX), this.height_); | |
872 | } | |
873 | }; | |
874 | ||
875 | /** | |
876 | * Zoom to something containing [lowX, highX]. These are pixel coordinates | |
877 | * in the canvas. The exact zoom window may be slightly larger if there are no | |
878 | * data points near lowX or highX. This function redraws the graph. | |
879 | * @param {Number} lowX The leftmost pixel value that should be visible. | |
880 | * @param {Number} highX The rightmost pixel value that should be visible. | |
881 | * @private | |
882 | */ | |
285a6bda | 883 | Dygraph.prototype.doZoom_ = function(lowX, highX) { |
6a1aa64f | 884 | // Find the earliest and latest dates contained in this canvasx range. |
56623f3b DV |
885 | var r = this.toDataCoords(lowX, null); |
886 | var minDate = r[0]; | |
887 | r = this.toDataCoords(highX, null); | |
888 | var maxDate = r[0]; | |
6a1aa64f DV |
889 | |
890 | this.dateWindow_ = [minDate, maxDate]; | |
891 | this.drawGraph_(this.rawData_); | |
285a6bda DV |
892 | if (this.attr_("zoomCallback")) { |
893 | this.attr_("zoomCallback")(minDate, maxDate); | |
67e650dc | 894 | } |
6a1aa64f DV |
895 | }; |
896 | ||
897 | /** | |
898 | * When the mouse moves in the canvas, display information about a nearby data | |
899 | * point and draw dots over those points in the data series. This function | |
900 | * takes care of cleanup of previously-drawn dots. | |
901 | * @param {Object} event The mousemove event from the browser. | |
902 | * @private | |
903 | */ | |
285a6bda | 904 | Dygraph.prototype.mouseMove_ = function(event) { |
eb7bf005 | 905 | var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_); |
6a1aa64f DV |
906 | var points = this.layout_.points; |
907 | ||
908 | var lastx = -1; | |
909 | var lasty = -1; | |
910 | ||
911 | // Loop through all the points and find the date nearest to our current | |
912 | // location. | |
913 | var minDist = 1e+100; | |
914 | var idx = -1; | |
915 | for (var i = 0; i < points.length; i++) { | |
916 | var dist = Math.abs(points[i].canvasx - canvasx); | |
f032c51d | 917 | if (dist > minDist) continue; |
6a1aa64f DV |
918 | minDist = dist; |
919 | idx = i; | |
920 | } | |
921 | if (idx >= 0) lastx = points[idx].xval; | |
922 | // Check that you can really highlight the last day's data | |
923 | if (canvasx > points[points.length-1].canvasx) | |
924 | lastx = points[points.length-1].xval; | |
925 | ||
926 | // Extract the points we've selected | |
b258a3da | 927 | this.selPoints_ = []; |
50360fd0 | 928 | var l = points.length; |
416b05ad NK |
929 | if (!this.attr_("stackedGraph")) { |
930 | for (var i = 0; i < l; i++) { | |
931 | if (points[i].xval == lastx) { | |
932 | this.selPoints_.push(points[i]); | |
933 | } | |
934 | } | |
935 | } else { | |
354e15ab DE |
936 | // Need to 'unstack' points starting from the bottom |
937 | var cumulative_sum = 0; | |
416b05ad NK |
938 | for (var i = l - 1; i >= 0; i--) { |
939 | if (points[i].xval == lastx) { | |
354e15ab | 940 | var p = {}; // Clone the point since we modify it |
d4139cd8 NK |
941 | for (var k in points[i]) { |
942 | p[k] = points[i][k]; | |
50360fd0 NK |
943 | } |
944 | p.yval -= cumulative_sum; | |
945 | cumulative_sum += p.yval; | |
d4139cd8 | 946 | this.selPoints_.push(p); |
12e4c741 | 947 | } |
6a1aa64f | 948 | } |
354e15ab | 949 | this.selPoints_.reverse(); |
6a1aa64f DV |
950 | } |
951 | ||
b258a3da | 952 | if (this.attr_("highlightCallback")) { |
a4c6a67c | 953 | var px = this.lastx_; |
dd082dda | 954 | if (px !== null && lastx != px) { |
344ba8c0 | 955 | // only fire if the selected point has changed. |
50360fd0 | 956 | this.attr_("highlightCallback")(event, lastx, this.selPoints_); |
43af96e7 | 957 | } |
12e4c741 | 958 | } |
43af96e7 | 959 | |
239c712d NAG |
960 | // Save last x position for callbacks. |
961 | this.lastx_ = lastx; | |
50360fd0 | 962 | |
239c712d NAG |
963 | this.updateSelection_(); |
964 | }; | |
b258a3da | 965 | |
239c712d NAG |
966 | /** |
967 | * Draw dots over the selectied points in the data series. This function | |
968 | * takes care of cleanup of previously-drawn dots. | |
969 | * @private | |
970 | */ | |
971 | Dygraph.prototype.updateSelection_ = function() { | |
6a1aa64f | 972 | // Clear the previously drawn vertical, if there is one |
285a6bda | 973 | var circleSize = this.attr_('highlightCircleSize'); |
6a1aa64f DV |
974 | var ctx = this.canvas_.getContext("2d"); |
975 | if (this.previousVerticalX_ >= 0) { | |
976 | var px = this.previousVerticalX_; | |
977 | ctx.clearRect(px - circleSize - 1, 0, 2 * circleSize + 2, this.height_); | |
978 | } | |
979 | ||
584ceeaa DV |
980 | var isOK = function(x) { return x && !isNaN(x); }; |
981 | ||
d160cc3b | 982 | if (this.selPoints_.length > 0) { |
b258a3da | 983 | var canvasx = this.selPoints_[0].canvasx; |
6a1aa64f DV |
984 | |
985 | // Set the status message to indicate the selected point(s) | |
239c712d | 986 | var replace = this.attr_('xValueFormatter')(this.lastx_, this) + ":"; |
50360fd0 | 987 | var fmtFunc = this.attr_('yValueFormatter'); |
6a1aa64f | 988 | var clen = this.colors_.length; |
d160cc3b NK |
989 | |
990 | if (this.attr_('showLabelsOnHighlight')) { | |
991 | // Set the status message to indicate the selected point(s) | |
d160cc3b | 992 | for (var i = 0; i < this.selPoints_.length; i++) { |
bcd3ebf0 | 993 | if (!this.attr_("labelsShowZeroValues") && this.selPoints_[i].yval == 0) continue; |
d160cc3b NK |
994 | if (!isOK(this.selPoints_[i].canvasy)) continue; |
995 | if (this.attr_("labelsSeparateLines")) { | |
996 | replace += "<br/>"; | |
997 | } | |
998 | var point = this.selPoints_[i]; | |
999 | var c = new RGBColor(this.colors_[i%clen]); | |
029da4b6 | 1000 | var yval = fmtFunc(point.yval); |
d160cc3b NK |
1001 | replace += " <b><font color='" + c.toHex() + "'>" |
1002 | + point.name + "</font></b>:" | |
1003 | + yval; | |
6a1aa64f | 1004 | } |
50360fd0 | 1005 | |
d160cc3b | 1006 | this.attr_("labelsDiv").innerHTML = replace; |
6a1aa64f | 1007 | } |
6a1aa64f | 1008 | |
6a1aa64f | 1009 | // Draw colored circles over the center of each selected point |
43af96e7 | 1010 | ctx.save(); |
b258a3da | 1011 | for (var i = 0; i < this.selPoints_.length; i++) { |
f032c51d | 1012 | if (!isOK(this.selPoints_[i].canvasy)) continue; |
6a1aa64f | 1013 | ctx.beginPath(); |
563c70ca | 1014 | ctx.fillStyle = this.plotter_.colors[this.selPoints_[i].name]; |
f032c51d | 1015 | ctx.arc(canvasx, this.selPoints_[i].canvasy, circleSize, |
7bf6a9fe | 1016 | 0, 2 * Math.PI, false); |
6a1aa64f DV |
1017 | ctx.fill(); |
1018 | } | |
1019 | ctx.restore(); | |
1020 | ||
1021 | this.previousVerticalX_ = canvasx; | |
1022 | } | |
1023 | }; | |
1024 | ||
1025 | /** | |
239c712d NAG |
1026 | * Set manually set selected dots, and display information about them |
1027 | * @param int row number that should by highlighted | |
1028 | * false value clears the selection | |
1029 | * @public | |
1030 | */ | |
1031 | Dygraph.prototype.setSelection = function(row) { | |
1032 | // Extract the points we've selected | |
1033 | this.selPoints_ = []; | |
1034 | var pos = 0; | |
50360fd0 | 1035 | |
239c712d | 1036 | if (row !== false) { |
16269f6e NAG |
1037 | row = row-this.boundaryIds_[0][0]; |
1038 | } | |
50360fd0 | 1039 | |
16269f6e | 1040 | if (row !== false && row >= 0) { |
239c712d | 1041 | for (var i in this.layout_.datasets) { |
16269f6e NAG |
1042 | if (row < this.layout_.datasets[i].length) { |
1043 | this.selPoints_.push(this.layout_.points[pos+row]); | |
1044 | } | |
239c712d NAG |
1045 | pos += this.layout_.datasets[i].length; |
1046 | } | |
16269f6e | 1047 | } |
50360fd0 | 1048 | |
16269f6e | 1049 | if (this.selPoints_.length) { |
239c712d NAG |
1050 | this.lastx_ = this.selPoints_[0].xval; |
1051 | this.updateSelection_(); | |
1052 | } else { | |
1053 | this.lastx_ = -1; | |
1054 | this.clearSelection(); | |
1055 | } | |
1056 | ||
1057 | }; | |
1058 | ||
1059 | /** | |
6a1aa64f DV |
1060 | * The mouse has left the canvas. Clear out whatever artifacts remain |
1061 | * @param {Object} event the mouseout event from the browser. | |
1062 | * @private | |
1063 | */ | |
285a6bda | 1064 | Dygraph.prototype.mouseOut_ = function(event) { |
a4c6a67c AV |
1065 | if (this.attr_("unhighlightCallback")) { |
1066 | this.attr_("unhighlightCallback")(event); | |
1067 | } | |
1068 | ||
43af96e7 | 1069 | if (this.attr_("hideOverlayOnMouseOut")) { |
239c712d | 1070 | this.clearSelection(); |
43af96e7 | 1071 | } |
6a1aa64f DV |
1072 | }; |
1073 | ||
239c712d NAG |
1074 | /** |
1075 | * Remove all selection from the canvas | |
1076 | * @public | |
1077 | */ | |
1078 | Dygraph.prototype.clearSelection = function() { | |
1079 | // Get rid of the overlay data | |
1080 | var ctx = this.canvas_.getContext("2d"); | |
1081 | ctx.clearRect(0, 0, this.width_, this.height_); | |
1082 | this.attr_("labelsDiv").innerHTML = ""; | |
1083 | this.selPoints_ = []; | |
1084 | this.lastx_ = -1; | |
1085 | } | |
1086 | ||
103b7292 NAG |
1087 | /** |
1088 | * Returns the number of the currently selected row | |
1089 | * @return int row number, of -1 if nothing is selected | |
1090 | * @public | |
1091 | */ | |
1092 | Dygraph.prototype.getSelection = function() { | |
1093 | if (!this.selPoints_ || this.selPoints_.length < 1) { | |
1094 | return -1; | |
1095 | } | |
50360fd0 | 1096 | |
103b7292 NAG |
1097 | for (var row=0; row<this.layout_.points.length; row++ ) { |
1098 | if (this.layout_.points[row].x == this.selPoints_[0].x) { | |
16269f6e | 1099 | return row + this.boundaryIds_[0][0]; |
103b7292 NAG |
1100 | } |
1101 | } | |
1102 | return -1; | |
1103 | } | |
1104 | ||
285a6bda | 1105 | Dygraph.zeropad = function(x) { |
32988383 DV |
1106 | if (x < 10) return "0" + x; else return "" + x; |
1107 | } | |
1108 | ||
6a1aa64f | 1109 | /** |
6b8e33dd DV |
1110 | * Return a string version of the hours, minutes and seconds portion of a date. |
1111 | * @param {Number} date The JavaScript date (ms since epoch) | |
1112 | * @return {String} A time of the form "HH:MM:SS" | |
1113 | * @private | |
1114 | */ | |
bf640e56 | 1115 | Dygraph.hmsString_ = function(date) { |
285a6bda | 1116 | var zeropad = Dygraph.zeropad; |
6b8e33dd DV |
1117 | var d = new Date(date); |
1118 | if (d.getSeconds()) { | |
1119 | return zeropad(d.getHours()) + ":" + | |
1120 | zeropad(d.getMinutes()) + ":" + | |
1121 | zeropad(d.getSeconds()); | |
6b8e33dd | 1122 | } else { |
054531ca | 1123 | return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes()); |
6b8e33dd DV |
1124 | } |
1125 | } | |
1126 | ||
1127 | /** | |
bf640e56 AV |
1128 | * Convert a JS date to a string appropriate to display on an axis that |
1129 | * is displaying values at the stated granularity. | |
1130 | * @param {Date} date The date to format | |
1131 | * @param {Number} granularity One of the Dygraph granularity constants | |
1132 | * @return {String} The formatted date | |
1133 | * @private | |
1134 | */ | |
1135 | Dygraph.dateAxisFormatter = function(date, granularity) { | |
1136 | if (granularity >= Dygraph.MONTHLY) { | |
1137 | return date.strftime('%b %y'); | |
1138 | } else { | |
31eddad3 | 1139 | var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds(); |
bf640e56 AV |
1140 | if (frac == 0 || granularity >= Dygraph.DAILY) { |
1141 | return new Date(date.getTime() + 3600*1000).strftime('%d%b'); | |
1142 | } else { | |
1143 | return Dygraph.hmsString_(date.getTime()); | |
1144 | } | |
1145 | } | |
1146 | } | |
1147 | ||
1148 | /** | |
6a1aa64f DV |
1149 | * Convert a JS date (millis since epoch) to YYYY/MM/DD |
1150 | * @param {Number} date The JavaScript date (ms since epoch) | |
1151 | * @return {String} A date of the form "YYYY/MM/DD" | |
1152 | * @private | |
1153 | */ | |
285a6bda DV |
1154 | Dygraph.dateString_ = function(date, self) { |
1155 | var zeropad = Dygraph.zeropad; | |
6a1aa64f DV |
1156 | var d = new Date(date); |
1157 | ||
1158 | // Get the year: | |
1159 | var year = "" + d.getFullYear(); | |
1160 | // Get a 0 padded month string | |
6b8e33dd | 1161 | var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh |
6a1aa64f | 1162 | // Get a 0 padded day string |
6b8e33dd | 1163 | var day = zeropad(d.getDate()); |
6a1aa64f | 1164 | |
6b8e33dd DV |
1165 | var ret = ""; |
1166 | var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds(); | |
bf640e56 | 1167 | if (frac) ret = " " + Dygraph.hmsString_(date); |
6b8e33dd DV |
1168 | |
1169 | return year + "/" + month + "/" + day + ret; | |
6a1aa64f DV |
1170 | }; |
1171 | ||
1172 | /** | |
1173 | * Round a number to the specified number of digits past the decimal point. | |
1174 | * @param {Number} num The number to round | |
1175 | * @param {Number} places The number of decimals to which to round | |
1176 | * @return {Number} The rounded number | |
1177 | * @private | |
1178 | */ | |
029da4b6 | 1179 | Dygraph.round_ = function(num, places) { |
6a1aa64f DV |
1180 | var shift = Math.pow(10, places); |
1181 | return Math.round(num * shift)/shift; | |
1182 | }; | |
1183 | ||
1184 | /** | |
1185 | * Fires when there's data available to be graphed. | |
1186 | * @param {String} data Raw CSV data to be plotted | |
1187 | * @private | |
1188 | */ | |
285a6bda | 1189 | Dygraph.prototype.loadedEvent_ = function(data) { |
6a1aa64f DV |
1190 | this.rawData_ = this.parseCSV_(data); |
1191 | this.drawGraph_(this.rawData_); | |
1192 | }; | |
1193 | ||
285a6bda | 1194 | Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", |
8846615a | 1195 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; |
285a6bda | 1196 | Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"]; |
6a1aa64f DV |
1197 | |
1198 | /** | |
1199 | * Add ticks on the x-axis representing years, months, quarters, weeks, or days | |
1200 | * @private | |
1201 | */ | |
285a6bda | 1202 | Dygraph.prototype.addXTicks_ = function() { |
6a1aa64f DV |
1203 | // Determine the correct ticks scale on the x-axis: quarterly, monthly, ... |
1204 | var startDate, endDate; | |
1205 | if (this.dateWindow_) { | |
1206 | startDate = this.dateWindow_[0]; | |
1207 | endDate = this.dateWindow_[1]; | |
1208 | } else { | |
1209 | startDate = this.rawData_[0][0]; | |
1210 | endDate = this.rawData_[this.rawData_.length - 1][0]; | |
1211 | } | |
1212 | ||
285a6bda | 1213 | var xTicks = this.attr_('xTicker')(startDate, endDate, this); |
6a1aa64f | 1214 | this.layout_.updateOptions({xTicks: xTicks}); |
32988383 DV |
1215 | }; |
1216 | ||
1217 | // Time granularity enumeration | |
285a6bda | 1218 | Dygraph.SECONDLY = 0; |
20a41c17 DV |
1219 | Dygraph.TWO_SECONDLY = 1; |
1220 | Dygraph.FIVE_SECONDLY = 2; | |
1221 | Dygraph.TEN_SECONDLY = 3; | |
1222 | Dygraph.THIRTY_SECONDLY = 4; | |
1223 | Dygraph.MINUTELY = 5; | |
1224 | Dygraph.TWO_MINUTELY = 6; | |
1225 | Dygraph.FIVE_MINUTELY = 7; | |
1226 | Dygraph.TEN_MINUTELY = 8; | |
1227 | Dygraph.THIRTY_MINUTELY = 9; | |
1228 | Dygraph.HOURLY = 10; | |
1229 | Dygraph.TWO_HOURLY = 11; | |
1230 | Dygraph.SIX_HOURLY = 12; | |
1231 | Dygraph.DAILY = 13; | |
1232 | Dygraph.WEEKLY = 14; | |
1233 | Dygraph.MONTHLY = 15; | |
1234 | Dygraph.QUARTERLY = 16; | |
1235 | Dygraph.BIANNUAL = 17; | |
1236 | Dygraph.ANNUAL = 18; | |
1237 | Dygraph.DECADAL = 19; | |
1238 | Dygraph.NUM_GRANULARITIES = 20; | |
285a6bda DV |
1239 | |
1240 | Dygraph.SHORT_SPACINGS = []; | |
1241 | Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1; | |
20a41c17 DV |
1242 | Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2; |
1243 | Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5; | |
285a6bda DV |
1244 | Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10; |
1245 | Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30; | |
1246 | Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60; | |
20a41c17 DV |
1247 | Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2; |
1248 | Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5; | |
285a6bda DV |
1249 | Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10; |
1250 | Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30; | |
1251 | Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600; | |
20a41c17 | 1252 | Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2; |
805d5519 | 1253 | Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6; |
285a6bda DV |
1254 | Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400; |
1255 | Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800; | |
32988383 DV |
1256 | |
1257 | // NumXTicks() | |
1258 | // | |
1259 | // If we used this time granularity, how many ticks would there be? | |
1260 | // This is only an approximation, but it's generally good enough. | |
1261 | // | |
285a6bda DV |
1262 | Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) { |
1263 | if (granularity < Dygraph.MONTHLY) { | |
32988383 | 1264 | // Generate one tick mark for every fixed interval of time. |
285a6bda | 1265 | var spacing = Dygraph.SHORT_SPACINGS[granularity]; |
32988383 DV |
1266 | return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing); |
1267 | } else { | |
1268 | var year_mod = 1; // e.g. to only print one point every 10 years. | |
1269 | var num_months = 12; | |
285a6bda DV |
1270 | if (granularity == Dygraph.QUARTERLY) num_months = 3; |
1271 | if (granularity == Dygraph.BIANNUAL) num_months = 2; | |
1272 | if (granularity == Dygraph.ANNUAL) num_months = 1; | |
1273 | if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; } | |
32988383 DV |
1274 | |
1275 | var msInYear = 365.2524 * 24 * 3600 * 1000; | |
1276 | var num_years = 1.0 * (end_time - start_time) / msInYear; | |
1277 | return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod); | |
1278 | } | |
1279 | }; | |
1280 | ||
1281 | // GetXAxis() | |
1282 | // | |
1283 | // Construct an x-axis of nicely-formatted times on meaningful boundaries | |
1284 | // (e.g. 'Jan 09' rather than 'Jan 22, 2009'). | |
1285 | // | |
1286 | // Returns an array containing {v: millis, label: label} dictionaries. | |
1287 | // | |
285a6bda | 1288 | Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) { |
bf640e56 | 1289 | var formatter = this.attr_("xAxisLabelFormatter"); |
32988383 | 1290 | var ticks = []; |
285a6bda | 1291 | if (granularity < Dygraph.MONTHLY) { |
32988383 | 1292 | // Generate one tick mark for every fixed interval of time. |
285a6bda | 1293 | var spacing = Dygraph.SHORT_SPACINGS[granularity]; |
3d29302c | 1294 | var format = '%d%b'; // e.g. "1Jan" |
076c9622 DV |
1295 | |
1296 | // Find a time less than start_time which occurs on a "nice" time boundary | |
1297 | // for this granularity. | |
1298 | var g = spacing / 1000; | |
076c9622 DV |
1299 | var d = new Date(start_time); |
1300 | if (g <= 60) { // seconds | |
1301 | var x = d.getSeconds(); d.setSeconds(x - x % g); | |
1302 | } else { | |
1303 | d.setSeconds(0); | |
1304 | g /= 60; | |
1305 | if (g <= 60) { // minutes | |
1306 | var x = d.getMinutes(); d.setMinutes(x - x % g); | |
1307 | } else { | |
1308 | d.setMinutes(0); | |
1309 | g /= 60; | |
1310 | ||
1311 | if (g <= 24) { // days | |
1312 | var x = d.getHours(); d.setHours(x - x % g); | |
1313 | } else { | |
1314 | d.setHours(0); | |
1315 | g /= 24; | |
1316 | ||
1317 | if (g == 7) { // one week | |
20a41c17 | 1318 | d.setDate(d.getDate() - d.getDay()); |
076c9622 DV |
1319 | } |
1320 | } | |
1321 | } | |
328bb812 | 1322 | } |
076c9622 DV |
1323 | start_time = d.getTime(); |
1324 | ||
32988383 | 1325 | for (var t = start_time; t <= end_time; t += spacing) { |
bf640e56 | 1326 | ticks.push({ v:t, label: formatter(new Date(t), granularity) }); |
32988383 DV |
1327 | } |
1328 | } else { | |
1329 | // Display a tick mark on the first of a set of months of each year. | |
1330 | // Years get a tick mark iff y % year_mod == 0. This is useful for | |
1331 | // displaying a tick mark once every 10 years, say, on long time scales. | |
1332 | var months; | |
1333 | var year_mod = 1; // e.g. to only print one point every 10 years. | |
1334 | ||
285a6bda | 1335 | if (granularity == Dygraph.MONTHLY) { |
32988383 | 1336 | months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]; |
285a6bda | 1337 | } else if (granularity == Dygraph.QUARTERLY) { |
32988383 | 1338 | months = [ 0, 3, 6, 9 ]; |
285a6bda | 1339 | } else if (granularity == Dygraph.BIANNUAL) { |
32988383 | 1340 | months = [ 0, 6 ]; |
285a6bda | 1341 | } else if (granularity == Dygraph.ANNUAL) { |
32988383 | 1342 | months = [ 0 ]; |
285a6bda | 1343 | } else if (granularity == Dygraph.DECADAL) { |
32988383 DV |
1344 | months = [ 0 ]; |
1345 | year_mod = 10; | |
1346 | } | |
1347 | ||
1348 | var start_year = new Date(start_time).getFullYear(); | |
1349 | var end_year = new Date(end_time).getFullYear(); | |
285a6bda | 1350 | var zeropad = Dygraph.zeropad; |
32988383 DV |
1351 | for (var i = start_year; i <= end_year; i++) { |
1352 | if (i % year_mod != 0) continue; | |
1353 | for (var j = 0; j < months.length; j++) { | |
1354 | var date_str = i + "/" + zeropad(1 + months[j]) + "/01"; | |
1355 | var t = Date.parse(date_str); | |
1356 | if (t < start_time || t > end_time) continue; | |
bf640e56 | 1357 | ticks.push({ v:t, label: formatter(new Date(t), granularity) }); |
32988383 DV |
1358 | } |
1359 | } | |
1360 | } | |
1361 | ||
1362 | return ticks; | |
1363 | }; | |
1364 | ||
6a1aa64f DV |
1365 | |
1366 | /** | |
1367 | * Add ticks to the x-axis based on a date range. | |
1368 | * @param {Number} startDate Start of the date window (millis since epoch) | |
1369 | * @param {Number} endDate End of the date window (millis since epoch) | |
1370 | * @return {Array.<Object>} Array of {label, value} tuples. | |
1371 | * @public | |
1372 | */ | |
285a6bda | 1373 | Dygraph.dateTicker = function(startDate, endDate, self) { |
32988383 | 1374 | var chosen = -1; |
285a6bda DV |
1375 | for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) { |
1376 | var num_ticks = self.NumXTicks(startDate, endDate, i); | |
1377 | if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) { | |
32988383 DV |
1378 | chosen = i; |
1379 | break; | |
2769de62 | 1380 | } |
6a1aa64f DV |
1381 | } |
1382 | ||
32988383 | 1383 | if (chosen >= 0) { |
285a6bda | 1384 | return self.GetXAxis(startDate, endDate, chosen); |
6a1aa64f | 1385 | } else { |
32988383 | 1386 | // TODO(danvk): signal error. |
6a1aa64f | 1387 | } |
6a1aa64f DV |
1388 | }; |
1389 | ||
1390 | /** | |
1391 | * Add ticks when the x axis has numbers on it (instead of dates) | |
1392 | * @param {Number} startDate Start of the date window (millis since epoch) | |
1393 | * @param {Number} endDate End of the date window (millis since epoch) | |
1394 | * @return {Array.<Object>} Array of {label, value} tuples. | |
1395 | * @public | |
1396 | */ | |
285a6bda | 1397 | Dygraph.numericTicks = function(minV, maxV, self) { |
c6336f04 DV |
1398 | // Basic idea: |
1399 | // Try labels every 1, 2, 5, 10, 20, 50, 100, etc. | |
1400 | // Calculate the resulting tick spacing (i.e. this.height_ / nTicks). | |
285a6bda | 1401 | // The first spacing greater than pixelsPerYLabel is what we use. |
ff00d3e2 | 1402 | // TODO(danvk): version that works on a log scale. |
f09e46d4 DV |
1403 | if (self.attr_("labelsKMG2")) { |
1404 | var mults = [1, 2, 4, 8]; | |
1405 | } else { | |
1406 | var mults = [1, 2, 5]; | |
1407 | } | |
c6336f04 | 1408 | var scale, low_val, high_val, nTicks; |
285a6bda DV |
1409 | // TODO(danvk): make it possible to set this for x- and y-axes independently. |
1410 | var pixelsPerTick = self.attr_('pixelsPerYLabel'); | |
c6336f04 | 1411 | for (var i = -10; i < 50; i++) { |
f09e46d4 DV |
1412 | if (self.attr_("labelsKMG2")) { |
1413 | var base_scale = Math.pow(16, i); | |
1414 | } else { | |
1415 | var base_scale = Math.pow(10, i); | |
1416 | } | |
c6336f04 DV |
1417 | for (var j = 0; j < mults.length; j++) { |
1418 | scale = base_scale * mults[j]; | |
c6336f04 DV |
1419 | low_val = Math.floor(minV / scale) * scale; |
1420 | high_val = Math.ceil(maxV / scale) * scale; | |
48a0ac91 | 1421 | nTicks = Math.abs(high_val - low_val) / scale; |
285a6bda | 1422 | var spacing = self.height_ / nTicks; |
c6336f04 | 1423 | // wish I could break out of both loops at once... |
285a6bda | 1424 | if (spacing > pixelsPerTick) break; |
c6336f04 | 1425 | } |
285a6bda | 1426 | if (spacing > pixelsPerTick) break; |
6a1aa64f DV |
1427 | } |
1428 | ||
1429 | // Construct labels for the ticks | |
1430 | var ticks = []; | |
ed11be50 DV |
1431 | var k; |
1432 | var k_labels = []; | |
1433 | if (self.attr_("labelsKMB")) { | |
1434 | k = 1000; | |
1435 | k_labels = [ "K", "M", "B", "T" ]; | |
1436 | } | |
1437 | if (self.attr_("labelsKMG2")) { | |
1438 | if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!"); | |
1439 | k = 1024; | |
1440 | k_labels = [ "k", "M", "G", "T" ]; | |
1441 | } | |
1442 | ||
e21e69e2 | 1443 | // Allow reverse y-axis if it's explicitly requested. |
be7cdb11 | 1444 | if (low_val > high_val) scale *= -1; |
48a0ac91 | 1445 | |
c6336f04 DV |
1446 | for (var i = 0; i < nTicks; i++) { |
1447 | var tickV = low_val + i * scale; | |
0af6e346 | 1448 | var absTickV = Math.abs(tickV); |
029da4b6 | 1449 | var label = Dygraph.round_(tickV, 2); |
ed11be50 DV |
1450 | if (k_labels.length) { |
1451 | // Round up to an appropriate unit. | |
1452 | var n = k*k*k*k; | |
1453 | for (var j = 3; j >= 0; j--, n /= k) { | |
1454 | if (absTickV >= n) { | |
029da4b6 | 1455 | label = Dygraph.round_(tickV / n, 1) + k_labels[j]; |
ed11be50 DV |
1456 | break; |
1457 | } | |
afefbcdb | 1458 | } |
6a1aa64f DV |
1459 | } |
1460 | ticks.push( {label: label, v: tickV} ); | |
1461 | } | |
1462 | return ticks; | |
1463 | }; | |
1464 | ||
1465 | /** | |
1466 | * Adds appropriate ticks on the y-axis | |
1467 | * @param {Number} minY The minimum Y value in the data set | |
1468 | * @param {Number} maxY The maximum Y value in the data set | |
1469 | * @private | |
1470 | */ | |
285a6bda | 1471 | Dygraph.prototype.addYTicks_ = function(minY, maxY) { |
6a1aa64f | 1472 | // Set the number of ticks so that the labels are human-friendly. |
285a6bda DV |
1473 | // TODO(danvk): make this an attribute as well. |
1474 | var ticks = Dygraph.numericTicks(minY, maxY, this); | |
6a1aa64f DV |
1475 | this.layout_.updateOptions( { yAxis: [minY, maxY], |
1476 | yTicks: ticks } ); | |
1477 | }; | |
1478 | ||
5011e7a1 DV |
1479 | // Computes the range of the data series (including confidence intervals). |
1480 | // series is either [ [x1, y1], [x2, y2], ... ] or | |
1481 | // [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ... | |
1482 | // Returns [low, high] | |
1483 | Dygraph.prototype.extremeValues_ = function(series) { | |
1484 | var minY = null, maxY = null; | |
1485 | ||
9922b78b | 1486 | var bars = this.attr_("errorBars") || this.attr_("customBars"); |
5011e7a1 DV |
1487 | if (bars) { |
1488 | // With custom bars, maxY is the max of the high values. | |
1489 | for (var j = 0; j < series.length; j++) { | |
1490 | var y = series[j][1][0]; | |
1491 | if (!y) continue; | |
1492 | var low = y - series[j][1][1]; | |
1493 | var high = y + series[j][1][2]; | |
1494 | if (low > y) low = y; // this can happen with custom bars, | |
1495 | if (high < y) high = y; // e.g. in tests/custom-bars.html | |
1496 | if (maxY == null || high > maxY) { | |
1497 | maxY = high; | |
1498 | } | |
1499 | if (minY == null || low < minY) { | |
1500 | minY = low; | |
1501 | } | |
1502 | } | |
1503 | } else { | |
1504 | for (var j = 0; j < series.length; j++) { | |
1505 | var y = series[j][1]; | |
d12999d3 | 1506 | if (y === null || isNaN(y)) continue; |
5011e7a1 DV |
1507 | if (maxY == null || y > maxY) { |
1508 | maxY = y; | |
1509 | } | |
1510 | if (minY == null || y < minY) { | |
1511 | minY = y; | |
1512 | } | |
1513 | } | |
1514 | } | |
1515 | ||
1516 | return [minY, maxY]; | |
1517 | }; | |
1518 | ||
6a1aa64f DV |
1519 | /** |
1520 | * Update the graph with new data. Data is in the format | |
1521 | * [ [date1, val1, val2, ...], [date2, val1, val2, ...] if errorBars=false | |
1522 | * or, if errorBars=true, | |
1523 | * [ [date1, [val1,stddev1], [val2,stddev2], ...], [date2, ...], ...] | |
1524 | * @param {Array.<Object>} data The data (see above) | |
1525 | * @private | |
1526 | */ | |
285a6bda | 1527 | Dygraph.prototype.drawGraph_ = function(data) { |
fe0b7c03 DV |
1528 | // This is used to set the second parameter to drawCallback, below. |
1529 | var is_initial_draw = this.is_initial_draw_; | |
1530 | this.is_initial_draw_ = false; | |
1531 | ||
3bd9c228 | 1532 | var minY = null, maxY = null; |
6a1aa64f | 1533 | this.layout_.removeAllDatasets(); |
285a6bda | 1534 | this.setColors_(); |
9317362d | 1535 | this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize'); |
285a6bda | 1536 | |
f032c51d AV |
1537 | var connectSeparatedPoints = this.attr_('connectSeparatedPoints'); |
1538 | ||
354e15ab DE |
1539 | // Loop over the fields (series). Go from the last to the first, |
1540 | // because if they're stacked that's how we accumulate the values. | |
43af96e7 | 1541 | |
354e15ab DE |
1542 | var cumulative_y = []; // For stacked series. |
1543 | var datasets = []; | |
1544 | ||
1545 | // Loop over all fields and create datasets | |
1546 | for (var i = data[0].length - 1; i >= 1; i--) { | |
1cf11047 DV |
1547 | if (!this.visibility()[i - 1]) continue; |
1548 | ||
6a1aa64f DV |
1549 | var series = []; |
1550 | for (var j = 0; j < data.length; j++) { | |
4a634fc7 | 1551 | if (data[j][i] != null || !connectSeparatedPoints) { |
f032c51d | 1552 | var date = data[j][0]; |
563c70ca | 1553 | series.push([date, data[j][i]]); |
f032c51d | 1554 | } |
6a1aa64f DV |
1555 | } |
1556 | series = this.rollingAverage(series, this.rollPeriod_); | |
1557 | ||
1558 | // Prune down to the desired range, if necessary (for zooming) | |
1a26f3fb DV |
1559 | // Because there can be lines going to points outside of the visible area, |
1560 | // we actually prune to visible points, plus one on either side. | |
9922b78b | 1561 | var bars = this.attr_("errorBars") || this.attr_("customBars"); |
6a1aa64f DV |
1562 | if (this.dateWindow_) { |
1563 | var low = this.dateWindow_[0]; | |
1564 | var high= this.dateWindow_[1]; | |
1565 | var pruned = []; | |
1a26f3fb DV |
1566 | // TODO(danvk): do binary search instead of linear search. |
1567 | // TODO(danvk): pass firstIdx and lastIdx directly to the renderer. | |
1568 | var firstIdx = null, lastIdx = null; | |
6a1aa64f | 1569 | for (var k = 0; k < series.length; k++) { |
1a26f3fb DV |
1570 | if (series[k][0] >= low && firstIdx === null) { |
1571 | firstIdx = k; | |
1572 | } | |
1573 | if (series[k][0] <= high) { | |
1574 | lastIdx = k; | |
6a1aa64f DV |
1575 | } |
1576 | } | |
1a26f3fb DV |
1577 | if (firstIdx === null) firstIdx = 0; |
1578 | if (firstIdx > 0) firstIdx--; | |
1579 | if (lastIdx === null) lastIdx = series.length - 1; | |
1580 | if (lastIdx < series.length - 1) lastIdx++; | |
16269f6e | 1581 | this.boundaryIds_[i-1] = [firstIdx, lastIdx]; |
1a26f3fb DV |
1582 | for (var k = firstIdx; k <= lastIdx; k++) { |
1583 | pruned.push(series[k]); | |
6a1aa64f DV |
1584 | } |
1585 | series = pruned; | |
16269f6e NAG |
1586 | } else { |
1587 | this.boundaryIds_[i-1] = [0, series.length-1]; | |
6a1aa64f DV |
1588 | } |
1589 | ||
648acd28 DV |
1590 | var extremes = this.extremeValues_(series); |
1591 | var thisMinY = extremes[0]; | |
1592 | var thisMaxY = extremes[1]; | |
61b78cd6 DV |
1593 | if (minY === null || thisMinY < minY) minY = thisMinY; |
1594 | if (maxY === null || thisMaxY > maxY) maxY = thisMaxY; | |
5011e7a1 | 1595 | |
6a1aa64f | 1596 | if (bars) { |
354e15ab DE |
1597 | for (var j=0; j<series.length; j++) { |
1598 | val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]]; | |
1599 | series[j] = val; | |
1600 | } | |
43af96e7 | 1601 | } else if (this.attr_("stackedGraph")) { |
43af96e7 NK |
1602 | var l = series.length; |
1603 | var actual_y; | |
1604 | for (var j = 0; j < l; j++) { | |
354e15ab DE |
1605 | // If one data set has a NaN, let all subsequent stacked |
1606 | // sets inherit the NaN -- only start at 0 for the first set. | |
1607 | var x = series[j][0]; | |
1608 | if (cumulative_y[x] === undefined) | |
1609 | cumulative_y[x] = 0; | |
43af96e7 NK |
1610 | |
1611 | actual_y = series[j][1]; | |
354e15ab | 1612 | cumulative_y[x] += actual_y; |
43af96e7 | 1613 | |
354e15ab | 1614 | series[j] = [x, cumulative_y[x]] |
43af96e7 | 1615 | |
354e15ab DE |
1616 | if (!maxY || cumulative_y[x] > maxY) |
1617 | maxY = cumulative_y[x]; | |
43af96e7 | 1618 | } |
6a1aa64f | 1619 | } |
354e15ab DE |
1620 | |
1621 | datasets[i] = series; | |
6a1aa64f DV |
1622 | } |
1623 | ||
354e15ab | 1624 | for (var i = 1; i < datasets.length; i++) { |
4523c1f6 | 1625 | if (!this.visibility()[i - 1]) continue; |
354e15ab | 1626 | this.layout_.addDataset(this.attr_("labels")[i], datasets[i]); |
43af96e7 NK |
1627 | } |
1628 | ||
6a1aa64f DV |
1629 | // Use some heuristics to come up with a good maxY value, unless it's been |
1630 | // set explicitly by the user. | |
1631 | if (this.valueRange_ != null) { | |
1632 | this.addYTicks_(this.valueRange_[0], this.valueRange_[1]); | |
3230c662 | 1633 | this.displayedYRange_ = this.valueRange_; |
6a1aa64f | 1634 | } else { |
d053ab5a DV |
1635 | // This affects the calculation of span, below. |
1636 | if (this.attr_("includeZero") && minY > 0) { | |
1637 | minY = 0; | |
1638 | } | |
1639 | ||
6a1aa64f | 1640 | // Add some padding and round up to an integer to be human-friendly. |
3bd9c228 | 1641 | var span = maxY - minY; |
93dfacfd DV |
1642 | // special case: if we have no sense of scale, use +/-10% of the sole value. |
1643 | if (span == 0) { span = maxY; } | |
3bd9c228 DV |
1644 | var maxAxisY = maxY + 0.1 * span; |
1645 | var minAxisY = minY - 0.1 * span; | |
1646 | ||
1647 | // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense. | |
ceb009dd DV |
1648 | if (minAxisY < 0 && minY >= 0) minAxisY = 0; |
1649 | if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0; | |
3bd9c228 DV |
1650 | |
1651 | if (this.attr_("includeZero")) { | |
1652 | if (maxY < 0) maxAxisY = 0; | |
1653 | if (minY > 0) minAxisY = 0; | |
1654 | } | |
1655 | ||
1656 | this.addYTicks_(minAxisY, maxAxisY); | |
3230c662 | 1657 | this.displayedYRange_ = [minAxisY, maxAxisY]; |
6a1aa64f DV |
1658 | } |
1659 | ||
1660 | this.addXTicks_(); | |
1661 | ||
1662 | // Tell PlotKit to use this new data and render itself | |
d033ae1c | 1663 | this.layout_.updateOptions({dateWindow: this.dateWindow_}); |
6a1aa64f DV |
1664 | this.layout_.evaluateWithError(); |
1665 | this.plotter_.clear(); | |
1666 | this.plotter_.render(); | |
f6401bf6 DV |
1667 | this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width, |
1668 | this.canvas_.height); | |
599fb4ad DV |
1669 | |
1670 | if (this.attr_("drawCallback") !== null) { | |
fe0b7c03 | 1671 | this.attr_("drawCallback")(this, is_initial_draw); |
599fb4ad | 1672 | } |
6a1aa64f DV |
1673 | }; |
1674 | ||
1675 | /** | |
1676 | * Calculates the rolling average of a data set. | |
1677 | * If originalData is [label, val], rolls the average of those. | |
1678 | * If originalData is [label, [, it's interpreted as [value, stddev] | |
1679 | * and the roll is returned in the same form, with appropriately reduced | |
1680 | * stddev for each value. | |
1681 | * Note that this is where fractional input (i.e. '5/10') is converted into | |
1682 | * decimal values. | |
1683 | * @param {Array} originalData The data in the appropriate format (see above) | |
1684 | * @param {Number} rollPeriod The number of days over which to average the data | |
1685 | */ | |
285a6bda | 1686 | Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) { |
6a1aa64f DV |
1687 | if (originalData.length < 2) |
1688 | return originalData; | |
1689 | var rollPeriod = Math.min(rollPeriod, originalData.length - 1); | |
1690 | var rollingData = []; | |
285a6bda | 1691 | var sigma = this.attr_("sigma"); |
6a1aa64f DV |
1692 | |
1693 | if (this.fractions_) { | |
1694 | var num = 0; | |
1695 | var den = 0; // numerator/denominator | |
1696 | var mult = 100.0; | |
1697 | for (var i = 0; i < originalData.length; i++) { | |
1698 | num += originalData[i][1][0]; | |
1699 | den += originalData[i][1][1]; | |
1700 | if (i - rollPeriod >= 0) { | |
1701 | num -= originalData[i - rollPeriod][1][0]; | |
1702 | den -= originalData[i - rollPeriod][1][1]; | |
1703 | } | |
1704 | ||
1705 | var date = originalData[i][0]; | |
1706 | var value = den ? num / den : 0.0; | |
285a6bda | 1707 | if (this.attr_("errorBars")) { |
6a1aa64f DV |
1708 | if (this.wilsonInterval_) { |
1709 | // For more details on this confidence interval, see: | |
1710 | // http://en.wikipedia.org/wiki/Binomial_confidence_interval | |
1711 | if (den) { | |
1712 | var p = value < 0 ? 0 : value, n = den; | |
1713 | var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n)); | |
1714 | var denom = 1 + sigma * sigma / den; | |
1715 | var low = (p + sigma * sigma / (2 * den) - pm) / denom; | |
1716 | var high = (p + sigma * sigma / (2 * den) + pm) / denom; | |
1717 | rollingData[i] = [date, | |
1718 | [p * mult, (p - low) * mult, (high - p) * mult]]; | |
1719 | } else { | |
1720 | rollingData[i] = [date, [0, 0, 0]]; | |
1721 | } | |
1722 | } else { | |
1723 | var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0; | |
1724 | rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]]; | |
1725 | } | |
1726 | } else { | |
1727 | rollingData[i] = [date, mult * value]; | |
1728 | } | |
1729 | } | |
9922b78b | 1730 | } else if (this.attr_("customBars")) { |
f6885d6a DV |
1731 | var low = 0; |
1732 | var mid = 0; | |
1733 | var high = 0; | |
1734 | var count = 0; | |
6a1aa64f DV |
1735 | for (var i = 0; i < originalData.length; i++) { |
1736 | var data = originalData[i][1]; | |
1737 | var y = data[1]; | |
1738 | rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]]; | |
f6885d6a | 1739 | |
8b91c51f | 1740 | if (y != null && !isNaN(y)) { |
49a7d0d5 DV |
1741 | low += data[0]; |
1742 | mid += y; | |
1743 | high += data[2]; | |
1744 | count += 1; | |
1745 | } | |
f6885d6a DV |
1746 | if (i - rollPeriod >= 0) { |
1747 | var prev = originalData[i - rollPeriod]; | |
8b91c51f | 1748 | if (prev[1][1] != null && !isNaN(prev[1][1])) { |
49a7d0d5 DV |
1749 | low -= prev[1][0]; |
1750 | mid -= prev[1][1]; | |
1751 | high -= prev[1][2]; | |
1752 | count -= 1; | |
1753 | } | |
f6885d6a DV |
1754 | } |
1755 | rollingData[i] = [originalData[i][0], [ 1.0 * mid / count, | |
1756 | 1.0 * (mid - low) / count, | |
1757 | 1.0 * (high - mid) / count ]]; | |
2769de62 | 1758 | } |
6a1aa64f DV |
1759 | } else { |
1760 | // Calculate the rolling average for the first rollPeriod - 1 points where | |
1761 | // there is not enough data to roll over the full number of days | |
1762 | var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2); | |
285a6bda | 1763 | if (!this.attr_("errorBars")){ |
5011e7a1 DV |
1764 | if (rollPeriod == 1) { |
1765 | return originalData; | |
1766 | } | |
1767 | ||
2847c1cf | 1768 | for (var i = 0; i < originalData.length; i++) { |
6a1aa64f | 1769 | var sum = 0; |
5011e7a1 | 1770 | var num_ok = 0; |
2847c1cf DV |
1771 | for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { |
1772 | var y = originalData[j][1]; | |
8b91c51f | 1773 | if (y == null || isNaN(y)) continue; |
5011e7a1 | 1774 | num_ok++; |
2847c1cf | 1775 | sum += originalData[j][1]; |
6a1aa64f | 1776 | } |
5011e7a1 | 1777 | if (num_ok) { |
2847c1cf | 1778 | rollingData[i] = [originalData[i][0], sum / num_ok]; |
5011e7a1 | 1779 | } else { |
2847c1cf | 1780 | rollingData[i] = [originalData[i][0], null]; |
5011e7a1 | 1781 | } |
6a1aa64f | 1782 | } |
2847c1cf DV |
1783 | |
1784 | } else { | |
1785 | for (var i = 0; i < originalData.length; i++) { | |
6a1aa64f DV |
1786 | var sum = 0; |
1787 | var variance = 0; | |
5011e7a1 | 1788 | var num_ok = 0; |
2847c1cf | 1789 | for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { |
5011e7a1 | 1790 | var y = originalData[j][1][0]; |
8b91c51f | 1791 | if (y == null || isNaN(y)) continue; |
5011e7a1 | 1792 | num_ok++; |
6a1aa64f DV |
1793 | sum += originalData[j][1][0]; |
1794 | variance += Math.pow(originalData[j][1][1], 2); | |
1795 | } | |
5011e7a1 DV |
1796 | if (num_ok) { |
1797 | var stddev = Math.sqrt(variance) / num_ok; | |
1798 | rollingData[i] = [originalData[i][0], | |
1799 | [sum / num_ok, sigma * stddev, sigma * stddev]]; | |
1800 | } else { | |
1801 | rollingData[i] = [originalData[i][0], [null, null, null]]; | |
1802 | } | |
6a1aa64f DV |
1803 | } |
1804 | } | |
1805 | } | |
1806 | ||
1807 | return rollingData; | |
1808 | }; | |
1809 | ||
1810 | /** | |
1811 | * Parses a date, returning the number of milliseconds since epoch. This can be | |
285a6bda DV |
1812 | * passed in as an xValueParser in the Dygraph constructor. |
1813 | * TODO(danvk): enumerate formats that this understands. | |
6a1aa64f DV |
1814 | * @param {String} A date in YYYYMMDD format. |
1815 | * @return {Number} Milliseconds since epoch. | |
1816 | * @public | |
1817 | */ | |
285a6bda | 1818 | Dygraph.dateParser = function(dateStr, self) { |
6a1aa64f | 1819 | var dateStrSlashed; |
285a6bda | 1820 | var d; |
986a5026 | 1821 | if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' |
6a1aa64f | 1822 | dateStrSlashed = dateStr.replace("-", "/", "g"); |
353a0294 DV |
1823 | while (dateStrSlashed.search("-") != -1) { |
1824 | dateStrSlashed = dateStrSlashed.replace("-", "/"); | |
1825 | } | |
285a6bda | 1826 | d = Date.parse(dateStrSlashed); |
2769de62 | 1827 | } else if (dateStr.length == 8) { // e.g. '20090712' |
285a6bda | 1828 | // TODO(danvk): remove support for this format. It's confusing. |
6a1aa64f DV |
1829 | dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) |
1830 | + "/" + dateStr.substr(6,2); | |
285a6bda | 1831 | d = Date.parse(dateStrSlashed); |
2769de62 DV |
1832 | } else { |
1833 | // Any format that Date.parse will accept, e.g. "2009/07/12" or | |
1834 | // "2009/07/12 12:34:56" | |
285a6bda DV |
1835 | d = Date.parse(dateStr); |
1836 | } | |
1837 | ||
1838 | if (!d || isNaN(d)) { | |
1839 | self.error("Couldn't parse " + dateStr + " as a date"); | |
1840 | } | |
1841 | return d; | |
1842 | }; | |
1843 | ||
1844 | /** | |
1845 | * Detects the type of the str (date or numeric) and sets the various | |
1846 | * formatting attributes in this.attrs_ based on this type. | |
1847 | * @param {String} str An x value. | |
1848 | * @private | |
1849 | */ | |
1850 | Dygraph.prototype.detectTypeFromString_ = function(str) { | |
1851 | var isDate = false; | |
1852 | if (str.indexOf('-') >= 0 || | |
1853 | str.indexOf('/') >= 0 || | |
1854 | isNaN(parseFloat(str))) { | |
1855 | isDate = true; | |
1856 | } else if (str.length == 8 && str > '19700101' && str < '20371231') { | |
1857 | // TODO(danvk): remove support for this format. | |
1858 | isDate = true; | |
1859 | } | |
1860 | ||
1861 | if (isDate) { | |
1862 | this.attrs_.xValueFormatter = Dygraph.dateString_; | |
1863 | this.attrs_.xValueParser = Dygraph.dateParser; | |
1864 | this.attrs_.xTicker = Dygraph.dateTicker; | |
bf640e56 | 1865 | this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter; |
285a6bda DV |
1866 | } else { |
1867 | this.attrs_.xValueFormatter = function(x) { return x; }; | |
1868 | this.attrs_.xValueParser = function(x) { return parseFloat(x); }; | |
1869 | this.attrs_.xTicker = Dygraph.numericTicks; | |
bf640e56 | 1870 | this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter; |
6a1aa64f | 1871 | } |
6a1aa64f DV |
1872 | }; |
1873 | ||
1874 | /** | |
1875 | * Parses a string in a special csv format. We expect a csv file where each | |
1876 | * line is a date point, and the first field in each line is the date string. | |
1877 | * We also expect that all remaining fields represent series. | |
285a6bda | 1878 | * if the errorBars attribute is set, then interpret the fields as: |
6a1aa64f DV |
1879 | * date, series1, stddev1, series2, stddev2, ... |
1880 | * @param {Array.<Object>} data See above. | |
1881 | * @private | |
285a6bda DV |
1882 | * |
1883 | * @return Array.<Object> An array with one entry for each row. These entries | |
1884 | * are an array of cells in that row. The first entry is the parsed x-value for | |
1885 | * the row. The second, third, etc. are the y-values. These can take on one of | |
1886 | * three forms, depending on the CSV and constructor parameters: | |
1887 | * 1. numeric value | |
1888 | * 2. [ value, stddev ] | |
1889 | * 3. [ low value, center value, high value ] | |
6a1aa64f | 1890 | */ |
285a6bda | 1891 | Dygraph.prototype.parseCSV_ = function(data) { |
6a1aa64f DV |
1892 | var ret = []; |
1893 | var lines = data.split("\n"); | |
3d67f03b DV |
1894 | |
1895 | // Use the default delimiter or fall back to a tab if that makes sense. | |
1896 | var delim = this.attr_('delimiter'); | |
1897 | if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) { | |
1898 | delim = '\t'; | |
1899 | } | |
1900 | ||
285a6bda | 1901 | var start = 0; |
6a1aa64f | 1902 | if (this.labelsFromCSV_) { |
285a6bda | 1903 | start = 1; |
3d67f03b | 1904 | this.attrs_.labels = lines[0].split(delim); |
6a1aa64f DV |
1905 | } |
1906 | ||
03b522a4 DV |
1907 | // Parse the x as a float or return null if it's not a number. |
1908 | var parseFloatOrNull = function(x) { | |
41333ec0 DV |
1909 | var val = parseFloat(x); |
1910 | return isNaN(val) ? null : val; | |
03b522a4 DV |
1911 | }; |
1912 | ||
285a6bda DV |
1913 | var xParser; |
1914 | var defaultParserSet = false; // attempt to auto-detect x value type | |
1915 | var expectedCols = this.attr_("labels").length; | |
987840a2 | 1916 | var outOfOrder = false; |
6a1aa64f DV |
1917 | for (var i = start; i < lines.length; i++) { |
1918 | var line = lines[i]; | |
1919 | if (line.length == 0) continue; // skip blank lines | |
3d67f03b DV |
1920 | if (line[0] == '#') continue; // skip comment lines |
1921 | var inFields = line.split(delim); | |
285a6bda | 1922 | if (inFields.length < 2) continue; |
6a1aa64f DV |
1923 | |
1924 | var fields = []; | |
285a6bda DV |
1925 | if (!defaultParserSet) { |
1926 | this.detectTypeFromString_(inFields[0]); | |
1927 | xParser = this.attr_("xValueParser"); | |
1928 | defaultParserSet = true; | |
1929 | } | |
1930 | fields[0] = xParser(inFields[0], this); | |
6a1aa64f DV |
1931 | |
1932 | // If fractions are expected, parse the numbers as "A/B" | |
1933 | if (this.fractions_) { | |
1934 | for (var j = 1; j < inFields.length; j++) { | |
1935 | // TODO(danvk): figure out an appropriate way to flag parse errors. | |
1936 | var vals = inFields[j].split("/"); | |
03b522a4 | 1937 | fields[j] = [parseFloatOrNull(vals[0]), parseFloatOrNull(vals[1])]; |
6a1aa64f | 1938 | } |
285a6bda | 1939 | } else if (this.attr_("errorBars")) { |
6a1aa64f DV |
1940 | // If there are error bars, values are (value, stddev) pairs |
1941 | for (var j = 1; j < inFields.length; j += 2) | |
03b522a4 DV |
1942 | fields[(j + 1) / 2] = [parseFloatOrNull(inFields[j]), |
1943 | parseFloatOrNull(inFields[j + 1])]; | |
9922b78b | 1944 | } else if (this.attr_("customBars")) { |
6a1aa64f DV |
1945 | // Bars are a low;center;high tuple |
1946 | for (var j = 1; j < inFields.length; j++) { | |
1947 | var vals = inFields[j].split(";"); | |
03b522a4 DV |
1948 | fields[j] = [ parseFloatOrNull(vals[0]), |
1949 | parseFloatOrNull(vals[1]), | |
1950 | parseFloatOrNull(vals[2]) ]; | |
6a1aa64f DV |
1951 | } |
1952 | } else { | |
1953 | // Values are just numbers | |
285a6bda | 1954 | for (var j = 1; j < inFields.length; j++) { |
03b522a4 | 1955 | fields[j] = parseFloatOrNull(inFields[j]); |
285a6bda | 1956 | } |
6a1aa64f | 1957 | } |
987840a2 DV |
1958 | if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) { |
1959 | outOfOrder = true; | |
1960 | } | |
6a1aa64f | 1961 | ret.push(fields); |
285a6bda DV |
1962 | |
1963 | if (fields.length != expectedCols) { | |
1964 | this.error("Number of columns in line " + i + " (" + fields.length + | |
1965 | ") does not agree with number of labels (" + expectedCols + | |
1966 | ") " + line); | |
1967 | } | |
6a1aa64f | 1968 | } |
987840a2 DV |
1969 | |
1970 | if (outOfOrder) { | |
1971 | this.warn("CSV is out of order; order it correctly to speed loading."); | |
1972 | ret.sort(function(a,b) { return a[0] - b[0] }); | |
1973 | } | |
1974 | ||
6a1aa64f DV |
1975 | return ret; |
1976 | }; | |
1977 | ||
1978 | /** | |
285a6bda DV |
1979 | * The user has provided their data as a pre-packaged JS array. If the x values |
1980 | * are numeric, this is the same as dygraphs' internal format. If the x values | |
1981 | * are dates, we need to convert them from Date objects to ms since epoch. | |
1982 | * @param {Array.<Object>} data | |
1983 | * @return {Array.<Object>} data with numeric x values. | |
1984 | */ | |
1985 | Dygraph.prototype.parseArray_ = function(data) { | |
1986 | // Peek at the first x value to see if it's numeric. | |
1987 | if (data.length == 0) { | |
1988 | this.error("Can't plot empty data set"); | |
1989 | return null; | |
1990 | } | |
1991 | if (data[0].length == 0) { | |
1992 | this.error("Data set cannot contain an empty row"); | |
1993 | return null; | |
1994 | } | |
1995 | ||
1996 | if (this.attr_("labels") == null) { | |
1997 | this.warn("Using default labels. Set labels explicitly via 'labels' " + | |
1998 | "in the options parameter"); | |
1999 | this.attrs_.labels = [ "X" ]; | |
2000 | for (var i = 1; i < data[0].length; i++) { | |
2001 | this.attrs_.labels.push("Y" + i); | |
2002 | } | |
2003 | } | |
2004 | ||
2dda3850 | 2005 | if (Dygraph.isDateLike(data[0][0])) { |
285a6bda DV |
2006 | // Some intelligent defaults for a date x-axis. |
2007 | this.attrs_.xValueFormatter = Dygraph.dateString_; | |
bf640e56 | 2008 | this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter; |
285a6bda DV |
2009 | this.attrs_.xTicker = Dygraph.dateTicker; |
2010 | ||
2011 | // Assume they're all dates. | |
e3ab7b40 | 2012 | var parsedData = Dygraph.clone(data); |
285a6bda DV |
2013 | for (var i = 0; i < data.length; i++) { |
2014 | if (parsedData[i].length == 0) { | |
a323ff4a | 2015 | this.error("Row " + (1 + i) + " of data is empty"); |
285a6bda DV |
2016 | return null; |
2017 | } | |
2018 | if (parsedData[i][0] == null | |
3a909ec5 DV |
2019 | || typeof(parsedData[i][0].getTime) != 'function' |
2020 | || isNaN(parsedData[i][0].getTime())) { | |
be96a1f5 | 2021 | this.error("x value in row " + (1 + i) + " is not a Date"); |
285a6bda DV |
2022 | return null; |
2023 | } | |
2024 | parsedData[i][0] = parsedData[i][0].getTime(); | |
2025 | } | |
2026 | return parsedData; | |
2027 | } else { | |
2028 | // Some intelligent defaults for a numeric x-axis. | |
2029 | this.attrs_.xValueFormatter = function(x) { return x; }; | |
2030 | this.attrs_.xTicker = Dygraph.numericTicks; | |
2031 | return data; | |
2032 | } | |
2033 | }; | |
2034 | ||
2035 | /** | |
79420a1e DV |
2036 | * Parses a DataTable object from gviz. |
2037 | * The data is expected to have a first column that is either a date or a | |
2038 | * number. All subsequent columns must be numbers. If there is a clear mismatch | |
2039 | * between this.xValueParser_ and the type of the first column, it will be | |
a685723c | 2040 | * fixed. Fills out rawData_. |
79420a1e DV |
2041 | * @param {Array.<Object>} data See above. |
2042 | * @private | |
2043 | */ | |
285a6bda | 2044 | Dygraph.prototype.parseDataTable_ = function(data) { |
79420a1e DV |
2045 | var cols = data.getNumberOfColumns(); |
2046 | var rows = data.getNumberOfRows(); | |
2047 | ||
d955e223 | 2048 | var indepType = data.getColumnType(0); |
4440f6c8 | 2049 | if (indepType == 'date' || indepType == 'datetime') { |
285a6bda DV |
2050 | this.attrs_.xValueFormatter = Dygraph.dateString_; |
2051 | this.attrs_.xValueParser = Dygraph.dateParser; | |
2052 | this.attrs_.xTicker = Dygraph.dateTicker; | |
bf640e56 | 2053 | this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter; |
33127159 | 2054 | } else if (indepType == 'number') { |
285a6bda DV |
2055 | this.attrs_.xValueFormatter = function(x) { return x; }; |
2056 | this.attrs_.xValueParser = function(x) { return parseFloat(x); }; | |
2057 | this.attrs_.xTicker = Dygraph.numericTicks; | |
bf640e56 | 2058 | this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter; |
285a6bda | 2059 | } else { |
987840a2 DV |
2060 | this.error("only 'date', 'datetime' and 'number' types are supported for " + |
2061 | "column 1 of DataTable input (Got '" + indepType + "')"); | |
79420a1e DV |
2062 | return null; |
2063 | } | |
2064 | ||
a685723c DV |
2065 | // Array of the column indices which contain data (and not annotations). |
2066 | var colIdx = []; | |
2067 | var annotationCols = {}; // data index -> [annotation cols] | |
2068 | var hasAnnotations = false; | |
2069 | for (var i = 1; i < cols; i++) { | |
2070 | var type = data.getColumnType(i); | |
2071 | if (type == 'number') { | |
2072 | colIdx.push(i); | |
2073 | } else if (type == 'string' && this.attr_('displayAnnotations')) { | |
2074 | // This is OK -- it's an annotation column. | |
2075 | var dataIdx = colIdx[colIdx.length - 1]; | |
2076 | if (!annotationCols.hasOwnProperty(dataIdx)) { | |
2077 | annotationCols[dataIdx] = [i]; | |
2078 | } else { | |
2079 | annotationCols[dataIdx].push(i); | |
2080 | } | |
2081 | hasAnnotations = true; | |
2082 | } else { | |
2083 | this.error("Only 'number' is supported as a dependent type with Gviz." + | |
2084 | " 'string' is only supported if displayAnnotations is true"); | |
2085 | } | |
2086 | } | |
2087 | ||
2088 | // Read column labels | |
2089 | // TODO(danvk): add support back for errorBars | |
2090 | var labels = [data.getColumnLabel(0)]; | |
2091 | for (var i = 0; i < colIdx.length; i++) { | |
2092 | labels.push(data.getColumnLabel(colIdx[i])); | |
2093 | } | |
2094 | this.attrs_.labels = labels; | |
2095 | cols = labels.length; | |
2096 | ||
79420a1e | 2097 | var ret = []; |
987840a2 | 2098 | var outOfOrder = false; |
a685723c | 2099 | var annotations = []; |
79420a1e DV |
2100 | for (var i = 0; i < rows; i++) { |
2101 | var row = []; | |
debe4434 DV |
2102 | if (typeof(data.getValue(i, 0)) === 'undefined' || |
2103 | data.getValue(i, 0) === null) { | |
2104 | this.warning("Ignoring row " + i + | |
2105 | " of DataTable because of undefined or null first column."); | |
2106 | continue; | |
2107 | } | |
2108 | ||
c21d2c2d | 2109 | if (indepType == 'date' || indepType == 'datetime') { |
d955e223 DV |
2110 | row.push(data.getValue(i, 0).getTime()); |
2111 | } else { | |
2112 | row.push(data.getValue(i, 0)); | |
2113 | } | |
3e3f84e4 | 2114 | if (!this.attr_("errorBars")) { |
a685723c DV |
2115 | for (var j = 0; j < colIdx.length; j++) { |
2116 | var col = colIdx[j]; | |
2117 | row.push(data.getValue(i, col)); | |
2118 | if (hasAnnotations && | |
2119 | annotationCols.hasOwnProperty(col) && | |
2120 | data.getValue(i, annotationCols[col][0]) != null) { | |
2121 | var ann = {}; | |
2122 | ann.series = data.getColumnLabel(col); | |
2123 | ann.xval = row[0]; | |
2124 | ann.shortText = String.fromCharCode(65 /* A */ + annotations.length) | |
2125 | ann.text = ''; | |
2126 | for (var k = 0; k < annotationCols[col].length; k++) { | |
2127 | if (k) ann.text += "\n"; | |
2128 | ann.text += data.getValue(i, annotationCols[col][k]); | |
2129 | } | |
2130 | annotations.push(ann); | |
2131 | } | |
3e3f84e4 DV |
2132 | } |
2133 | } else { | |
2134 | for (var j = 0; j < cols - 1; j++) { | |
2135 | row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]); | |
2136 | } | |
79420a1e | 2137 | } |
987840a2 DV |
2138 | if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) { |
2139 | outOfOrder = true; | |
2140 | } | |
243d96e8 | 2141 | ret.push(row); |
79420a1e | 2142 | } |
987840a2 DV |
2143 | |
2144 | if (outOfOrder) { | |
2145 | this.warn("DataTable is out of order; order it correctly to speed loading."); | |
2146 | ret.sort(function(a,b) { return a[0] - b[0] }); | |
2147 | } | |
a685723c DV |
2148 | this.rawData_ = ret; |
2149 | ||
2150 | if (annotations.length > 0) { | |
2151 | this.setAnnotations(annotations, true); | |
2152 | } | |
79420a1e DV |
2153 | } |
2154 | ||
24e5350c | 2155 | // These functions are all based on MochiKit. |
fc80a396 DV |
2156 | Dygraph.update = function (self, o) { |
2157 | if (typeof(o) != 'undefined' && o !== null) { | |
2158 | for (var k in o) { | |
85b99f0b DV |
2159 | if (o.hasOwnProperty(k)) { |
2160 | self[k] = o[k]; | |
2161 | } | |
fc80a396 DV |
2162 | } |
2163 | } | |
2164 | return self; | |
2165 | }; | |
2166 | ||
2dda3850 DV |
2167 | Dygraph.isArrayLike = function (o) { |
2168 | var typ = typeof(o); | |
2169 | if ( | |
c21d2c2d | 2170 | (typ != 'object' && !(typ == 'function' && |
2dda3850 DV |
2171 | typeof(o.item) == 'function')) || |
2172 | o === null || | |
2173 | typeof(o.length) != 'number' || | |
2174 | o.nodeType === 3 | |
2175 | ) { | |
2176 | return false; | |
2177 | } | |
2178 | return true; | |
2179 | }; | |
2180 | ||
2181 | Dygraph.isDateLike = function (o) { | |
2182 | if (typeof(o) != "object" || o === null || | |
2183 | typeof(o.getTime) != 'function') { | |
2184 | return false; | |
2185 | } | |
2186 | return true; | |
2187 | }; | |
2188 | ||
e3ab7b40 DV |
2189 | Dygraph.clone = function(o) { |
2190 | // TODO(danvk): figure out how MochiKit's version works | |
2191 | var r = []; | |
2192 | for (var i = 0; i < o.length; i++) { | |
2193 | if (Dygraph.isArrayLike(o[i])) { | |
2194 | r.push(Dygraph.clone(o[i])); | |
2195 | } else { | |
2196 | r.push(o[i]); | |
2197 | } | |
2198 | } | |
2199 | return r; | |
24e5350c DV |
2200 | }; |
2201 | ||
2dda3850 | 2202 | |
79420a1e | 2203 | /** |
6a1aa64f DV |
2204 | * Get the CSV data. If it's in a function, call that function. If it's in a |
2205 | * file, do an XMLHttpRequest to get it. | |
2206 | * @private | |
2207 | */ | |
285a6bda | 2208 | Dygraph.prototype.start_ = function() { |
6a1aa64f | 2209 | if (typeof this.file_ == 'function') { |
285a6bda | 2210 | // CSV string. Pretend we got it via XHR. |
6a1aa64f | 2211 | this.loadedEvent_(this.file_()); |
2dda3850 | 2212 | } else if (Dygraph.isArrayLike(this.file_)) { |
285a6bda DV |
2213 | this.rawData_ = this.parseArray_(this.file_); |
2214 | this.drawGraph_(this.rawData_); | |
79420a1e DV |
2215 | } else if (typeof this.file_ == 'object' && |
2216 | typeof this.file_.getColumnRange == 'function') { | |
2217 | // must be a DataTable from gviz. | |
a685723c | 2218 | this.parseDataTable_(this.file_); |
79420a1e | 2219 | this.drawGraph_(this.rawData_); |
285a6bda DV |
2220 | } else if (typeof this.file_ == 'string') { |
2221 | // Heuristic: a newline means it's CSV data. Otherwise it's an URL. | |
2222 | if (this.file_.indexOf('\n') >= 0) { | |
2223 | this.loadedEvent_(this.file_); | |
2224 | } else { | |
2225 | var req = new XMLHttpRequest(); | |
2226 | var caller = this; | |
2227 | req.onreadystatechange = function () { | |
2228 | if (req.readyState == 4) { | |
2229 | if (req.status == 200) { | |
2230 | caller.loadedEvent_(req.responseText); | |
2231 | } | |
6a1aa64f | 2232 | } |
285a6bda | 2233 | }; |
6a1aa64f | 2234 | |
285a6bda DV |
2235 | req.open("GET", this.file_, true); |
2236 | req.send(null); | |
2237 | } | |
2238 | } else { | |
2239 | this.error("Unknown data format: " + (typeof this.file_)); | |
6a1aa64f DV |
2240 | } |
2241 | }; | |
2242 | ||
2243 | /** | |
2244 | * Changes various properties of the graph. These can include: | |
2245 | * <ul> | |
2246 | * <li>file: changes the source data for the graph</li> | |
2247 | * <li>errorBars: changes whether the data contains stddev</li> | |
2248 | * </ul> | |
2249 | * @param {Object} attrs The new properties and values | |
2250 | */ | |
285a6bda DV |
2251 | Dygraph.prototype.updateOptions = function(attrs) { |
2252 | // TODO(danvk): this is a mess. Rethink this function. | |
6a1aa64f DV |
2253 | if (attrs.rollPeriod) { |
2254 | this.rollPeriod_ = attrs.rollPeriod; | |
2255 | } | |
2256 | if (attrs.dateWindow) { | |
2257 | this.dateWindow_ = attrs.dateWindow; | |
2258 | } | |
2259 | if (attrs.valueRange) { | |
2260 | this.valueRange_ = attrs.valueRange; | |
2261 | } | |
fc80a396 | 2262 | Dygraph.update(this.user_attrs_, attrs); |
87bb7958 | 2263 | Dygraph.update(this.renderOptions_, attrs); |
285a6bda DV |
2264 | |
2265 | this.labelsFromCSV_ = (this.attr_("labels") == null); | |
2266 | ||
2267 | // TODO(danvk): this doesn't match the constructor logic | |
2268 | this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") }); | |
5e50289f | 2269 | if (attrs['file']) { |
6a1aa64f DV |
2270 | this.file_ = attrs['file']; |
2271 | this.start_(); | |
2272 | } else { | |
2273 | this.drawGraph_(this.rawData_); | |
2274 | } | |
2275 | }; | |
2276 | ||
2277 | /** | |
697e70b2 DV |
2278 | * Resizes the dygraph. If no parameters are specified, resizes to fill the |
2279 | * containing div (which has presumably changed size since the dygraph was | |
2280 | * instantiated. If the width/height are specified, the div will be resized. | |
964f30c6 DV |
2281 | * |
2282 | * This is far more efficient than destroying and re-instantiating a | |
2283 | * Dygraph, since it doesn't have to reparse the underlying data. | |
2284 | * | |
697e70b2 DV |
2285 | * @param {Number} width Width (in pixels) |
2286 | * @param {Number} height Height (in pixels) | |
2287 | */ | |
2288 | Dygraph.prototype.resize = function(width, height) { | |
e8c7ef86 DV |
2289 | if (this.resize_lock) { |
2290 | return; | |
2291 | } | |
2292 | this.resize_lock = true; | |
2293 | ||
697e70b2 DV |
2294 | if ((width === null) != (height === null)) { |
2295 | this.warn("Dygraph.resize() should be called with zero parameters or " + | |
2296 | "two non-NULL parameters. Pretending it was zero."); | |
2297 | width = height = null; | |
2298 | } | |
2299 | ||
b16e6369 | 2300 | // TODO(danvk): there should be a clear() method. |
697e70b2 | 2301 | this.maindiv_.innerHTML = ""; |
b16e6369 DV |
2302 | this.attrs_.labelsDiv = null; |
2303 | ||
697e70b2 DV |
2304 | if (width) { |
2305 | this.maindiv_.style.width = width + "px"; | |
2306 | this.maindiv_.style.height = height + "px"; | |
2307 | this.width_ = width; | |
2308 | this.height_ = height; | |
2309 | } else { | |
2310 | this.width_ = this.maindiv_.offsetWidth; | |
2311 | this.height_ = this.maindiv_.offsetHeight; | |
2312 | } | |
2313 | ||
2314 | this.createInterface_(); | |
964f30c6 | 2315 | this.drawGraph_(this.rawData_); |
e8c7ef86 DV |
2316 | |
2317 | this.resize_lock = false; | |
697e70b2 DV |
2318 | }; |
2319 | ||
2320 | /** | |
6a1aa64f DV |
2321 | * Adjusts the number of days in the rolling average. Updates the graph to |
2322 | * reflect the new averaging period. | |
2323 | * @param {Number} length Number of days over which to average the data. | |
2324 | */ | |
285a6bda | 2325 | Dygraph.prototype.adjustRoll = function(length) { |
6a1aa64f DV |
2326 | this.rollPeriod_ = length; |
2327 | this.drawGraph_(this.rawData_); | |
2328 | }; | |
540d00f1 | 2329 | |
f8cfec73 | 2330 | /** |
1cf11047 DV |
2331 | * Returns a boolean array of visibility statuses. |
2332 | */ | |
2333 | Dygraph.prototype.visibility = function() { | |
2334 | // Do lazy-initialization, so that this happens after we know the number of | |
2335 | // data series. | |
2336 | if (!this.attr_("visibility")) { | |
f38dec01 | 2337 | this.attrs_["visibility"] = []; |
1cf11047 DV |
2338 | } |
2339 | while (this.attr_("visibility").length < this.rawData_[0].length - 1) { | |
f38dec01 | 2340 | this.attr_("visibility").push(true); |
1cf11047 DV |
2341 | } |
2342 | return this.attr_("visibility"); | |
2343 | }; | |
2344 | ||
2345 | /** | |
2346 | * Changes the visiblity of a series. | |
2347 | */ | |
2348 | Dygraph.prototype.setVisibility = function(num, value) { | |
2349 | var x = this.visibility(); | |
2350 | if (num < 0 && num >= x.length) { | |
2351 | this.warn("invalid series number in setVisibility: " + num); | |
2352 | } else { | |
2353 | x[num] = value; | |
2354 | this.drawGraph_(this.rawData_); | |
2355 | } | |
2356 | }; | |
2357 | ||
2358 | /** | |
5c528fa2 DV |
2359 | * Update the list of annotations and redraw the chart. |
2360 | */ | |
a685723c | 2361 | Dygraph.prototype.setAnnotations = function(ann, suppressDraw) { |
5c528fa2 DV |
2362 | this.annotations_ = ann; |
2363 | this.layout_.setAnnotations(this.annotations_); | |
a685723c DV |
2364 | if (!suppressDraw) { |
2365 | this.drawGraph_(this.rawData_); | |
2366 | } | |
5c528fa2 DV |
2367 | }; |
2368 | ||
2369 | /** | |
2370 | * Return the list of annotations. | |
2371 | */ | |
2372 | Dygraph.prototype.annotations = function() { | |
2373 | return this.annotations_; | |
2374 | }; | |
2375 | ||
2376 | Dygraph.addAnnotationRule = function() { | |
2377 | if (Dygraph.addedAnnotationCSS) return; | |
2378 | ||
18a016b1 DV |
2379 | var mysheet; |
2380 | if (document.styleSheets.length > 0) { | |
2381 | mysheet = document.styleSheets[0]; | |
2382 | } else { | |
2383 | var styleSheetElement = document.createElement("style"); | |
2384 | styleSheetElement.type = "text/css"; | |
2385 | document.getElementsByTagName("head")[0].appendChild(styleSheetElement); | |
2386 | for(i = 0; i < document.styleSheets.length; i++) { | |
2387 | if (document.styleSheets[i].disabled) continue; | |
2388 | mysheet = document.styleSheets[i]; | |
2389 | } | |
2390 | } | |
2391 | ||
5c528fa2 DV |
2392 | var rule = "border: 1px solid black; " + |
2393 | "background-color: white; " + | |
2394 | "text-align: center;"; | |
2395 | if (mysheet.insertRule) { // Firefox | |
b39466eb | 2396 | mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", 0); |
5c528fa2 DV |
2397 | } else if (mysheet.addRule) { // IE |
2398 | mysheet.addRule(".dygraphDefaultAnnotation", rule); | |
2399 | } | |
2400 | ||
2401 | Dygraph.addedAnnotationCSS = true; | |
2402 | } | |
2403 | ||
2404 | /** | |
f8cfec73 DV |
2405 | * Create a new canvas element. This is more complex than a simple |
2406 | * document.createElement("canvas") because of IE and excanvas. | |
2407 | */ | |
2408 | Dygraph.createCanvas = function() { | |
2409 | var canvas = document.createElement("canvas"); | |
2410 | ||
2411 | isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); | |
2412 | if (isIE) { | |
2413 | canvas = G_vmlCanvasManager.initElement(canvas); | |
2414 | } | |
2415 | ||
2416 | return canvas; | |
2417 | }; | |
2418 | ||
540d00f1 DV |
2419 | |
2420 | /** | |
285a6bda | 2421 | * A wrapper around Dygraph that implements the gviz API. |
540d00f1 DV |
2422 | * @param {Object} container The DOM object the visualization should live in. |
2423 | */ | |
285a6bda | 2424 | Dygraph.GVizChart = function(container) { |
540d00f1 DV |
2425 | this.container = container; |
2426 | } | |
2427 | ||
285a6bda | 2428 | Dygraph.GVizChart.prototype.draw = function(data, options) { |
540d00f1 | 2429 | this.container.innerHTML = ''; |
285a6bda | 2430 | this.date_graph = new Dygraph(this.container, data, options); |
540d00f1 | 2431 | } |
285a6bda | 2432 | |
239c712d NAG |
2433 | /** |
2434 | * Google charts compatible setSelection | |
50360fd0 | 2435 | * Only row selection is supported, all points in the row will be highlighted |
239c712d NAG |
2436 | * @param {Array} array of the selected cells |
2437 | * @public | |
2438 | */ | |
2439 | Dygraph.GVizChart.prototype.setSelection = function(selection_array) { | |
2440 | var row = false; | |
2441 | if (selection_array.length) { | |
2442 | row = selection_array[0].row; | |
2443 | } | |
2444 | this.date_graph.setSelection(row); | |
2445 | } | |
2446 | ||
103b7292 NAG |
2447 | /** |
2448 | * Google charts compatible getSelection implementation | |
2449 | * @return {Array} array of the selected cells | |
2450 | * @public | |
2451 | */ | |
2452 | Dygraph.GVizChart.prototype.getSelection = function() { | |
2453 | var selection = []; | |
50360fd0 | 2454 | |
103b7292 | 2455 | var row = this.date_graph.getSelection(); |
50360fd0 | 2456 | |
103b7292 | 2457 | if (row < 0) return selection; |
50360fd0 | 2458 | |
103b7292 NAG |
2459 | col = 1; |
2460 | for (var i in this.date_graph.layout_.datasets) { | |
2461 | selection.push({row: row, column: col}); | |
2462 | col++; | |
2463 | } | |
2464 | ||
2465 | return selection; | |
2466 | } | |
2467 | ||
285a6bda DV |
2468 | // Older pages may still use this name. |
2469 | DateGraph = Dygraph; |