| 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 |
| 6 | * string. Dygraph can handle multiple series with or without error bars. The |
| 7 | * date/value ranges will be automatically set. Dygraph uses the |
| 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"> |
| 14 | new Dygraph(document.getElementById("graphdiv"), |
| 15 | "datafile.csv", // CSV file with headers |
| 16 | { }); // options |
| 17 | </script> |
| 18 | |
| 19 | The CSV file is of the form |
| 20 | |
| 21 | Date,SeriesA,SeriesB,SeriesC |
| 22 | YYYYMMDD,A1,B1,C1 |
| 23 | YYYYMMDD,A2,B2,C2 |
| 24 | |
| 25 | If the 'errorBars' option is set in the constructor, the input should be of |
| 26 | the form |
| 27 | |
| 28 | Date,SeriesA,SeriesB,... |
| 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 | |
| 34 | Date,SeriesA,SeriesB,... |
| 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 | |
| 40 | For further documentation and examples, see http://dygraphs.com/ |
| 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,... |
| 50 | * @param {Object} attrs Various other attributes, e.g. errorBars determines |
| 51 | * whether the input data contains error ranges. |
| 52 | */ |
| 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 | } |
| 65 | }; |
| 66 | |
| 67 | Dygraph.NAME = "Dygraph"; |
| 68 | Dygraph.VERSION = "1.2"; |
| 69 | Dygraph.__repr__ = function() { |
| 70 | return "[" + this.NAME + " " + this.VERSION + "]"; |
| 71 | }; |
| 72 | Dygraph.toString = function() { |
| 73 | return this.__repr__(); |
| 74 | }; |
| 75 | |
| 76 | /** |
| 77 | * Formatting to use for an integer number. |
| 78 | * |
| 79 | * @param {Number} x The number to format |
| 80 | * @param {Number} unused_precision The precision to use, ignored. |
| 81 | * @return {String} A string formatted like %g in printf. The max generated |
| 82 | * string length should be precision + 6 (e.g 1.123e+300). |
| 83 | */ |
| 84 | Dygraph.intFormat = function(x, unused_precision) { |
| 85 | return x.toString(); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Number formatting function which mimicks the behavior of %g in printf, i.e. |
| 90 | * either exponential or fixed format (without trailing 0s) is used depending on |
| 91 | * the length of the generated string. The advantage of this format is that |
| 92 | * there is a predictable upper bound on the resulting string length, |
| 93 | * significant figures are not dropped, and normal numbers are not displayed in |
| 94 | * exponential notation. |
| 95 | * |
| 96 | * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g. |
| 97 | * It creates strings which are too long for absolute values between 10^-4 and |
| 98 | * 10^-6. See tests/number-format.html for output examples. |
| 99 | * |
| 100 | * @param {Number} x The number to format |
| 101 | * @param {Number} opt_precision The precision to use, default 2. |
| 102 | * @return {String} A string formatted like %g in printf. The max generated |
| 103 | * string length should be precision + 6 (e.g 1.123e+300). |
| 104 | */ |
| 105 | Dygraph.floatFormat = function(x, opt_precision) { |
| 106 | // Avoid invalid precision values; [1, 21] is the valid range. |
| 107 | var p = Math.min(Math.max(1, opt_precision || 2), 21); |
| 108 | |
| 109 | // This is deceptively simple. The actual algorithm comes from: |
| 110 | // |
| 111 | // Max allowed length = p + 4 |
| 112 | // where 4 comes from 'e+n' and '.'. |
| 113 | // |
| 114 | // Length of fixed format = 2 + y + p |
| 115 | // where 2 comes from '0.' and y = # of leading zeroes. |
| 116 | // |
| 117 | // Equating the two and solving for y yields y = 2, or 0.00xxxx which is |
| 118 | // 1.0e-3. |
| 119 | // |
| 120 | // Since the behavior of toPrecision() is identical for larger numbers, we |
| 121 | // don't have to worry about the other bound. |
| 122 | // |
| 123 | // Finally, the argument for toExponential() is the number of trailing digits, |
| 124 | // so we take off 1 for the value before the '.'. |
| 125 | return (Math.abs(x) < 1.0e-3 && x != 0.0) ? |
| 126 | x.toExponential(p - 1) : x.toPrecision(p); |
| 127 | }; |
| 128 | |
| 129 | // Various default values |
| 130 | Dygraph.DEFAULT_ROLL_PERIOD = 1; |
| 131 | Dygraph.DEFAULT_WIDTH = 480; |
| 132 | Dygraph.DEFAULT_HEIGHT = 320; |
| 133 | Dygraph.AXIS_LINE_WIDTH = 0.3; |
| 134 | |
| 135 | |
| 136 | // Default attribute values. |
| 137 | Dygraph.DEFAULT_ATTRS = { |
| 138 | highlightCircleSize: 3, |
| 139 | pixelsPerXLabel: 60, |
| 140 | pixelsPerYLabel: 30, |
| 141 | |
| 142 | labelsDivWidth: 250, |
| 143 | labelsDivStyles: { |
| 144 | // TODO(danvk): move defaults from createStatusMessage_ here. |
| 145 | }, |
| 146 | labelsSeparateLines: false, |
| 147 | labelsShowZeroValues: true, |
| 148 | labelsKMB: false, |
| 149 | labelsKMG2: false, |
| 150 | showLabelsOnHighlight: true, |
| 151 | |
| 152 | yValueFormatter: function(x, opt_precision) { |
| 153 | var s = Dygraph.floatFormat(x, opt_precision); |
| 154 | var s2 = Dygraph.intFormat(x); |
| 155 | return s.length <= s2.length ? s : s2; |
| 156 | }, |
| 157 | |
| 158 | strokeWidth: 1.0, |
| 159 | |
| 160 | axisTickSize: 3, |
| 161 | axisLabelFontSize: 14, |
| 162 | xAxisLabelWidth: 50, |
| 163 | yAxisLabelWidth: 50, |
| 164 | xAxisLabelFormatter: Dygraph.dateAxisFormatter, |
| 165 | rightGap: 5, |
| 166 | |
| 167 | showRoller: false, |
| 168 | xValueFormatter: Dygraph.dateString_, |
| 169 | xValueParser: Dygraph.dateParser, |
| 170 | xTicker: Dygraph.dateTicker, |
| 171 | |
| 172 | delimiter: ',', |
| 173 | |
| 174 | logScale: false, |
| 175 | sigma: 2.0, |
| 176 | errorBars: false, |
| 177 | fractions: false, |
| 178 | wilsonInterval: true, // only relevant if fractions is true |
| 179 | customBars: false, |
| 180 | fillGraph: false, |
| 181 | fillAlpha: 0.15, |
| 182 | connectSeparatedPoints: false, |
| 183 | |
| 184 | stackedGraph: false, |
| 185 | hideOverlayOnMouseOut: true, |
| 186 | |
| 187 | stepPlot: false, |
| 188 | avoidMinZero: false, |
| 189 | |
| 190 | interactionModel: null // will be set to Dygraph.defaultInteractionModel. |
| 191 | }; |
| 192 | |
| 193 | // Various logging levels. |
| 194 | Dygraph.DEBUG = 1; |
| 195 | Dygraph.INFO = 2; |
| 196 | Dygraph.WARNING = 3; |
| 197 | Dygraph.ERROR = 3; |
| 198 | |
| 199 | // Directions for panning and zooming. Use bit operations when combined |
| 200 | // values are possible. |
| 201 | Dygraph.HORIZONTAL = 1; |
| 202 | Dygraph.VERTICAL = 2; |
| 203 | |
| 204 | // Used for initializing annotation CSS rules only once. |
| 205 | Dygraph.addedAnnotationCSS = false; |
| 206 | |
| 207 | Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) { |
| 208 | // Labels is no longer a constructor parameter, since it's typically set |
| 209 | // directly from the data source. It also conains a name for the x-axis, |
| 210 | // which the previous constructor form did not. |
| 211 | if (labels != null) { |
| 212 | var new_labels = ["Date"]; |
| 213 | for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]); |
| 214 | Dygraph.update(attrs, { 'labels': new_labels }); |
| 215 | } |
| 216 | this.__init__(div, file, attrs); |
| 217 | }; |
| 218 | |
| 219 | /** |
| 220 | * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit |
| 221 | * and context <canvas> inside of it. See the constructor for details |
| 222 | * on the parameters. |
| 223 | * @param {Element} div the Element to render the graph into. |
| 224 | * @param {String | Function} file Source data |
| 225 | * @param {Object} attrs Miscellaneous other options |
| 226 | * @private |
| 227 | */ |
| 228 | Dygraph.prototype.__init__ = function(div, file, attrs) { |
| 229 | // Hack for IE: if we're using excanvas and the document hasn't finished |
| 230 | // loading yet (and hence may not have initialized whatever it needs to |
| 231 | // initialize), then keep calling this routine periodically until it has. |
| 232 | if (/MSIE/.test(navigator.userAgent) && !window.opera && |
| 233 | typeof(G_vmlCanvasManager) != 'undefined' && |
| 234 | document.readyState != 'complete') { |
| 235 | var self = this; |
| 236 | setTimeout(function() { self.__init__(div, file, attrs) }, 100); |
| 237 | } |
| 238 | |
| 239 | // Support two-argument constructor |
| 240 | if (attrs == null) { attrs = {}; } |
| 241 | |
| 242 | // Copy the important bits into the object |
| 243 | // TODO(danvk): most of these should just stay in the attrs_ dictionary. |
| 244 | this.maindiv_ = div; |
| 245 | this.file_ = file; |
| 246 | this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD; |
| 247 | this.previousVerticalX_ = -1; |
| 248 | this.fractions_ = attrs.fractions || false; |
| 249 | this.dateWindow_ = attrs.dateWindow || null; |
| 250 | |
| 251 | this.wilsonInterval_ = attrs.wilsonInterval || true; |
| 252 | this.is_initial_draw_ = true; |
| 253 | this.annotations_ = []; |
| 254 | |
| 255 | // Number of digits to use when labeling the x (if numeric) and y axis |
| 256 | // ticks. |
| 257 | this.numXDigits_ = 2; |
| 258 | this.numYDigits_ = 2; |
| 259 | |
| 260 | // When labeling x (if numeric) or y values in the legend, there are |
| 261 | // numDigits + numExtraDigits of precision used. For axes labels with N |
| 262 | // digits of precision, the data should be displayed with at least N+1 digits |
| 263 | // of precision. The reason for this is to divide each interval between |
| 264 | // successive ticks into tenths (for 1) or hundredths (for 2), etc. For |
| 265 | // example, if the labels are [0, 1, 2], we want data to be displayed as |
| 266 | // 0.1, 1.3, etc. |
| 267 | this.numExtraDigits_ = 1; |
| 268 | |
| 269 | // Clear the div. This ensure that, if multiple dygraphs are passed the same |
| 270 | // div, then only one will be drawn. |
| 271 | div.innerHTML = ""; |
| 272 | |
| 273 | // If the div isn't already sized then inherit from our attrs or |
| 274 | // give it a default size. |
| 275 | if (div.style.width == '') { |
| 276 | div.style.width = (attrs.width || Dygraph.DEFAULT_WIDTH) + "px"; |
| 277 | } |
| 278 | if (div.style.height == '') { |
| 279 | div.style.height = (attrs.height || Dygraph.DEFAULT_HEIGHT) + "px"; |
| 280 | } |
| 281 | this.width_ = parseInt(div.style.width, 10); |
| 282 | this.height_ = parseInt(div.style.height, 10); |
| 283 | // The div might have been specified as percent of the current window size, |
| 284 | // convert that to an appropriate number of pixels. |
| 285 | if (div.style.width.indexOf("%") == div.style.width.length - 1) { |
| 286 | this.width_ = div.offsetWidth; |
| 287 | } |
| 288 | if (div.style.height.indexOf("%") == div.style.height.length - 1) { |
| 289 | this.height_ = div.offsetHeight; |
| 290 | } |
| 291 | |
| 292 | if (this.width_ == 0) { |
| 293 | this.error("dygraph has zero width. Please specify a width in pixels."); |
| 294 | } |
| 295 | if (this.height_ == 0) { |
| 296 | this.error("dygraph has zero height. Please specify a height in pixels."); |
| 297 | } |
| 298 | |
| 299 | // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_. |
| 300 | if (attrs['stackedGraph']) { |
| 301 | attrs['fillGraph'] = true; |
| 302 | // TODO(nikhilk): Add any other stackedGraph checks here. |
| 303 | } |
| 304 | |
| 305 | // Dygraphs has many options, some of which interact with one another. |
| 306 | // To keep track of everything, we maintain two sets of options: |
| 307 | // |
| 308 | // this.user_attrs_ only options explicitly set by the user. |
| 309 | // this.attrs_ defaults, options derived from user_attrs_, data. |
| 310 | // |
| 311 | // Options are then accessed this.attr_('attr'), which first looks at |
| 312 | // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent |
| 313 | // defaults without overriding behavior that the user specifically asks for. |
| 314 | this.user_attrs_ = {}; |
| 315 | Dygraph.update(this.user_attrs_, attrs); |
| 316 | |
| 317 | this.attrs_ = {}; |
| 318 | Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS); |
| 319 | |
| 320 | this.boundaryIds_ = []; |
| 321 | |
| 322 | // Make a note of whether labels will be pulled from the CSV file. |
| 323 | this.labelsFromCSV_ = (this.attr_("labels") == null); |
| 324 | |
| 325 | // Create the containing DIV and other interactive elements |
| 326 | this.createInterface_(); |
| 327 | |
| 328 | this.start_(); |
| 329 | }; |
| 330 | |
| 331 | Dygraph.prototype.attr_ = function(name, seriesName) { |
| 332 | if (seriesName && |
| 333 | typeof(this.user_attrs_[seriesName]) != 'undefined' && |
| 334 | this.user_attrs_[seriesName] != null && |
| 335 | typeof(this.user_attrs_[seriesName][name]) != 'undefined') { |
| 336 | return this.user_attrs_[seriesName][name]; |
| 337 | } else if (typeof(this.user_attrs_[name]) != 'undefined') { |
| 338 | return this.user_attrs_[name]; |
| 339 | } else if (typeof(this.attrs_[name]) != 'undefined') { |
| 340 | return this.attrs_[name]; |
| 341 | } else { |
| 342 | return null; |
| 343 | } |
| 344 | }; |
| 345 | |
| 346 | // TODO(danvk): any way I can get the line numbers to be this.warn call? |
| 347 | Dygraph.prototype.log = function(severity, message) { |
| 348 | if (typeof(console) != 'undefined') { |
| 349 | switch (severity) { |
| 350 | case Dygraph.DEBUG: |
| 351 | console.debug('dygraphs: ' + message); |
| 352 | break; |
| 353 | case Dygraph.INFO: |
| 354 | console.info('dygraphs: ' + message); |
| 355 | break; |
| 356 | case Dygraph.WARNING: |
| 357 | console.warn('dygraphs: ' + message); |
| 358 | break; |
| 359 | case Dygraph.ERROR: |
| 360 | console.error('dygraphs: ' + message); |
| 361 | break; |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | Dygraph.prototype.info = function(message) { |
| 366 | this.log(Dygraph.INFO, message); |
| 367 | } |
| 368 | Dygraph.prototype.warn = function(message) { |
| 369 | this.log(Dygraph.WARNING, message); |
| 370 | } |
| 371 | Dygraph.prototype.error = function(message) { |
| 372 | this.log(Dygraph.ERROR, message); |
| 373 | } |
| 374 | |
| 375 | /** |
| 376 | * Returns the current rolling period, as set by the user or an option. |
| 377 | * @return {Number} The number of points in the rolling window |
| 378 | */ |
| 379 | Dygraph.prototype.rollPeriod = function() { |
| 380 | return this.rollPeriod_; |
| 381 | }; |
| 382 | |
| 383 | /** |
| 384 | * Returns the currently-visible x-range. This can be affected by zooming, |
| 385 | * panning or a call to updateOptions. |
| 386 | * Returns a two-element array: [left, right]. |
| 387 | * If the Dygraph has dates on the x-axis, these will be millis since epoch. |
| 388 | */ |
| 389 | Dygraph.prototype.xAxisRange = function() { |
| 390 | if (this.dateWindow_) return this.dateWindow_; |
| 391 | |
| 392 | // The entire chart is visible. |
| 393 | var left = this.rawData_[0][0]; |
| 394 | var right = this.rawData_[this.rawData_.length - 1][0]; |
| 395 | return [left, right]; |
| 396 | }; |
| 397 | |
| 398 | /** |
| 399 | * Returns the currently-visible y-range for an axis. This can be affected by |
| 400 | * zooming, panning or a call to updateOptions. Axis indices are zero-based. If |
| 401 | * called with no arguments, returns the range of the first axis. |
| 402 | * Returns a two-element array: [bottom, top]. |
| 403 | */ |
| 404 | Dygraph.prototype.yAxisRange = function(idx) { |
| 405 | if (typeof(idx) == "undefined") idx = 0; |
| 406 | if (idx < 0 || idx >= this.axes_.length) return null; |
| 407 | return [ this.axes_[idx].computedValueRange[0], |
| 408 | this.axes_[idx].computedValueRange[1] ]; |
| 409 | }; |
| 410 | |
| 411 | /** |
| 412 | * Returns the currently-visible y-ranges for each axis. This can be affected by |
| 413 | * zooming, panning, calls to updateOptions, etc. |
| 414 | * Returns an array of [bottom, top] pairs, one for each y-axis. |
| 415 | */ |
| 416 | Dygraph.prototype.yAxisRanges = function() { |
| 417 | var ret = []; |
| 418 | for (var i = 0; i < this.axes_.length; i++) { |
| 419 | ret.push(this.yAxisRange(i)); |
| 420 | } |
| 421 | return ret; |
| 422 | }; |
| 423 | |
| 424 | // TODO(danvk): use these functions throughout dygraphs. |
| 425 | /** |
| 426 | * Convert from data coordinates to canvas/div X/Y coordinates. |
| 427 | * If specified, do this conversion for the coordinate system of a particular |
| 428 | * axis. Uses the first axis by default. |
| 429 | * Returns a two-element array: [X, Y] |
| 430 | */ |
| 431 | Dygraph.prototype.toDomCoords = function(x, y, axis) { |
| 432 | var ret = [null, null]; |
| 433 | var area = this.plotter_.area; |
| 434 | if (x !== null) { |
| 435 | var xRange = this.xAxisRange(); |
| 436 | ret[0] = area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w; |
| 437 | } |
| 438 | |
| 439 | if (y !== null) { |
| 440 | var yRange = this.yAxisRange(axis); |
| 441 | ret[1] = area.y + (yRange[1] - y) / (yRange[1] - yRange[0]) * area.h; |
| 442 | } |
| 443 | |
| 444 | return ret; |
| 445 | }; |
| 446 | |
| 447 | /** |
| 448 | * Convert from canvas/div coords to data coordinates. |
| 449 | * If specified, do this conversion for the coordinate system of a particular |
| 450 | * axis. Uses the first axis by default. |
| 451 | * Returns a two-element array: [X, Y] |
| 452 | */ |
| 453 | Dygraph.prototype.toDataCoords = function(x, y, axis) { |
| 454 | var ret = [null, null]; |
| 455 | var area = this.plotter_.area; |
| 456 | if (x !== null) { |
| 457 | var xRange = this.xAxisRange(); |
| 458 | ret[0] = xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]); |
| 459 | } |
| 460 | |
| 461 | if (y !== null) { |
| 462 | var yRange = this.yAxisRange(axis); |
| 463 | ret[1] = yRange[0] + (area.h - y) / area.h * (yRange[1] - yRange[0]); |
| 464 | } |
| 465 | |
| 466 | return ret; |
| 467 | }; |
| 468 | |
| 469 | /** |
| 470 | * Returns the number of columns (including the independent variable). |
| 471 | */ |
| 472 | Dygraph.prototype.numColumns = function() { |
| 473 | return this.rawData_[0].length; |
| 474 | }; |
| 475 | |
| 476 | /** |
| 477 | * Returns the number of rows (excluding any header/label row). |
| 478 | */ |
| 479 | Dygraph.prototype.numRows = function() { |
| 480 | return this.rawData_.length; |
| 481 | }; |
| 482 | |
| 483 | /** |
| 484 | * Returns the value in the given row and column. If the row and column exceed |
| 485 | * the bounds on the data, returns null. Also returns null if the value is |
| 486 | * missing. |
| 487 | */ |
| 488 | Dygraph.prototype.getValue = function(row, col) { |
| 489 | if (row < 0 || row > this.rawData_.length) return null; |
| 490 | if (col < 0 || col > this.rawData_[row].length) return null; |
| 491 | |
| 492 | return this.rawData_[row][col]; |
| 493 | }; |
| 494 | |
| 495 | Dygraph.addEvent = function(el, evt, fn) { |
| 496 | var normed_fn = function(e) { |
| 497 | if (!e) var e = window.event; |
| 498 | fn(e); |
| 499 | }; |
| 500 | if (window.addEventListener) { // Mozilla, Netscape, Firefox |
| 501 | el.addEventListener(evt, normed_fn, false); |
| 502 | } else { // IE |
| 503 | el.attachEvent('on' + evt, normed_fn); |
| 504 | } |
| 505 | }; |
| 506 | |
| 507 | |
| 508 | // Based on the article at |
| 509 | // http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel |
| 510 | Dygraph.cancelEvent = function(e) { |
| 511 | e = e ? e : window.event; |
| 512 | if (e.stopPropagation) { |
| 513 | e.stopPropagation(); |
| 514 | } |
| 515 | if (e.preventDefault) { |
| 516 | e.preventDefault(); |
| 517 | } |
| 518 | e.cancelBubble = true; |
| 519 | e.cancel = true; |
| 520 | e.returnValue = false; |
| 521 | return false; |
| 522 | } |
| 523 | |
| 524 | |
| 525 | /** |
| 526 | * Generates interface elements for the Dygraph: a containing div, a div to |
| 527 | * display the current point, and a textbox to adjust the rolling average |
| 528 | * period. Also creates the Renderer/Layout elements. |
| 529 | * @private |
| 530 | */ |
| 531 | Dygraph.prototype.createInterface_ = function() { |
| 532 | // Create the all-enclosing graph div |
| 533 | var enclosing = this.maindiv_; |
| 534 | |
| 535 | this.graphDiv = document.createElement("div"); |
| 536 | this.graphDiv.style.width = this.width_ + "px"; |
| 537 | this.graphDiv.style.height = this.height_ + "px"; |
| 538 | enclosing.appendChild(this.graphDiv); |
| 539 | |
| 540 | // Create the canvas for interactive parts of the chart. |
| 541 | this.canvas_ = Dygraph.createCanvas(); |
| 542 | this.canvas_.style.position = "absolute"; |
| 543 | this.canvas_.width = this.width_; |
| 544 | this.canvas_.height = this.height_; |
| 545 | this.canvas_.style.width = this.width_ + "px"; // for IE |
| 546 | this.canvas_.style.height = this.height_ + "px"; // for IE |
| 547 | |
| 548 | // ... and for static parts of the chart. |
| 549 | this.hidden_ = this.createPlotKitCanvas_(this.canvas_); |
| 550 | |
| 551 | // The interactive parts of the graph are drawn on top of the chart. |
| 552 | this.graphDiv.appendChild(this.hidden_); |
| 553 | this.graphDiv.appendChild(this.canvas_); |
| 554 | this.mouseEventElement_ = this.canvas_; |
| 555 | |
| 556 | var dygraph = this; |
| 557 | Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) { |
| 558 | dygraph.mouseMove_(e); |
| 559 | }); |
| 560 | Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) { |
| 561 | dygraph.mouseOut_(e); |
| 562 | }); |
| 563 | |
| 564 | // Create the grapher |
| 565 | // TODO(danvk): why does the Layout need its own set of options? |
| 566 | this.layoutOptions_ = { 'xOriginIsZero': false }; |
| 567 | Dygraph.update(this.layoutOptions_, this.attrs_); |
| 568 | Dygraph.update(this.layoutOptions_, this.user_attrs_); |
| 569 | Dygraph.update(this.layoutOptions_, { |
| 570 | 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) }); |
| 571 | |
| 572 | this.layout_ = new DygraphLayout(this, this.layoutOptions_); |
| 573 | |
| 574 | // TODO(danvk): why does the Renderer need its own set of options? |
| 575 | this.renderOptions_ = { colorScheme: this.colors_, |
| 576 | strokeColor: null, |
| 577 | axisLineWidth: Dygraph.AXIS_LINE_WIDTH }; |
| 578 | Dygraph.update(this.renderOptions_, this.attrs_); |
| 579 | Dygraph.update(this.renderOptions_, this.user_attrs_); |
| 580 | |
| 581 | this.createStatusMessage_(); |
| 582 | this.createDragInterface_(); |
| 583 | }; |
| 584 | |
| 585 | /** |
| 586 | * Detach DOM elements in the dygraph and null out all data references. |
| 587 | * Calling this when you're done with a dygraph can dramatically reduce memory |
| 588 | * usage. See, e.g., the tests/perf.html example. |
| 589 | */ |
| 590 | Dygraph.prototype.destroy = function() { |
| 591 | var removeRecursive = function(node) { |
| 592 | while (node.hasChildNodes()) { |
| 593 | removeRecursive(node.firstChild); |
| 594 | node.removeChild(node.firstChild); |
| 595 | } |
| 596 | }; |
| 597 | removeRecursive(this.maindiv_); |
| 598 | |
| 599 | var nullOut = function(obj) { |
| 600 | for (var n in obj) { |
| 601 | if (typeof(obj[n]) === 'object') { |
| 602 | obj[n] = null; |
| 603 | } |
| 604 | } |
| 605 | }; |
| 606 | |
| 607 | // These may not all be necessary, but it can't hurt... |
| 608 | nullOut(this.layout_); |
| 609 | nullOut(this.plotter_); |
| 610 | nullOut(this); |
| 611 | }; |
| 612 | |
| 613 | /** |
| 614 | * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on |
| 615 | * this particular canvas. All Dygraph work is done on this.canvas_. |
| 616 | * @param {Object} canvas The Dygraph canvas over which to overlay the plot |
| 617 | * @return {Object} The newly-created canvas |
| 618 | * @private |
| 619 | */ |
| 620 | Dygraph.prototype.createPlotKitCanvas_ = function(canvas) { |
| 621 | var h = Dygraph.createCanvas(); |
| 622 | h.style.position = "absolute"; |
| 623 | // TODO(danvk): h should be offset from canvas. canvas needs to include |
| 624 | // some extra area to make it easier to zoom in on the far left and far |
| 625 | // right. h needs to be precisely the plot area, so that clipping occurs. |
| 626 | h.style.top = canvas.style.top; |
| 627 | h.style.left = canvas.style.left; |
| 628 | h.width = this.width_; |
| 629 | h.height = this.height_; |
| 630 | h.style.width = this.width_ + "px"; // for IE |
| 631 | h.style.height = this.height_ + "px"; // for IE |
| 632 | return h; |
| 633 | }; |
| 634 | |
| 635 | // Taken from MochiKit.Color |
| 636 | Dygraph.hsvToRGB = function (hue, saturation, value) { |
| 637 | var red; |
| 638 | var green; |
| 639 | var blue; |
| 640 | if (saturation === 0) { |
| 641 | red = value; |
| 642 | green = value; |
| 643 | blue = value; |
| 644 | } else { |
| 645 | var i = Math.floor(hue * 6); |
| 646 | var f = (hue * 6) - i; |
| 647 | var p = value * (1 - saturation); |
| 648 | var q = value * (1 - (saturation * f)); |
| 649 | var t = value * (1 - (saturation * (1 - f))); |
| 650 | switch (i) { |
| 651 | case 1: red = q; green = value; blue = p; break; |
| 652 | case 2: red = p; green = value; blue = t; break; |
| 653 | case 3: red = p; green = q; blue = value; break; |
| 654 | case 4: red = t; green = p; blue = value; break; |
| 655 | case 5: red = value; green = p; blue = q; break; |
| 656 | case 6: // fall through |
| 657 | case 0: red = value; green = t; blue = p; break; |
| 658 | } |
| 659 | } |
| 660 | red = Math.floor(255 * red + 0.5); |
| 661 | green = Math.floor(255 * green + 0.5); |
| 662 | blue = Math.floor(255 * blue + 0.5); |
| 663 | return 'rgb(' + red + ',' + green + ',' + blue + ')'; |
| 664 | }; |
| 665 | |
| 666 | |
| 667 | /** |
| 668 | * Generate a set of distinct colors for the data series. This is done with a |
| 669 | * color wheel. Saturation/Value are customizable, and the hue is |
| 670 | * equally-spaced around the color wheel. If a custom set of colors is |
| 671 | * specified, that is used instead. |
| 672 | * @private |
| 673 | */ |
| 674 | Dygraph.prototype.setColors_ = function() { |
| 675 | // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do |
| 676 | // away with this.renderOptions_. |
| 677 | var num = this.attr_("labels").length - 1; |
| 678 | this.colors_ = []; |
| 679 | var colors = this.attr_('colors'); |
| 680 | if (!colors) { |
| 681 | var sat = this.attr_('colorSaturation') || 1.0; |
| 682 | var val = this.attr_('colorValue') || 0.5; |
| 683 | var half = Math.ceil(num / 2); |
| 684 | for (var i = 1; i <= num; i++) { |
| 685 | if (!this.visibility()[i-1]) continue; |
| 686 | // alternate colors for high contrast. |
| 687 | var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2); |
| 688 | var hue = (1.0 * idx/ (1 + num)); |
| 689 | this.colors_.push(Dygraph.hsvToRGB(hue, sat, val)); |
| 690 | } |
| 691 | } else { |
| 692 | for (var i = 0; i < num; i++) { |
| 693 | if (!this.visibility()[i]) continue; |
| 694 | var colorStr = colors[i % colors.length]; |
| 695 | this.colors_.push(colorStr); |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | // TODO(danvk): update this w/r/t/ the new options system. |
| 700 | this.renderOptions_.colorScheme = this.colors_; |
| 701 | Dygraph.update(this.plotter_.options, this.renderOptions_); |
| 702 | Dygraph.update(this.layoutOptions_, this.user_attrs_); |
| 703 | Dygraph.update(this.layoutOptions_, this.attrs_); |
| 704 | } |
| 705 | |
| 706 | /** |
| 707 | * Return the list of colors. This is either the list of colors passed in the |
| 708 | * attributes, or the autogenerated list of rgb(r,g,b) strings. |
| 709 | * @return {Array<string>} The list of colors. |
| 710 | */ |
| 711 | Dygraph.prototype.getColors = function() { |
| 712 | return this.colors_; |
| 713 | }; |
| 714 | |
| 715 | // The following functions are from quirksmode.org with a modification for Safari from |
| 716 | // http://blog.firetree.net/2005/07/04/javascript-find-position/ |
| 717 | // http://www.quirksmode.org/js/findpos.html |
| 718 | Dygraph.findPosX = function(obj) { |
| 719 | var curleft = 0; |
| 720 | if(obj.offsetParent) |
| 721 | while(1) |
| 722 | { |
| 723 | curleft += obj.offsetLeft; |
| 724 | if(!obj.offsetParent) |
| 725 | break; |
| 726 | obj = obj.offsetParent; |
| 727 | } |
| 728 | else if(obj.x) |
| 729 | curleft += obj.x; |
| 730 | return curleft; |
| 731 | }; |
| 732 | |
| 733 | Dygraph.findPosY = function(obj) { |
| 734 | var curtop = 0; |
| 735 | if(obj.offsetParent) |
| 736 | while(1) |
| 737 | { |
| 738 | curtop += obj.offsetTop; |
| 739 | if(!obj.offsetParent) |
| 740 | break; |
| 741 | obj = obj.offsetParent; |
| 742 | } |
| 743 | else if(obj.y) |
| 744 | curtop += obj.y; |
| 745 | return curtop; |
| 746 | }; |
| 747 | |
| 748 | |
| 749 | |
| 750 | /** |
| 751 | * Create the div that contains information on the selected point(s) |
| 752 | * This goes in the top right of the canvas, unless an external div has already |
| 753 | * been specified. |
| 754 | * @private |
| 755 | */ |
| 756 | Dygraph.prototype.createStatusMessage_ = function() { |
| 757 | var userLabelsDiv = this.user_attrs_["labelsDiv"]; |
| 758 | if (userLabelsDiv && null != userLabelsDiv |
| 759 | && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) { |
| 760 | this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv); |
| 761 | } |
| 762 | if (!this.attr_("labelsDiv")) { |
| 763 | var divWidth = this.attr_('labelsDivWidth'); |
| 764 | var messagestyle = { |
| 765 | "position": "absolute", |
| 766 | "fontSize": "14px", |
| 767 | "zIndex": 10, |
| 768 | "width": divWidth + "px", |
| 769 | "top": "0px", |
| 770 | "left": (this.width_ - divWidth - 2) + "px", |
| 771 | "background": "white", |
| 772 | "textAlign": "left", |
| 773 | "overflow": "hidden"}; |
| 774 | Dygraph.update(messagestyle, this.attr_('labelsDivStyles')); |
| 775 | var div = document.createElement("div"); |
| 776 | for (var name in messagestyle) { |
| 777 | if (messagestyle.hasOwnProperty(name)) { |
| 778 | div.style[name] = messagestyle[name]; |
| 779 | } |
| 780 | } |
| 781 | this.graphDiv.appendChild(div); |
| 782 | this.attrs_.labelsDiv = div; |
| 783 | } |
| 784 | }; |
| 785 | |
| 786 | /** |
| 787 | * Position the labels div so that its right edge is flush with the right edge |
| 788 | * of the charting area. |
| 789 | */ |
| 790 | Dygraph.prototype.positionLabelsDiv_ = function() { |
| 791 | // Don't touch a user-specified labelsDiv. |
| 792 | if (this.user_attrs_.hasOwnProperty("labelsDiv")) return; |
| 793 | |
| 794 | var area = this.plotter_.area; |
| 795 | var div = this.attr_("labelsDiv"); |
| 796 | div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px"; |
| 797 | }; |
| 798 | |
| 799 | /** |
| 800 | * Create the text box to adjust the averaging period |
| 801 | * @private |
| 802 | */ |
| 803 | Dygraph.prototype.createRollInterface_ = function() { |
| 804 | // Create a roller if one doesn't exist already. |
| 805 | if (!this.roller_) { |
| 806 | this.roller_ = document.createElement("input"); |
| 807 | this.roller_.type = "text"; |
| 808 | this.roller_.style.display = "none"; |
| 809 | this.graphDiv.appendChild(this.roller_); |
| 810 | } |
| 811 | |
| 812 | var display = this.attr_('showRoller') ? 'block' : 'none'; |
| 813 | |
| 814 | var textAttr = { "position": "absolute", |
| 815 | "zIndex": 10, |
| 816 | "top": (this.plotter_.area.h - 25) + "px", |
| 817 | "left": (this.plotter_.area.x + 1) + "px", |
| 818 | "display": display |
| 819 | }; |
| 820 | this.roller_.size = "2"; |
| 821 | this.roller_.value = this.rollPeriod_; |
| 822 | for (var name in textAttr) { |
| 823 | if (textAttr.hasOwnProperty(name)) { |
| 824 | this.roller_.style[name] = textAttr[name]; |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | var dygraph = this; |
| 829 | this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); }; |
| 830 | }; |
| 831 | |
| 832 | // These functions are taken from MochiKit.Signal |
| 833 | Dygraph.pageX = function(e) { |
| 834 | if (e.pageX) { |
| 835 | return (!e.pageX || e.pageX < 0) ? 0 : e.pageX; |
| 836 | } else { |
| 837 | var de = document; |
| 838 | var b = document.body; |
| 839 | return e.clientX + |
| 840 | (de.scrollLeft || b.scrollLeft) - |
| 841 | (de.clientLeft || 0); |
| 842 | } |
| 843 | }; |
| 844 | |
| 845 | Dygraph.pageY = function(e) { |
| 846 | if (e.pageY) { |
| 847 | return (!e.pageY || e.pageY < 0) ? 0 : e.pageY; |
| 848 | } else { |
| 849 | var de = document; |
| 850 | var b = document.body; |
| 851 | return e.clientY + |
| 852 | (de.scrollTop || b.scrollTop) - |
| 853 | (de.clientTop || 0); |
| 854 | } |
| 855 | }; |
| 856 | |
| 857 | Dygraph.prototype.dragGetX_ = function(e, context) { |
| 858 | return Dygraph.pageX(e) - context.px |
| 859 | }; |
| 860 | |
| 861 | Dygraph.prototype.dragGetY_ = function(e, context) { |
| 862 | return Dygraph.pageY(e) - context.py |
| 863 | }; |
| 864 | |
| 865 | // Called in response to an interaction model operation that |
| 866 | // should start the default panning behavior. |
| 867 | // |
| 868 | // It's used in the default callback for "mousedown" operations. |
| 869 | // Custom interaction model builders can use it to provide the default |
| 870 | // panning behavior. |
| 871 | // |
| 872 | Dygraph.startPan = function(event, g, context) { |
| 873 | // have to be zoomed in to pan. |
| 874 | // TODO(konigsberg): Let's loosen this zoom-to-pan restriction, also |
| 875 | // perhaps create panning boundaries? A more flexible pan would make it, |
| 876 | // ahem, 'pan-useful'. |
| 877 | var zoomedY = false; |
| 878 | for (var i = 0; i < g.axes_.length; i++) { |
| 879 | if (g.axes_[i].valueWindow || g.axes_[i].valueRange) { |
| 880 | zoomedY = true; |
| 881 | break; |
| 882 | } |
| 883 | } |
| 884 | if (!g.dateWindow_ && !zoomedY) return; |
| 885 | |
| 886 | context.isPanning = true; |
| 887 | var xRange = g.xAxisRange(); |
| 888 | context.dateRange = xRange[1] - xRange[0]; |
| 889 | |
| 890 | // Record the range of each y-axis at the start of the drag. |
| 891 | // If any axis has a valueRange or valueWindow, then we want a 2D pan. |
| 892 | context.is2DPan = false; |
| 893 | for (var i = 0; i < g.axes_.length; i++) { |
| 894 | var axis = g.axes_[i]; |
| 895 | var yRange = g.yAxisRange(i); |
| 896 | axis.dragValueRange = yRange[1] - yRange[0]; |
| 897 | var r = g.toDataCoords(null, context.dragStartY, i); |
| 898 | axis.draggingValue = r[1]; |
| 899 | if (axis.valueWindow || axis.valueRange) context.is2DPan = true; |
| 900 | } |
| 901 | |
| 902 | // TODO(konigsberg): Switch from all this math to toDataCoords? |
| 903 | // Seems to work for the dragging value. |
| 904 | context.draggingDate = (context.dragStartX / g.width_) * context.dateRange + xRange[0]; |
| 905 | }; |
| 906 | |
| 907 | // Called in response to an interaction model operation that |
| 908 | // responds to an event that pans the view. |
| 909 | // |
| 910 | // It's used in the default callback for "mousemove" operations. |
| 911 | // Custom interaction model builders can use it to provide the default |
| 912 | // panning behavior. |
| 913 | // |
| 914 | Dygraph.movePan = function(event, g, context) { |
| 915 | context.dragEndX = g.dragGetX_(event, context); |
| 916 | context.dragEndY = g.dragGetY_(event, context); |
| 917 | |
| 918 | // TODO(danvk): update this comment |
| 919 | // Want to have it so that: |
| 920 | // 1. draggingDate appears at dragEndX, draggingValue appears at dragEndY. |
| 921 | // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered. |
| 922 | // 3. draggingValue appears at dragEndY. |
| 923 | // 4. valueRange is unaltered. |
| 924 | |
| 925 | var minDate = context.draggingDate - (context.dragEndX / g.width_) * context.dateRange; |
| 926 | var maxDate = minDate + context.dateRange; |
| 927 | g.dateWindow_ = [minDate, maxDate]; |
| 928 | |
| 929 | // y-axis scaling is automatic unless this is a full 2D pan. |
| 930 | if (context.is2DPan) { |
| 931 | // Adjust each axis appropriately. |
| 932 | var y_frac = context.dragEndY / g.height_; |
| 933 | for (var i = 0; i < g.axes_.length; i++) { |
| 934 | var axis = g.axes_[i]; |
| 935 | var maxValue = axis.draggingValue + y_frac * axis.dragValueRange; |
| 936 | var minValue = maxValue - axis.dragValueRange; |
| 937 | axis.valueWindow = [ minValue, maxValue ]; |
| 938 | } |
| 939 | } |
| 940 | |
| 941 | g.drawGraph_(); |
| 942 | } |
| 943 | |
| 944 | // Called in response to an interaction model operation that |
| 945 | // responds to an event that ends panning. |
| 946 | // |
| 947 | // It's used in the default callback for "mouseup" operations. |
| 948 | // Custom interaction model builders can use it to provide the default |
| 949 | // panning behavior. |
| 950 | // |
| 951 | Dygraph.endPan = function(event, g, context) { |
| 952 | context.isPanning = false; |
| 953 | context.is2DPan = false; |
| 954 | context.draggingDate = null; |
| 955 | context.dateRange = null; |
| 956 | context.valueRange = null; |
| 957 | } |
| 958 | |
| 959 | // Called in response to an interaction model operation that |
| 960 | // responds to an event that starts zooming. |
| 961 | // |
| 962 | // It's used in the default callback for "mousedown" operations. |
| 963 | // Custom interaction model builders can use it to provide the default |
| 964 | // zooming behavior. |
| 965 | // |
| 966 | Dygraph.startZoom = function(event, g, context) { |
| 967 | context.isZooming = true; |
| 968 | } |
| 969 | |
| 970 | // Called in response to an interaction model operation that |
| 971 | // responds to an event that defines zoom boundaries. |
| 972 | // |
| 973 | // It's used in the default callback for "mousemove" operations. |
| 974 | // Custom interaction model builders can use it to provide the default |
| 975 | // zooming behavior. |
| 976 | // |
| 977 | Dygraph.moveZoom = function(event, g, context) { |
| 978 | context.dragEndX = g.dragGetX_(event, context); |
| 979 | context.dragEndY = g.dragGetY_(event, context); |
| 980 | |
| 981 | var xDelta = Math.abs(context.dragStartX - context.dragEndX); |
| 982 | var yDelta = Math.abs(context.dragStartY - context.dragEndY); |
| 983 | |
| 984 | // drag direction threshold for y axis is twice as large as x axis |
| 985 | context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL; |
| 986 | |
| 987 | g.drawZoomRect_( |
| 988 | context.dragDirection, |
| 989 | context.dragStartX, |
| 990 | context.dragEndX, |
| 991 | context.dragStartY, |
| 992 | context.dragEndY, |
| 993 | context.prevDragDirection, |
| 994 | context.prevEndX, |
| 995 | context.prevEndY); |
| 996 | |
| 997 | context.prevEndX = context.dragEndX; |
| 998 | context.prevEndY = context.dragEndY; |
| 999 | context.prevDragDirection = context.dragDirection; |
| 1000 | } |
| 1001 | |
| 1002 | // Called in response to an interaction model operation that |
| 1003 | // responds to an event that performs a zoom based on previously defined |
| 1004 | // bounds.. |
| 1005 | // |
| 1006 | // It's used in the default callback for "mouseup" operations. |
| 1007 | // Custom interaction model builders can use it to provide the default |
| 1008 | // zooming behavior. |
| 1009 | // |
| 1010 | Dygraph.endZoom = function(event, g, context) { |
| 1011 | context.isZooming = false; |
| 1012 | context.dragEndX = g.dragGetX_(event, context); |
| 1013 | context.dragEndY = g.dragGetY_(event, context); |
| 1014 | var regionWidth = Math.abs(context.dragEndX - context.dragStartX); |
| 1015 | var regionHeight = Math.abs(context.dragEndY - context.dragStartY); |
| 1016 | |
| 1017 | if (regionWidth < 2 && regionHeight < 2 && |
| 1018 | g.lastx_ != undefined && g.lastx_ != -1) { |
| 1019 | // TODO(danvk): pass along more info about the points, e.g. 'x' |
| 1020 | if (g.attr_('clickCallback') != null) { |
| 1021 | g.attr_('clickCallback')(event, g.lastx_, g.selPoints_); |
| 1022 | } |
| 1023 | if (g.attr_('pointClickCallback')) { |
| 1024 | // check if the click was on a particular point. |
| 1025 | var closestIdx = -1; |
| 1026 | var closestDistance = 0; |
| 1027 | for (var i = 0; i < g.selPoints_.length; i++) { |
| 1028 | var p = g.selPoints_[i]; |
| 1029 | var distance = Math.pow(p.canvasx - context.dragEndX, 2) + |
| 1030 | Math.pow(p.canvasy - context.dragEndY, 2); |
| 1031 | if (closestIdx == -1 || distance < closestDistance) { |
| 1032 | closestDistance = distance; |
| 1033 | closestIdx = i; |
| 1034 | } |
| 1035 | } |
| 1036 | |
| 1037 | // Allow any click within two pixels of the dot. |
| 1038 | var radius = g.attr_('highlightCircleSize') + 2; |
| 1039 | if (closestDistance <= 5 * 5) { |
| 1040 | g.attr_('pointClickCallback')(event, g.selPoints_[closestIdx]); |
| 1041 | } |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) { |
| 1046 | g.doZoomX_(Math.min(context.dragStartX, context.dragEndX), |
| 1047 | Math.max(context.dragStartX, context.dragEndX)); |
| 1048 | } else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) { |
| 1049 | g.doZoomY_(Math.min(context.dragStartY, context.dragEndY), |
| 1050 | Math.max(context.dragStartY, context.dragEndY)); |
| 1051 | } else { |
| 1052 | g.canvas_.getContext("2d").clearRect(0, 0, |
| 1053 | g.canvas_.width, |
| 1054 | g.canvas_.height); |
| 1055 | } |
| 1056 | context.dragStartX = null; |
| 1057 | context.dragStartY = null; |
| 1058 | } |
| 1059 | |
| 1060 | Dygraph.defaultInteractionModel = { |
| 1061 | // Track the beginning of drag events |
| 1062 | mousedown: function(event, g, context) { |
| 1063 | context.initializeMouseDown(event, g, context); |
| 1064 | |
| 1065 | if (event.altKey || event.shiftKey) { |
| 1066 | Dygraph.startPan(event, g, context); |
| 1067 | } else { |
| 1068 | Dygraph.startZoom(event, g, context); |
| 1069 | } |
| 1070 | }, |
| 1071 | |
| 1072 | // Draw zoom rectangles when the mouse is down and the user moves around |
| 1073 | mousemove: function(event, g, context) { |
| 1074 | if (context.isZooming) { |
| 1075 | Dygraph.moveZoom(event, g, context); |
| 1076 | } else if (context.isPanning) { |
| 1077 | Dygraph.movePan(event, g, context); |
| 1078 | } |
| 1079 | }, |
| 1080 | |
| 1081 | mouseup: function(event, g, context) { |
| 1082 | if (context.isZooming) { |
| 1083 | Dygraph.endZoom(event, g, context); |
| 1084 | } else if (context.isPanning) { |
| 1085 | Dygraph.endPan(event, g, context); |
| 1086 | } |
| 1087 | }, |
| 1088 | |
| 1089 | // Temporarily cancel the dragging event when the mouse leaves the graph |
| 1090 | mouseout: function(event, g, context) { |
| 1091 | if (context.isZooming) { |
| 1092 | context.dragEndX = null; |
| 1093 | context.dragEndY = null; |
| 1094 | } |
| 1095 | }, |
| 1096 | |
| 1097 | // Disable zooming out if panning. |
| 1098 | dblclick: function(event, g, context) { |
| 1099 | if (event.altKey || event.shiftKey) { |
| 1100 | return; |
| 1101 | } |
| 1102 | // TODO(konigsberg): replace g.doUnzoom()_ with something that is |
| 1103 | // friendlier to public use. |
| 1104 | g.doUnzoom_(); |
| 1105 | } |
| 1106 | }; |
| 1107 | |
| 1108 | Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.defaultInteractionModel; |
| 1109 | |
| 1110 | /** |
| 1111 | * Set up all the mouse handlers needed to capture dragging behavior for zoom |
| 1112 | * events. |
| 1113 | * @private |
| 1114 | */ |
| 1115 | Dygraph.prototype.createDragInterface_ = function() { |
| 1116 | var context = { |
| 1117 | // Tracks whether the mouse is down right now |
| 1118 | isZooming: false, |
| 1119 | isPanning: false, // is this drag part of a pan? |
| 1120 | is2DPan: false, // if so, is that pan 1- or 2-dimensional? |
| 1121 | dragStartX: null, |
| 1122 | dragStartY: null, |
| 1123 | dragEndX: null, |
| 1124 | dragEndY: null, |
| 1125 | dragDirection: null, |
| 1126 | prevEndX: null, |
| 1127 | prevEndY: null, |
| 1128 | prevDragDirection: null, |
| 1129 | |
| 1130 | // TODO(danvk): update this comment |
| 1131 | // draggingDate and draggingValue represent the [date,value] point on the |
| 1132 | // graph at which the mouse was pressed. As the mouse moves while panning, |
| 1133 | // the viewport must pan so that the mouse position points to |
| 1134 | // [draggingDate, draggingValue] |
| 1135 | draggingDate: null, |
| 1136 | |
| 1137 | // TODO(danvk): update this comment |
| 1138 | // The range in second/value units that the viewport encompasses during a |
| 1139 | // panning operation. |
| 1140 | dateRange: null, |
| 1141 | |
| 1142 | // Utility function to convert page-wide coordinates to canvas coords |
| 1143 | px: 0, |
| 1144 | py: 0, |
| 1145 | |
| 1146 | initializeMouseDown: function(event, g, context) { |
| 1147 | // prevents mouse drags from selecting page text. |
| 1148 | if (event.preventDefault) { |
| 1149 | event.preventDefault(); // Firefox, Chrome, etc. |
| 1150 | } else { |
| 1151 | event.returnValue = false; // IE |
| 1152 | event.cancelBubble = true; |
| 1153 | } |
| 1154 | |
| 1155 | context.px = Dygraph.findPosX(g.canvas_); |
| 1156 | context.py = Dygraph.findPosY(g.canvas_); |
| 1157 | context.dragStartX = g.dragGetX_(event, context); |
| 1158 | context.dragStartY = g.dragGetY_(event, context); |
| 1159 | } |
| 1160 | }; |
| 1161 | |
| 1162 | var interactionModel = this.attr_("interactionModel"); |
| 1163 | |
| 1164 | // Self is the graph. |
| 1165 | var self = this; |
| 1166 | |
| 1167 | // Function that binds the graph and context to the handler. |
| 1168 | var bindHandler = function(handler) { |
| 1169 | return function(event) { |
| 1170 | handler(event, self, context); |
| 1171 | }; |
| 1172 | }; |
| 1173 | |
| 1174 | for (var eventName in interactionModel) { |
| 1175 | if (!interactionModel.hasOwnProperty(eventName)) continue; |
| 1176 | Dygraph.addEvent(this.mouseEventElement_, eventName, |
| 1177 | bindHandler(interactionModel[eventName])); |
| 1178 | } |
| 1179 | |
| 1180 | // If the user releases the mouse button during a drag, but not over the |
| 1181 | // canvas, then it doesn't count as a zooming action. |
| 1182 | Dygraph.addEvent(document, 'mouseup', function(event) { |
| 1183 | if (context.isZooming || context.isPanning) { |
| 1184 | context.isZooming = false; |
| 1185 | context.dragStartX = null; |
| 1186 | context.dragStartY = null; |
| 1187 | } |
| 1188 | |
| 1189 | if (context.isPanning) { |
| 1190 | context.isPanning = false; |
| 1191 | context.draggingDate = null; |
| 1192 | context.dateRange = null; |
| 1193 | for (var i = 0; i < self.axes_.length; i++) { |
| 1194 | delete self.axes_[i].draggingValue; |
| 1195 | delete self.axes_[i].dragValueRange; |
| 1196 | } |
| 1197 | } |
| 1198 | }); |
| 1199 | }; |
| 1200 | |
| 1201 | |
| 1202 | /** |
| 1203 | * Draw a gray zoom rectangle over the desired area of the canvas. Also clears |
| 1204 | * up any previous zoom rectangles that were drawn. This could be optimized to |
| 1205 | * avoid extra redrawing, but it's tricky to avoid interactions with the status |
| 1206 | * dots. |
| 1207 | * |
| 1208 | * @param {Number} direction the direction of the zoom rectangle. Acceptable |
| 1209 | * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL. |
| 1210 | * @param {Number} startX The X position where the drag started, in canvas |
| 1211 | * coordinates. |
| 1212 | * @param {Number} endX The current X position of the drag, in canvas coords. |
| 1213 | * @param {Number} startY The Y position where the drag started, in canvas |
| 1214 | * coordinates. |
| 1215 | * @param {Number} endY The current Y position of the drag, in canvas coords. |
| 1216 | * @param {Number} prevDirection the value of direction on the previous call to |
| 1217 | * this function. Used to avoid excess redrawing |
| 1218 | * @param {Number} prevEndX The value of endX on the previous call to this |
| 1219 | * function. Used to avoid excess redrawing |
| 1220 | * @param {Number} prevEndY The value of endY on the previous call to this |
| 1221 | * function. Used to avoid excess redrawing |
| 1222 | * @private |
| 1223 | */ |
| 1224 | Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY, |
| 1225 | endY, prevDirection, prevEndX, |
| 1226 | prevEndY) { |
| 1227 | var ctx = this.canvas_.getContext("2d"); |
| 1228 | |
| 1229 | // Clean up from the previous rect if necessary |
| 1230 | if (prevDirection == Dygraph.HORIZONTAL) { |
| 1231 | ctx.clearRect(Math.min(startX, prevEndX), 0, |
| 1232 | Math.abs(startX - prevEndX), this.height_); |
| 1233 | } else if (prevDirection == Dygraph.VERTICAL){ |
| 1234 | ctx.clearRect(0, Math.min(startY, prevEndY), |
| 1235 | this.width_, Math.abs(startY - prevEndY)); |
| 1236 | } |
| 1237 | |
| 1238 | // Draw a light-grey rectangle to show the new viewing area |
| 1239 | if (direction == Dygraph.HORIZONTAL) { |
| 1240 | if (endX && startX) { |
| 1241 | ctx.fillStyle = "rgba(128,128,128,0.33)"; |
| 1242 | ctx.fillRect(Math.min(startX, endX), 0, |
| 1243 | Math.abs(endX - startX), this.height_); |
| 1244 | } |
| 1245 | } |
| 1246 | if (direction == Dygraph.VERTICAL) { |
| 1247 | if (endY && startY) { |
| 1248 | ctx.fillStyle = "rgba(128,128,128,0.33)"; |
| 1249 | ctx.fillRect(0, Math.min(startY, endY), |
| 1250 | this.width_, Math.abs(endY - startY)); |
| 1251 | } |
| 1252 | } |
| 1253 | }; |
| 1254 | |
| 1255 | /** |
| 1256 | * Zoom to something containing [lowX, highX]. These are pixel coordinates in |
| 1257 | * the canvas. The exact zoom window may be slightly larger if there are no data |
| 1258 | * points near lowX or highX. Don't confuse this function with doZoomXDates, |
| 1259 | * which accepts dates that match the raw data. This function redraws the graph. |
| 1260 | * |
| 1261 | * @param {Number} lowX The leftmost pixel value that should be visible. |
| 1262 | * @param {Number} highX The rightmost pixel value that should be visible. |
| 1263 | * @private |
| 1264 | */ |
| 1265 | Dygraph.prototype.doZoomX_ = function(lowX, highX) { |
| 1266 | // Find the earliest and latest dates contained in this canvasx range. |
| 1267 | // Convert the call to date ranges of the raw data. |
| 1268 | var r = this.toDataCoords(lowX, null); |
| 1269 | var minDate = r[0]; |
| 1270 | r = this.toDataCoords(highX, null); |
| 1271 | var maxDate = r[0]; |
| 1272 | this.doZoomXDates_(minDate, maxDate); |
| 1273 | }; |
| 1274 | |
| 1275 | /** |
| 1276 | * Zoom to something containing [minDate, maxDate] values. Don't confuse this |
| 1277 | * method with doZoomX which accepts pixel coordinates. This function redraws |
| 1278 | * the graph. |
| 1279 | * |
| 1280 | * @param {Number} minDate The minimum date that should be visible. |
| 1281 | * @param {Number} maxDate The maximum date that should be visible. |
| 1282 | * @private |
| 1283 | */ |
| 1284 | Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) { |
| 1285 | this.dateWindow_ = [minDate, maxDate]; |
| 1286 | this.drawGraph_(); |
| 1287 | if (this.attr_("zoomCallback")) { |
| 1288 | this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges()); |
| 1289 | } |
| 1290 | }; |
| 1291 | |
| 1292 | /** |
| 1293 | * Zoom to something containing [lowY, highY]. These are pixel coordinates in |
| 1294 | * the canvas. This function redraws the graph. |
| 1295 | * |
| 1296 | * @param {Number} lowY The topmost pixel value that should be visible. |
| 1297 | * @param {Number} highY The lowest pixel value that should be visible. |
| 1298 | * @private |
| 1299 | */ |
| 1300 | Dygraph.prototype.doZoomY_ = function(lowY, highY) { |
| 1301 | // Find the highest and lowest values in pixel range for each axis. |
| 1302 | // Note that lowY (in pixels) corresponds to the max Value (in data coords). |
| 1303 | // This is because pixels increase as you go down on the screen, whereas data |
| 1304 | // coordinates increase as you go up the screen. |
| 1305 | var valueRanges = []; |
| 1306 | for (var i = 0; i < this.axes_.length; i++) { |
| 1307 | var hi = this.toDataCoords(null, lowY, i); |
| 1308 | var low = this.toDataCoords(null, highY, i); |
| 1309 | this.axes_[i].valueWindow = [low[1], hi[1]]; |
| 1310 | valueRanges.push([low[1], hi[1]]); |
| 1311 | } |
| 1312 | |
| 1313 | this.drawGraph_(); |
| 1314 | if (this.attr_("zoomCallback")) { |
| 1315 | var xRange = this.xAxisRange(); |
| 1316 | this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges()); |
| 1317 | } |
| 1318 | }; |
| 1319 | |
| 1320 | /** |
| 1321 | * Reset the zoom to the original view coordinates. This is the same as |
| 1322 | * double-clicking on the graph. |
| 1323 | * |
| 1324 | * @private |
| 1325 | */ |
| 1326 | Dygraph.prototype.doUnzoom_ = function() { |
| 1327 | var dirty = false; |
| 1328 | if (this.dateWindow_ != null) { |
| 1329 | dirty = true; |
| 1330 | this.dateWindow_ = null; |
| 1331 | } |
| 1332 | |
| 1333 | for (var i = 0; i < this.axes_.length; i++) { |
| 1334 | if (this.axes_[i].valueWindow != null) { |
| 1335 | dirty = true; |
| 1336 | delete this.axes_[i].valueWindow; |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | if (dirty) { |
| 1341 | // Putting the drawing operation before the callback because it resets |
| 1342 | // yAxisRange. |
| 1343 | this.drawGraph_(); |
| 1344 | if (this.attr_("zoomCallback")) { |
| 1345 | var minDate = this.rawData_[0][0]; |
| 1346 | var maxDate = this.rawData_[this.rawData_.length - 1][0]; |
| 1347 | this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges()); |
| 1348 | } |
| 1349 | } |
| 1350 | }; |
| 1351 | |
| 1352 | /** |
| 1353 | * When the mouse moves in the canvas, display information about a nearby data |
| 1354 | * point and draw dots over those points in the data series. This function |
| 1355 | * takes care of cleanup of previously-drawn dots. |
| 1356 | * @param {Object} event The mousemove event from the browser. |
| 1357 | * @private |
| 1358 | */ |
| 1359 | Dygraph.prototype.mouseMove_ = function(event) { |
| 1360 | var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_); |
| 1361 | var points = this.layout_.points; |
| 1362 | |
| 1363 | var lastx = -1; |
| 1364 | var lasty = -1; |
| 1365 | |
| 1366 | // Loop through all the points and find the date nearest to our current |
| 1367 | // location. |
| 1368 | var minDist = 1e+100; |
| 1369 | var idx = -1; |
| 1370 | for (var i = 0; i < points.length; i++) { |
| 1371 | var point = points[i]; |
| 1372 | if (point == null) continue; |
| 1373 | var dist = Math.abs(point.canvasx - canvasx); |
| 1374 | if (dist > minDist) continue; |
| 1375 | minDist = dist; |
| 1376 | idx = i; |
| 1377 | } |
| 1378 | if (idx >= 0) lastx = points[idx].xval; |
| 1379 | // Check that you can really highlight the last day's data |
| 1380 | var last = points[points.length-1]; |
| 1381 | if (last != null && canvasx > last.canvasx) |
| 1382 | lastx = points[points.length-1].xval; |
| 1383 | |
| 1384 | // Extract the points we've selected |
| 1385 | this.selPoints_ = []; |
| 1386 | var l = points.length; |
| 1387 | if (!this.attr_("stackedGraph")) { |
| 1388 | for (var i = 0; i < l; i++) { |
| 1389 | if (points[i].xval == lastx) { |
| 1390 | this.selPoints_.push(points[i]); |
| 1391 | } |
| 1392 | } |
| 1393 | } else { |
| 1394 | // Need to 'unstack' points starting from the bottom |
| 1395 | var cumulative_sum = 0; |
| 1396 | for (var i = l - 1; i >= 0; i--) { |
| 1397 | if (points[i].xval == lastx) { |
| 1398 | var p = {}; // Clone the point since we modify it |
| 1399 | for (var k in points[i]) { |
| 1400 | p[k] = points[i][k]; |
| 1401 | } |
| 1402 | p.yval -= cumulative_sum; |
| 1403 | cumulative_sum += p.yval; |
| 1404 | this.selPoints_.push(p); |
| 1405 | } |
| 1406 | } |
| 1407 | this.selPoints_.reverse(); |
| 1408 | } |
| 1409 | |
| 1410 | if (this.attr_("highlightCallback")) { |
| 1411 | var px = this.lastx_; |
| 1412 | if (px !== null && lastx != px) { |
| 1413 | // only fire if the selected point has changed. |
| 1414 | this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx)); |
| 1415 | } |
| 1416 | } |
| 1417 | |
| 1418 | // Save last x position for callbacks. |
| 1419 | this.lastx_ = lastx; |
| 1420 | |
| 1421 | this.updateSelection_(); |
| 1422 | }; |
| 1423 | |
| 1424 | /** |
| 1425 | * Transforms layout_.points index into data row number. |
| 1426 | * @param int layout_.points index |
| 1427 | * @return int row number, or -1 if none could be found. |
| 1428 | * @private |
| 1429 | */ |
| 1430 | Dygraph.prototype.idxToRow_ = function(idx) { |
| 1431 | if (idx < 0) return -1; |
| 1432 | |
| 1433 | for (var i in this.layout_.datasets) { |
| 1434 | if (idx < this.layout_.datasets[i].length) { |
| 1435 | return this.boundaryIds_[0][0]+idx; |
| 1436 | } |
| 1437 | idx -= this.layout_.datasets[i].length; |
| 1438 | } |
| 1439 | return -1; |
| 1440 | }; |
| 1441 | |
| 1442 | /** |
| 1443 | * Draw dots over the selectied points in the data series. This function |
| 1444 | * takes care of cleanup of previously-drawn dots. |
| 1445 | * @private |
| 1446 | */ |
| 1447 | Dygraph.prototype.updateSelection_ = function() { |
| 1448 | // Clear the previously drawn vertical, if there is one |
| 1449 | var ctx = this.canvas_.getContext("2d"); |
| 1450 | if (this.previousVerticalX_ >= 0) { |
| 1451 | // Determine the maximum highlight circle size. |
| 1452 | var maxCircleSize = 0; |
| 1453 | var labels = this.attr_('labels'); |
| 1454 | for (var i = 1; i < labels.length; i++) { |
| 1455 | var r = this.attr_('highlightCircleSize', labels[i]); |
| 1456 | if (r > maxCircleSize) maxCircleSize = r; |
| 1457 | } |
| 1458 | var px = this.previousVerticalX_; |
| 1459 | ctx.clearRect(px - maxCircleSize - 1, 0, |
| 1460 | 2 * maxCircleSize + 2, this.height_); |
| 1461 | } |
| 1462 | |
| 1463 | var isOK = function(x) { return x && !isNaN(x); }; |
| 1464 | |
| 1465 | if (this.selPoints_.length > 0) { |
| 1466 | var canvasx = this.selPoints_[0].canvasx; |
| 1467 | |
| 1468 | // Set the status message to indicate the selected point(s) |
| 1469 | var replace = this.attr_('xValueFormatter')( |
| 1470 | this.lastx_, this.numXDigits_ + this.numExtraDigits_) + ":"; |
| 1471 | var fmtFunc = this.attr_('yValueFormatter'); |
| 1472 | var clen = this.colors_.length; |
| 1473 | |
| 1474 | if (this.attr_('showLabelsOnHighlight')) { |
| 1475 | // Set the status message to indicate the selected point(s) |
| 1476 | for (var i = 0; i < this.selPoints_.length; i++) { |
| 1477 | if (!this.attr_("labelsShowZeroValues") && this.selPoints_[i].yval == 0) continue; |
| 1478 | if (!isOK(this.selPoints_[i].canvasy)) continue; |
| 1479 | if (this.attr_("labelsSeparateLines")) { |
| 1480 | replace += "<br/>"; |
| 1481 | } |
| 1482 | var point = this.selPoints_[i]; |
| 1483 | var c = new RGBColor(this.plotter_.colors[point.name]); |
| 1484 | var yval = fmtFunc(point.yval, this.numYDigits_ + this.numExtraDigits_); |
| 1485 | replace += " <b><font color='" + c.toHex() + "'>" |
| 1486 | + point.name + "</font></b>:" |
| 1487 | + yval; |
| 1488 | } |
| 1489 | |
| 1490 | this.attr_("labelsDiv").innerHTML = replace; |
| 1491 | } |
| 1492 | |
| 1493 | // Draw colored circles over the center of each selected point |
| 1494 | ctx.save(); |
| 1495 | for (var i = 0; i < this.selPoints_.length; i++) { |
| 1496 | if (!isOK(this.selPoints_[i].canvasy)) continue; |
| 1497 | var circleSize = |
| 1498 | this.attr_('highlightCircleSize', this.selPoints_[i].name); |
| 1499 | ctx.beginPath(); |
| 1500 | ctx.fillStyle = this.plotter_.colors[this.selPoints_[i].name]; |
| 1501 | ctx.arc(canvasx, this.selPoints_[i].canvasy, circleSize, |
| 1502 | 0, 2 * Math.PI, false); |
| 1503 | ctx.fill(); |
| 1504 | } |
| 1505 | ctx.restore(); |
| 1506 | |
| 1507 | this.previousVerticalX_ = canvasx; |
| 1508 | } |
| 1509 | }; |
| 1510 | |
| 1511 | /** |
| 1512 | * Set manually set selected dots, and display information about them |
| 1513 | * @param int row number that should by highlighted |
| 1514 | * false value clears the selection |
| 1515 | * @public |
| 1516 | */ |
| 1517 | Dygraph.prototype.setSelection = function(row) { |
| 1518 | // Extract the points we've selected |
| 1519 | this.selPoints_ = []; |
| 1520 | var pos = 0; |
| 1521 | |
| 1522 | if (row !== false) { |
| 1523 | row = row-this.boundaryIds_[0][0]; |
| 1524 | } |
| 1525 | |
| 1526 | if (row !== false && row >= 0) { |
| 1527 | for (var i in this.layout_.datasets) { |
| 1528 | if (row < this.layout_.datasets[i].length) { |
| 1529 | var point = this.layout_.points[pos+row]; |
| 1530 | |
| 1531 | if (this.attr_("stackedGraph")) { |
| 1532 | point = this.layout_.unstackPointAtIndex(pos+row); |
| 1533 | } |
| 1534 | |
| 1535 | this.selPoints_.push(point); |
| 1536 | } |
| 1537 | pos += this.layout_.datasets[i].length; |
| 1538 | } |
| 1539 | } |
| 1540 | |
| 1541 | if (this.selPoints_.length) { |
| 1542 | this.lastx_ = this.selPoints_[0].xval; |
| 1543 | this.updateSelection_(); |
| 1544 | } else { |
| 1545 | this.lastx_ = -1; |
| 1546 | this.clearSelection(); |
| 1547 | } |
| 1548 | |
| 1549 | }; |
| 1550 | |
| 1551 | /** |
| 1552 | * The mouse has left the canvas. Clear out whatever artifacts remain |
| 1553 | * @param {Object} event the mouseout event from the browser. |
| 1554 | * @private |
| 1555 | */ |
| 1556 | Dygraph.prototype.mouseOut_ = function(event) { |
| 1557 | if (this.attr_("unhighlightCallback")) { |
| 1558 | this.attr_("unhighlightCallback")(event); |
| 1559 | } |
| 1560 | |
| 1561 | if (this.attr_("hideOverlayOnMouseOut")) { |
| 1562 | this.clearSelection(); |
| 1563 | } |
| 1564 | }; |
| 1565 | |
| 1566 | /** |
| 1567 | * Remove all selection from the canvas |
| 1568 | * @public |
| 1569 | */ |
| 1570 | Dygraph.prototype.clearSelection = function() { |
| 1571 | // Get rid of the overlay data |
| 1572 | var ctx = this.canvas_.getContext("2d"); |
| 1573 | ctx.clearRect(0, 0, this.width_, this.height_); |
| 1574 | this.attr_("labelsDiv").innerHTML = ""; |
| 1575 | this.selPoints_ = []; |
| 1576 | this.lastx_ = -1; |
| 1577 | } |
| 1578 | |
| 1579 | /** |
| 1580 | * Returns the number of the currently selected row |
| 1581 | * @return int row number, of -1 if nothing is selected |
| 1582 | * @public |
| 1583 | */ |
| 1584 | Dygraph.prototype.getSelection = function() { |
| 1585 | if (!this.selPoints_ || this.selPoints_.length < 1) { |
| 1586 | return -1; |
| 1587 | } |
| 1588 | |
| 1589 | for (var row=0; row<this.layout_.points.length; row++ ) { |
| 1590 | if (this.layout_.points[row].x == this.selPoints_[0].x) { |
| 1591 | return row + this.boundaryIds_[0][0]; |
| 1592 | } |
| 1593 | } |
| 1594 | return -1; |
| 1595 | } |
| 1596 | |
| 1597 | Dygraph.zeropad = function(x) { |
| 1598 | if (x < 10) return "0" + x; else return "" + x; |
| 1599 | } |
| 1600 | |
| 1601 | /** |
| 1602 | * Return a string version of the hours, minutes and seconds portion of a date. |
| 1603 | * @param {Number} date The JavaScript date (ms since epoch) |
| 1604 | * @return {String} A time of the form "HH:MM:SS" |
| 1605 | * @private |
| 1606 | */ |
| 1607 | Dygraph.hmsString_ = function(date) { |
| 1608 | var zeropad = Dygraph.zeropad; |
| 1609 | var d = new Date(date); |
| 1610 | if (d.getSeconds()) { |
| 1611 | return zeropad(d.getHours()) + ":" + |
| 1612 | zeropad(d.getMinutes()) + ":" + |
| 1613 | zeropad(d.getSeconds()); |
| 1614 | } else { |
| 1615 | return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes()); |
| 1616 | } |
| 1617 | } |
| 1618 | |
| 1619 | /** |
| 1620 | * Convert a JS date to a string appropriate to display on an axis that |
| 1621 | * is displaying values at the stated granularity. |
| 1622 | * @param {Date} date The date to format |
| 1623 | * @param {Number} granularity One of the Dygraph granularity constants |
| 1624 | * @return {String} The formatted date |
| 1625 | * @private |
| 1626 | */ |
| 1627 | Dygraph.dateAxisFormatter = function(date, granularity) { |
| 1628 | if (granularity >= Dygraph.DECADAL) { |
| 1629 | return date.strftime('%Y'); |
| 1630 | } else if (granularity >= Dygraph.MONTHLY) { |
| 1631 | return date.strftime('%b %y'); |
| 1632 | } else { |
| 1633 | var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds(); |
| 1634 | if (frac == 0 || granularity >= Dygraph.DAILY) { |
| 1635 | return new Date(date.getTime() + 3600*1000).strftime('%d%b'); |
| 1636 | } else { |
| 1637 | return Dygraph.hmsString_(date.getTime()); |
| 1638 | } |
| 1639 | } |
| 1640 | } |
| 1641 | |
| 1642 | /** |
| 1643 | * Convert a JS date (millis since epoch) to YYYY/MM/DD |
| 1644 | * @param {Number} date The JavaScript date (ms since epoch) |
| 1645 | * @return {String} A date of the form "YYYY/MM/DD" |
| 1646 | * @private |
| 1647 | */ |
| 1648 | Dygraph.dateString_ = function(date) { |
| 1649 | var zeropad = Dygraph.zeropad; |
| 1650 | var d = new Date(date); |
| 1651 | |
| 1652 | // Get the year: |
| 1653 | var year = "" + d.getFullYear(); |
| 1654 | // Get a 0 padded month string |
| 1655 | var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh |
| 1656 | // Get a 0 padded day string |
| 1657 | var day = zeropad(d.getDate()); |
| 1658 | |
| 1659 | var ret = ""; |
| 1660 | var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds(); |
| 1661 | if (frac) ret = " " + Dygraph.hmsString_(date); |
| 1662 | |
| 1663 | return year + "/" + month + "/" + day + ret; |
| 1664 | }; |
| 1665 | |
| 1666 | /** |
| 1667 | * Fires when there's data available to be graphed. |
| 1668 | * @param {String} data Raw CSV data to be plotted |
| 1669 | * @private |
| 1670 | */ |
| 1671 | Dygraph.prototype.loadedEvent_ = function(data) { |
| 1672 | this.rawData_ = this.parseCSV_(data); |
| 1673 | this.predraw_(); |
| 1674 | }; |
| 1675 | |
| 1676 | Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", |
| 1677 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; |
| 1678 | Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"]; |
| 1679 | |
| 1680 | /** |
| 1681 | * Add ticks on the x-axis representing years, months, quarters, weeks, or days |
| 1682 | * @private |
| 1683 | */ |
| 1684 | Dygraph.prototype.addXTicks_ = function() { |
| 1685 | // Determine the correct ticks scale on the x-axis: quarterly, monthly, ... |
| 1686 | var range; |
| 1687 | if (this.dateWindow_) { |
| 1688 | range = [this.dateWindow_[0], this.dateWindow_[1]]; |
| 1689 | } else { |
| 1690 | range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]]; |
| 1691 | } |
| 1692 | |
| 1693 | var formatter = this.attr_('xTicker'); |
| 1694 | var ret = formatter(range[0], range[1], this); |
| 1695 | var xTicks = []; |
| 1696 | |
| 1697 | if (ret.ticks !== undefined) { |
| 1698 | // numericTicks() returns multiple values. |
| 1699 | xTicks = ret.ticks; |
| 1700 | this.numXDigits_ = ret.numDigits; |
| 1701 | } else { |
| 1702 | xTicks = ret; |
| 1703 | } |
| 1704 | |
| 1705 | this.layout_.updateOptions({xTicks: xTicks}); |
| 1706 | }; |
| 1707 | |
| 1708 | // Time granularity enumeration |
| 1709 | Dygraph.SECONDLY = 0; |
| 1710 | Dygraph.TWO_SECONDLY = 1; |
| 1711 | Dygraph.FIVE_SECONDLY = 2; |
| 1712 | Dygraph.TEN_SECONDLY = 3; |
| 1713 | Dygraph.THIRTY_SECONDLY = 4; |
| 1714 | Dygraph.MINUTELY = 5; |
| 1715 | Dygraph.TWO_MINUTELY = 6; |
| 1716 | Dygraph.FIVE_MINUTELY = 7; |
| 1717 | Dygraph.TEN_MINUTELY = 8; |
| 1718 | Dygraph.THIRTY_MINUTELY = 9; |
| 1719 | Dygraph.HOURLY = 10; |
| 1720 | Dygraph.TWO_HOURLY = 11; |
| 1721 | Dygraph.SIX_HOURLY = 12; |
| 1722 | Dygraph.DAILY = 13; |
| 1723 | Dygraph.WEEKLY = 14; |
| 1724 | Dygraph.MONTHLY = 15; |
| 1725 | Dygraph.QUARTERLY = 16; |
| 1726 | Dygraph.BIANNUAL = 17; |
| 1727 | Dygraph.ANNUAL = 18; |
| 1728 | Dygraph.DECADAL = 19; |
| 1729 | Dygraph.CENTENNIAL = 20; |
| 1730 | Dygraph.NUM_GRANULARITIES = 21; |
| 1731 | |
| 1732 | Dygraph.SHORT_SPACINGS = []; |
| 1733 | Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1; |
| 1734 | Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2; |
| 1735 | Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5; |
| 1736 | Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10; |
| 1737 | Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30; |
| 1738 | Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60; |
| 1739 | Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2; |
| 1740 | Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5; |
| 1741 | Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10; |
| 1742 | Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30; |
| 1743 | Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600; |
| 1744 | Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2; |
| 1745 | Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6; |
| 1746 | Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400; |
| 1747 | Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800; |
| 1748 | |
| 1749 | // NumXTicks() |
| 1750 | // |
| 1751 | // If we used this time granularity, how many ticks would there be? |
| 1752 | // This is only an approximation, but it's generally good enough. |
| 1753 | // |
| 1754 | Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) { |
| 1755 | if (granularity < Dygraph.MONTHLY) { |
| 1756 | // Generate one tick mark for every fixed interval of time. |
| 1757 | var spacing = Dygraph.SHORT_SPACINGS[granularity]; |
| 1758 | return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing); |
| 1759 | } else { |
| 1760 | var year_mod = 1; // e.g. to only print one point every 10 years. |
| 1761 | var num_months = 12; |
| 1762 | if (granularity == Dygraph.QUARTERLY) num_months = 3; |
| 1763 | if (granularity == Dygraph.BIANNUAL) num_months = 2; |
| 1764 | if (granularity == Dygraph.ANNUAL) num_months = 1; |
| 1765 | if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; } |
| 1766 | if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; } |
| 1767 | |
| 1768 | var msInYear = 365.2524 * 24 * 3600 * 1000; |
| 1769 | var num_years = 1.0 * (end_time - start_time) / msInYear; |
| 1770 | return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod); |
| 1771 | } |
| 1772 | }; |
| 1773 | |
| 1774 | // GetXAxis() |
| 1775 | // |
| 1776 | // Construct an x-axis of nicely-formatted times on meaningful boundaries |
| 1777 | // (e.g. 'Jan 09' rather than 'Jan 22, 2009'). |
| 1778 | // |
| 1779 | // Returns an array containing {v: millis, label: label} dictionaries. |
| 1780 | // |
| 1781 | Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) { |
| 1782 | var formatter = this.attr_("xAxisLabelFormatter"); |
| 1783 | var ticks = []; |
| 1784 | if (granularity < Dygraph.MONTHLY) { |
| 1785 | // Generate one tick mark for every fixed interval of time. |
| 1786 | var spacing = Dygraph.SHORT_SPACINGS[granularity]; |
| 1787 | var format = '%d%b'; // e.g. "1Jan" |
| 1788 | |
| 1789 | // Find a time less than start_time which occurs on a "nice" time boundary |
| 1790 | // for this granularity. |
| 1791 | var g = spacing / 1000; |
| 1792 | var d = new Date(start_time); |
| 1793 | if (g <= 60) { // seconds |
| 1794 | var x = d.getSeconds(); d.setSeconds(x - x % g); |
| 1795 | } else { |
| 1796 | d.setSeconds(0); |
| 1797 | g /= 60; |
| 1798 | if (g <= 60) { // minutes |
| 1799 | var x = d.getMinutes(); d.setMinutes(x - x % g); |
| 1800 | } else { |
| 1801 | d.setMinutes(0); |
| 1802 | g /= 60; |
| 1803 | |
| 1804 | if (g <= 24) { // days |
| 1805 | var x = d.getHours(); d.setHours(x - x % g); |
| 1806 | } else { |
| 1807 | d.setHours(0); |
| 1808 | g /= 24; |
| 1809 | |
| 1810 | if (g == 7) { // one week |
| 1811 | d.setDate(d.getDate() - d.getDay()); |
| 1812 | } |
| 1813 | } |
| 1814 | } |
| 1815 | } |
| 1816 | start_time = d.getTime(); |
| 1817 | |
| 1818 | for (var t = start_time; t <= end_time; t += spacing) { |
| 1819 | ticks.push({ v:t, label: formatter(new Date(t), granularity) }); |
| 1820 | } |
| 1821 | } else { |
| 1822 | // Display a tick mark on the first of a set of months of each year. |
| 1823 | // Years get a tick mark iff y % year_mod == 0. This is useful for |
| 1824 | // displaying a tick mark once every 10 years, say, on long time scales. |
| 1825 | var months; |
| 1826 | var year_mod = 1; // e.g. to only print one point every 10 years. |
| 1827 | |
| 1828 | if (granularity == Dygraph.MONTHLY) { |
| 1829 | months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]; |
| 1830 | } else if (granularity == Dygraph.QUARTERLY) { |
| 1831 | months = [ 0, 3, 6, 9 ]; |
| 1832 | } else if (granularity == Dygraph.BIANNUAL) { |
| 1833 | months = [ 0, 6 ]; |
| 1834 | } else if (granularity == Dygraph.ANNUAL) { |
| 1835 | months = [ 0 ]; |
| 1836 | } else if (granularity == Dygraph.DECADAL) { |
| 1837 | months = [ 0 ]; |
| 1838 | year_mod = 10; |
| 1839 | } else if (granularity == Dygraph.CENTENNIAL) { |
| 1840 | months = [ 0 ]; |
| 1841 | year_mod = 100; |
| 1842 | } else { |
| 1843 | this.warn("Span of dates is too long"); |
| 1844 | } |
| 1845 | |
| 1846 | var start_year = new Date(start_time).getFullYear(); |
| 1847 | var end_year = new Date(end_time).getFullYear(); |
| 1848 | var zeropad = Dygraph.zeropad; |
| 1849 | for (var i = start_year; i <= end_year; i++) { |
| 1850 | if (i % year_mod != 0) continue; |
| 1851 | for (var j = 0; j < months.length; j++) { |
| 1852 | var date_str = i + "/" + zeropad(1 + months[j]) + "/01"; |
| 1853 | var t = Date.parse(date_str); |
| 1854 | if (t < start_time || t > end_time) continue; |
| 1855 | ticks.push({ v:t, label: formatter(new Date(t), granularity) }); |
| 1856 | } |
| 1857 | } |
| 1858 | } |
| 1859 | |
| 1860 | return ticks; |
| 1861 | }; |
| 1862 | |
| 1863 | |
| 1864 | /** |
| 1865 | * Add ticks to the x-axis based on a date range. |
| 1866 | * @param {Number} startDate Start of the date window (millis since epoch) |
| 1867 | * @param {Number} endDate End of the date window (millis since epoch) |
| 1868 | * @return {Array.<Object>} Array of {label, value} tuples. |
| 1869 | * @public |
| 1870 | */ |
| 1871 | Dygraph.dateTicker = function(startDate, endDate, self) { |
| 1872 | var chosen = -1; |
| 1873 | for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) { |
| 1874 | var num_ticks = self.NumXTicks(startDate, endDate, i); |
| 1875 | if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) { |
| 1876 | chosen = i; |
| 1877 | break; |
| 1878 | } |
| 1879 | } |
| 1880 | |
| 1881 | if (chosen >= 0) { |
| 1882 | return self.GetXAxis(startDate, endDate, chosen); |
| 1883 | } else { |
| 1884 | // TODO(danvk): signal error. |
| 1885 | } |
| 1886 | }; |
| 1887 | |
| 1888 | /** |
| 1889 | * Determine the number of significant figures in a Number up to the specified |
| 1890 | * precision. Note that there is no way to determine if a trailing '0' is |
| 1891 | * significant or not, so by convention we return 1 for all of the following |
| 1892 | * inputs: 1, 1.0, 1.00, 1.000 etc. |
| 1893 | * @param {Number} x The input value. |
| 1894 | * @param {Number} opt_maxPrecision Optional maximum precision to consider. |
| 1895 | * Default and maximum allowed value is 13. |
| 1896 | * @return {Number} The number of significant figures which is >= 1. |
| 1897 | */ |
| 1898 | Dygraph.significantFigures = function(x, opt_maxPrecision) { |
| 1899 | var precision = Math.max(opt_maxPrecision || 13, 13); |
| 1900 | |
| 1901 | // Convert the number to its exponential notation form and work backwards, |
| 1902 | // ignoring the 'e+xx' bit. This may seem like a hack, but doing a loop and |
| 1903 | // dividing by 10 leads to roundoff errors. By using toExponential(), we let |
| 1904 | // the JavaScript interpreter handle the low level bits of the Number for us. |
| 1905 | var s = x.toExponential(precision); |
| 1906 | var ePos = s.lastIndexOf('e'); // -1 case handled by return below. |
| 1907 | |
| 1908 | for (var i = ePos - 1; i >= 0; i--) { |
| 1909 | if (s[i] == '.') { |
| 1910 | // Got to the decimal place. We'll call this 1 digit of precision because |
| 1911 | // we can't know for sure how many trailing 0s are significant. |
| 1912 | return 1; |
| 1913 | } else if (s[i] != '0') { |
| 1914 | // Found the first non-zero digit. Return the number of characters |
| 1915 | // except for the '.'. |
| 1916 | return i; // This is i - 1 + 1 (-1 is for '.', +1 is for 0 based index). |
| 1917 | } |
| 1918 | } |
| 1919 | |
| 1920 | // Occurs if toExponential() doesn't return a string containing 'e', which |
| 1921 | // should never happen. |
| 1922 | return 1; |
| 1923 | }; |
| 1924 | |
| 1925 | /** |
| 1926 | * Add ticks when the x axis has numbers on it (instead of dates) |
| 1927 | * @param {Number} startDate Start of the date window (millis since epoch) |
| 1928 | * @param {Number} endDate End of the date window (millis since epoch) |
| 1929 | * @param self |
| 1930 | * @param {function} attribute accessor function. |
| 1931 | * @return {Array.<Object>} Array of {label, value} tuples. |
| 1932 | * @public |
| 1933 | */ |
| 1934 | Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) { |
| 1935 | var attr = function(k) { |
| 1936 | if (axis_props && axis_props.hasOwnProperty(k)) return axis_props[k]; |
| 1937 | return self.attr_(k); |
| 1938 | }; |
| 1939 | |
| 1940 | var ticks = []; |
| 1941 | if (vals) { |
| 1942 | for (var i = 0; i < vals.length; i++) { |
| 1943 | ticks[i].push({v: vals[i]}); |
| 1944 | } |
| 1945 | } else { |
| 1946 | // Basic idea: |
| 1947 | // Try labels every 1, 2, 5, 10, 20, 50, 100, etc. |
| 1948 | // Calculate the resulting tick spacing (i.e. this.height_ / nTicks). |
| 1949 | // The first spacing greater than pixelsPerYLabel is what we use. |
| 1950 | // TODO(danvk): version that works on a log scale. |
| 1951 | if (attr("labelsKMG2")) { |
| 1952 | var mults = [1, 2, 4, 8]; |
| 1953 | } else { |
| 1954 | var mults = [1, 2, 5]; |
| 1955 | } |
| 1956 | var scale, low_val, high_val, nTicks; |
| 1957 | // TODO(danvk): make it possible to set this for x- and y-axes independently. |
| 1958 | var pixelsPerTick = attr('pixelsPerYLabel'); |
| 1959 | for (var i = -10; i < 50; i++) { |
| 1960 | if (attr("labelsKMG2")) { |
| 1961 | var base_scale = Math.pow(16, i); |
| 1962 | } else { |
| 1963 | var base_scale = Math.pow(10, i); |
| 1964 | } |
| 1965 | for (var j = 0; j < mults.length; j++) { |
| 1966 | scale = base_scale * mults[j]; |
| 1967 | low_val = Math.floor(minV / scale) * scale; |
| 1968 | high_val = Math.ceil(maxV / scale) * scale; |
| 1969 | nTicks = Math.abs(high_val - low_val) / scale; |
| 1970 | var spacing = self.height_ / nTicks; |
| 1971 | // wish I could break out of both loops at once... |
| 1972 | if (spacing > pixelsPerTick) break; |
| 1973 | } |
| 1974 | if (spacing > pixelsPerTick) break; |
| 1975 | } |
| 1976 | |
| 1977 | // Construct the set of ticks. |
| 1978 | // Allow reverse y-axis if it's explicitly requested. |
| 1979 | if (low_val > high_val) scale *= -1; |
| 1980 | for (var i = 0; i < nTicks; i++) { |
| 1981 | var tickV = low_val + i * scale; |
| 1982 | ticks.push( {v: tickV} ); |
| 1983 | } |
| 1984 | } |
| 1985 | |
| 1986 | // Add formatted labels to the ticks. |
| 1987 | var k; |
| 1988 | var k_labels = []; |
| 1989 | if (attr("labelsKMB")) { |
| 1990 | k = 1000; |
| 1991 | k_labels = [ "K", "M", "B", "T" ]; |
| 1992 | } |
| 1993 | if (attr("labelsKMG2")) { |
| 1994 | if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!"); |
| 1995 | k = 1024; |
| 1996 | k_labels = [ "k", "M", "G", "T" ]; |
| 1997 | } |
| 1998 | var formatter = attr('yAxisLabelFormatter') ? |
| 1999 | attr('yAxisLabelFormatter') : attr('yValueFormatter'); |
| 2000 | |
| 2001 | // Determine the number of decimal places needed for the labels below by |
| 2002 | // taking the maximum number of significant figures for any label. We must |
| 2003 | // take the max because we can't tell if trailing 0s are significant. |
| 2004 | var numDigits = 0; |
| 2005 | for (var i = 0; i < ticks.length; i++) { |
| 2006 | numDigits = Math.max(Dygraph.significantFigures(ticks[i].v), numDigits); |
| 2007 | } |
| 2008 | |
| 2009 | for (var i = 0; i < ticks.length; i++) { |
| 2010 | var tickV = ticks[i].v; |
| 2011 | var absTickV = Math.abs(tickV); |
| 2012 | var label = (formatter !== undefined) ? |
| 2013 | formatter(tickV, numDigits) : tickV.toPrecision(numDigits); |
| 2014 | if (k_labels.length > 0) { |
| 2015 | // Round up to an appropriate unit. |
| 2016 | var n = k*k*k*k; |
| 2017 | for (var j = 3; j >= 0; j--, n /= k) { |
| 2018 | if (absTickV >= n) { |
| 2019 | label = (tickV / n).toPrecision(numDigits) + k_labels[j]; |
| 2020 | break; |
| 2021 | } |
| 2022 | } |
| 2023 | } |
| 2024 | ticks[i].label = label; |
| 2025 | } |
| 2026 | return {ticks: ticks, numDigits: numDigits}; |
| 2027 | }; |
| 2028 | |
| 2029 | // Computes the range of the data series (including confidence intervals). |
| 2030 | // series is either [ [x1, y1], [x2, y2], ... ] or |
| 2031 | // [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ... |
| 2032 | // Returns [low, high] |
| 2033 | Dygraph.prototype.extremeValues_ = function(series) { |
| 2034 | var minY = null, maxY = null; |
| 2035 | |
| 2036 | var bars = this.attr_("errorBars") || this.attr_("customBars"); |
| 2037 | if (bars) { |
| 2038 | // With custom bars, maxY is the max of the high values. |
| 2039 | for (var j = 0; j < series.length; j++) { |
| 2040 | var y = series[j][1][0]; |
| 2041 | if (!y) continue; |
| 2042 | var low = y - series[j][1][1]; |
| 2043 | var high = y + series[j][1][2]; |
| 2044 | if (low > y) low = y; // this can happen with custom bars, |
| 2045 | if (high < y) high = y; // e.g. in tests/custom-bars.html |
| 2046 | if (maxY == null || high > maxY) { |
| 2047 | maxY = high; |
| 2048 | } |
| 2049 | if (minY == null || low < minY) { |
| 2050 | minY = low; |
| 2051 | } |
| 2052 | } |
| 2053 | } else { |
| 2054 | for (var j = 0; j < series.length; j++) { |
| 2055 | var y = series[j][1]; |
| 2056 | if (y === null || isNaN(y)) continue; |
| 2057 | if (maxY == null || y > maxY) { |
| 2058 | maxY = y; |
| 2059 | } |
| 2060 | if (minY == null || y < minY) { |
| 2061 | minY = y; |
| 2062 | } |
| 2063 | } |
| 2064 | } |
| 2065 | |
| 2066 | return [minY, maxY]; |
| 2067 | }; |
| 2068 | |
| 2069 | /** |
| 2070 | * This function is called once when the chart's data is changed or the options |
| 2071 | * dictionary is updated. It is _not_ called when the user pans or zooms. The |
| 2072 | * idea is that values derived from the chart's data can be computed here, |
| 2073 | * rather than every time the chart is drawn. This includes things like the |
| 2074 | * number of axes, rolling averages, etc. |
| 2075 | */ |
| 2076 | Dygraph.prototype.predraw_ = function() { |
| 2077 | // TODO(danvk): move more computations out of drawGraph_ and into here. |
| 2078 | this.computeYAxes_(); |
| 2079 | |
| 2080 | // Create a new plotter. |
| 2081 | if (this.plotter_) this.plotter_.clear(); |
| 2082 | this.plotter_ = new DygraphCanvasRenderer(this, |
| 2083 | this.hidden_, this.layout_, |
| 2084 | this.renderOptions_); |
| 2085 | |
| 2086 | // The roller sits in the bottom left corner of the chart. We don't know where |
| 2087 | // this will be until the options are available, so it's positioned here. |
| 2088 | this.createRollInterface_(); |
| 2089 | |
| 2090 | // Same thing applies for the labelsDiv. It's right edge should be flush with |
| 2091 | // the right edge of the charting area (which may not be the same as the right |
| 2092 | // edge of the div, if we have two y-axes. |
| 2093 | this.positionLabelsDiv_(); |
| 2094 | |
| 2095 | // If the data or options have changed, then we'd better redraw. |
| 2096 | this.drawGraph_(); |
| 2097 | }; |
| 2098 | |
| 2099 | /** |
| 2100 | ======= |
| 2101 | * Update the graph with new data. This method is called when the viewing area |
| 2102 | * has changed. If the underlying data or options have changed, predraw_ will |
| 2103 | * be called before drawGraph_ is called. |
| 2104 | * @private |
| 2105 | */ |
| 2106 | Dygraph.prototype.drawGraph_ = function() { |
| 2107 | var data = this.rawData_; |
| 2108 | |
| 2109 | // This is used to set the second parameter to drawCallback, below. |
| 2110 | var is_initial_draw = this.is_initial_draw_; |
| 2111 | this.is_initial_draw_ = false; |
| 2112 | |
| 2113 | var minY = null, maxY = null; |
| 2114 | this.layout_.removeAllDatasets(); |
| 2115 | this.setColors_(); |
| 2116 | this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize'); |
| 2117 | |
| 2118 | // Loop over the fields (series). Go from the last to the first, |
| 2119 | // because if they're stacked that's how we accumulate the values. |
| 2120 | |
| 2121 | var cumulative_y = []; // For stacked series. |
| 2122 | var datasets = []; |
| 2123 | |
| 2124 | var extremes = {}; // series name -> [low, high] |
| 2125 | |
| 2126 | // Loop over all fields and create datasets |
| 2127 | for (var i = data[0].length - 1; i >= 1; i--) { |
| 2128 | if (!this.visibility()[i - 1]) continue; |
| 2129 | |
| 2130 | var seriesName = this.attr_("labels")[i]; |
| 2131 | var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i); |
| 2132 | |
| 2133 | var series = []; |
| 2134 | for (var j = 0; j < data.length; j++) { |
| 2135 | if (data[j][i] != null || !connectSeparatedPoints) { |
| 2136 | var date = data[j][0]; |
| 2137 | series.push([date, data[j][i]]); |
| 2138 | } |
| 2139 | } |
| 2140 | |
| 2141 | // TODO(danvk): move this into predraw_. It's insane to do it here. |
| 2142 | series = this.rollingAverage(series, this.rollPeriod_); |
| 2143 | |
| 2144 | // Prune down to the desired range, if necessary (for zooming) |
| 2145 | // Because there can be lines going to points outside of the visible area, |
| 2146 | // we actually prune to visible points, plus one on either side. |
| 2147 | var bars = this.attr_("errorBars") || this.attr_("customBars"); |
| 2148 | if (this.dateWindow_) { |
| 2149 | var low = this.dateWindow_[0]; |
| 2150 | var high= this.dateWindow_[1]; |
| 2151 | var pruned = []; |
| 2152 | // TODO(danvk): do binary search instead of linear search. |
| 2153 | // TODO(danvk): pass firstIdx and lastIdx directly to the renderer. |
| 2154 | var firstIdx = null, lastIdx = null; |
| 2155 | for (var k = 0; k < series.length; k++) { |
| 2156 | if (series[k][0] >= low && firstIdx === null) { |
| 2157 | firstIdx = k; |
| 2158 | } |
| 2159 | if (series[k][0] <= high) { |
| 2160 | lastIdx = k; |
| 2161 | } |
| 2162 | } |
| 2163 | if (firstIdx === null) firstIdx = 0; |
| 2164 | if (firstIdx > 0) firstIdx--; |
| 2165 | if (lastIdx === null) lastIdx = series.length - 1; |
| 2166 | if (lastIdx < series.length - 1) lastIdx++; |
| 2167 | this.boundaryIds_[i-1] = [firstIdx, lastIdx]; |
| 2168 | for (var k = firstIdx; k <= lastIdx; k++) { |
| 2169 | pruned.push(series[k]); |
| 2170 | } |
| 2171 | series = pruned; |
| 2172 | } else { |
| 2173 | this.boundaryIds_[i-1] = [0, series.length-1]; |
| 2174 | } |
| 2175 | |
| 2176 | var seriesExtremes = this.extremeValues_(series); |
| 2177 | |
| 2178 | if (bars) { |
| 2179 | for (var j=0; j<series.length; j++) { |
| 2180 | val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]]; |
| 2181 | series[j] = val; |
| 2182 | } |
| 2183 | } else if (this.attr_("stackedGraph")) { |
| 2184 | var l = series.length; |
| 2185 | var actual_y; |
| 2186 | for (var j = 0; j < l; j++) { |
| 2187 | // If one data set has a NaN, let all subsequent stacked |
| 2188 | // sets inherit the NaN -- only start at 0 for the first set. |
| 2189 | var x = series[j][0]; |
| 2190 | if (cumulative_y[x] === undefined) { |
| 2191 | cumulative_y[x] = 0; |
| 2192 | } |
| 2193 | |
| 2194 | actual_y = series[j][1]; |
| 2195 | cumulative_y[x] += actual_y; |
| 2196 | |
| 2197 | series[j] = [x, cumulative_y[x]] |
| 2198 | |
| 2199 | if (cumulative_y[x] > seriesExtremes[1]) { |
| 2200 | seriesExtremes[1] = cumulative_y[x]; |
| 2201 | } |
| 2202 | if (cumulative_y[x] < seriesExtremes[0]) { |
| 2203 | seriesExtremes[0] = cumulative_y[x]; |
| 2204 | } |
| 2205 | } |
| 2206 | } |
| 2207 | extremes[seriesName] = seriesExtremes; |
| 2208 | |
| 2209 | datasets[i] = series; |
| 2210 | } |
| 2211 | |
| 2212 | for (var i = 1; i < datasets.length; i++) { |
| 2213 | if (!this.visibility()[i - 1]) continue; |
| 2214 | this.layout_.addDataset(this.attr_("labels")[i], datasets[i]); |
| 2215 | } |
| 2216 | |
| 2217 | this.computeYAxisRanges_(extremes); |
| 2218 | this.layout_.updateOptions( { yAxes: this.axes_, |
| 2219 | seriesToAxisMap: this.seriesToAxisMap_ |
| 2220 | } ); |
| 2221 | |
| 2222 | this.addXTicks_(); |
| 2223 | |
| 2224 | // Tell PlotKit to use this new data and render itself |
| 2225 | this.layout_.updateOptions({dateWindow: this.dateWindow_}); |
| 2226 | this.layout_.evaluateWithError(); |
| 2227 | this.plotter_.clear(); |
| 2228 | this.plotter_.render(); |
| 2229 | this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width, |
| 2230 | this.canvas_.height); |
| 2231 | |
| 2232 | if (this.attr_("drawCallback") !== null) { |
| 2233 | this.attr_("drawCallback")(this, is_initial_draw); |
| 2234 | } |
| 2235 | }; |
| 2236 | |
| 2237 | /** |
| 2238 | * Determine properties of the y-axes which are independent of the data |
| 2239 | * currently being displayed. This includes things like the number of axes and |
| 2240 | * the style of the axes. It does not include the range of each axis and its |
| 2241 | * tick marks. |
| 2242 | * This fills in this.axes_ and this.seriesToAxisMap_. |
| 2243 | * axes_ = [ { options } ] |
| 2244 | * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... } |
| 2245 | * indices are into the axes_ array. |
| 2246 | */ |
| 2247 | Dygraph.prototype.computeYAxes_ = function() { |
| 2248 | this.axes_ = [{}]; // always have at least one y-axis. |
| 2249 | this.seriesToAxisMap_ = {}; |
| 2250 | |
| 2251 | // Get a list of series names. |
| 2252 | var labels = this.attr_("labels"); |
| 2253 | var series = {}; |
| 2254 | for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1); |
| 2255 | |
| 2256 | // all options which could be applied per-axis: |
| 2257 | var axisOptions = [ |
| 2258 | 'includeZero', |
| 2259 | 'valueRange', |
| 2260 | 'labelsKMB', |
| 2261 | 'labelsKMG2', |
| 2262 | 'pixelsPerYLabel', |
| 2263 | 'yAxisLabelWidth', |
| 2264 | 'axisLabelFontSize', |
| 2265 | 'axisTickSize' |
| 2266 | ]; |
| 2267 | |
| 2268 | // Copy global axis options over to the first axis. |
| 2269 | for (var i = 0; i < axisOptions.length; i++) { |
| 2270 | var k = axisOptions[i]; |
| 2271 | var v = this.attr_(k); |
| 2272 | if (v) this.axes_[0][k] = v; |
| 2273 | } |
| 2274 | |
| 2275 | // Go through once and add all the axes. |
| 2276 | for (var seriesName in series) { |
| 2277 | if (!series.hasOwnProperty(seriesName)) continue; |
| 2278 | var axis = this.attr_("axis", seriesName); |
| 2279 | if (axis == null) { |
| 2280 | this.seriesToAxisMap_[seriesName] = 0; |
| 2281 | continue; |
| 2282 | } |
| 2283 | if (typeof(axis) == 'object') { |
| 2284 | // Add a new axis, making a copy of its per-axis options. |
| 2285 | var opts = {}; |
| 2286 | Dygraph.update(opts, this.axes_[0]); |
| 2287 | Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this. |
| 2288 | Dygraph.update(opts, axis); |
| 2289 | this.axes_.push(opts); |
| 2290 | this.seriesToAxisMap_[seriesName] = this.axes_.length - 1; |
| 2291 | } |
| 2292 | } |
| 2293 | |
| 2294 | // Go through one more time and assign series to an axis defined by another |
| 2295 | // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } } |
| 2296 | for (var seriesName in series) { |
| 2297 | if (!series.hasOwnProperty(seriesName)) continue; |
| 2298 | var axis = this.attr_("axis", seriesName); |
| 2299 | if (typeof(axis) == 'string') { |
| 2300 | if (!this.seriesToAxisMap_.hasOwnProperty(axis)) { |
| 2301 | this.error("Series " + seriesName + " wants to share a y-axis with " + |
| 2302 | "series " + axis + ", which does not define its own axis."); |
| 2303 | return null; |
| 2304 | } |
| 2305 | var idx = this.seriesToAxisMap_[axis]; |
| 2306 | this.seriesToAxisMap_[seriesName] = idx; |
| 2307 | } |
| 2308 | } |
| 2309 | |
| 2310 | // Now we remove series from seriesToAxisMap_ which are not visible. We do |
| 2311 | // this last so that hiding the first series doesn't destroy the axis |
| 2312 | // properties of the primary axis. |
| 2313 | var seriesToAxisFiltered = {}; |
| 2314 | var vis = this.visibility(); |
| 2315 | for (var i = 1; i < labels.length; i++) { |
| 2316 | var s = labels[i]; |
| 2317 | if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s]; |
| 2318 | } |
| 2319 | this.seriesToAxisMap_ = seriesToAxisFiltered; |
| 2320 | }; |
| 2321 | |
| 2322 | /** |
| 2323 | * Returns the number of y-axes on the chart. |
| 2324 | * @return {Number} the number of axes. |
| 2325 | */ |
| 2326 | Dygraph.prototype.numAxes = function() { |
| 2327 | var last_axis = 0; |
| 2328 | for (var series in this.seriesToAxisMap_) { |
| 2329 | if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue; |
| 2330 | var idx = this.seriesToAxisMap_[series]; |
| 2331 | if (idx > last_axis) last_axis = idx; |
| 2332 | } |
| 2333 | return 1 + last_axis; |
| 2334 | }; |
| 2335 | |
| 2336 | /** |
| 2337 | * Determine the value range and tick marks for each axis. |
| 2338 | * @param {Object} extremes A mapping from seriesName -> [low, high] |
| 2339 | * This fills in the valueRange and ticks fields in each entry of this.axes_. |
| 2340 | */ |
| 2341 | Dygraph.prototype.computeYAxisRanges_ = function(extremes) { |
| 2342 | // Build a map from axis number -> [list of series names] |
| 2343 | var seriesForAxis = []; |
| 2344 | for (var series in this.seriesToAxisMap_) { |
| 2345 | if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue; |
| 2346 | var idx = this.seriesToAxisMap_[series]; |
| 2347 | while (seriesForAxis.length <= idx) seriesForAxis.push([]); |
| 2348 | seriesForAxis[idx].push(series); |
| 2349 | } |
| 2350 | |
| 2351 | // Compute extreme values, a span and tick marks for each axis. |
| 2352 | for (var i = 0; i < this.axes_.length; i++) { |
| 2353 | var axis = this.axes_[i]; |
| 2354 | if (axis.valueWindow) { |
| 2355 | // This is only set if the user has zoomed on the y-axis. It is never set |
| 2356 | // by a user. It takes precedence over axis.valueRange because, if you set |
| 2357 | // valueRange, you'd still expect to be able to pan. |
| 2358 | axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]]; |
| 2359 | } else if (axis.valueRange) { |
| 2360 | // This is a user-set value range for this axis. |
| 2361 | axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]]; |
| 2362 | } else { |
| 2363 | // Calculate the extremes of extremes. |
| 2364 | var series = seriesForAxis[i]; |
| 2365 | var minY = Infinity; // extremes[series[0]][0]; |
| 2366 | var maxY = -Infinity; // extremes[series[0]][1]; |
| 2367 | for (var j = 0; j < series.length; j++) { |
| 2368 | minY = Math.min(extremes[series[j]][0], minY); |
| 2369 | maxY = Math.max(extremes[series[j]][1], maxY); |
| 2370 | } |
| 2371 | if (axis.includeZero && minY > 0) minY = 0; |
| 2372 | |
| 2373 | // Add some padding and round up to an integer to be human-friendly. |
| 2374 | var span = maxY - minY; |
| 2375 | // special case: if we have no sense of scale, use +/-10% of the sole value. |
| 2376 | if (span == 0) { span = maxY; } |
| 2377 | var maxAxisY = maxY + 0.1 * span; |
| 2378 | var minAxisY = minY - 0.1 * span; |
| 2379 | |
| 2380 | // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense. |
| 2381 | if (!this.attr_("avoidMinZero")) { |
| 2382 | if (minAxisY < 0 && minY >= 0) minAxisY = 0; |
| 2383 | if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0; |
| 2384 | } |
| 2385 | |
| 2386 | if (this.attr_("includeZero")) { |
| 2387 | if (maxY < 0) maxAxisY = 0; |
| 2388 | if (minY > 0) minAxisY = 0; |
| 2389 | } |
| 2390 | |
| 2391 | axis.computedValueRange = [minAxisY, maxAxisY]; |
| 2392 | } |
| 2393 | |
| 2394 | // Add ticks. By default, all axes inherit the tick positions of the |
| 2395 | // primary axis. However, if an axis is specifically marked as having |
| 2396 | // independent ticks, then that is permissible as well. |
| 2397 | if (i == 0 || axis.independentTicks) { |
| 2398 | var ret = |
| 2399 | Dygraph.numericTicks(axis.computedValueRange[0], |
| 2400 | axis.computedValueRange[1], |
| 2401 | this, |
| 2402 | axis); |
| 2403 | axis.ticks = ret.ticks; |
| 2404 | this.numYDigits_ = ret.numDigits; |
| 2405 | } else { |
| 2406 | var p_axis = this.axes_[0]; |
| 2407 | var p_ticks = p_axis.ticks; |
| 2408 | var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0]; |
| 2409 | var scale = axis.computedValueRange[1] - axis.computedValueRange[0]; |
| 2410 | var tick_values = []; |
| 2411 | for (var i = 0; i < p_ticks.length; i++) { |
| 2412 | var y_frac = (p_ticks[i].v - p_axis.computedValueRange[0]) / p_scale; |
| 2413 | var y_val = axis.computedValueRange[0] + y_frac * scale; |
| 2414 | tick_values.push(y_val); |
| 2415 | } |
| 2416 | |
| 2417 | var ret = |
| 2418 | Dygraph.numericTicks(axis.computedValueRange[0], |
| 2419 | axis.computedValueRange[1], |
| 2420 | this, axis, tick_values); |
| 2421 | axis.ticks = ret.ticks; |
| 2422 | this.numYDigits_ = ret.numDigits; |
| 2423 | } |
| 2424 | } |
| 2425 | }; |
| 2426 | |
| 2427 | /** |
| 2428 | * Calculates the rolling average of a data set. |
| 2429 | * If originalData is [label, val], rolls the average of those. |
| 2430 | * If originalData is [label, [, it's interpreted as [value, stddev] |
| 2431 | * and the roll is returned in the same form, with appropriately reduced |
| 2432 | * stddev for each value. |
| 2433 | * Note that this is where fractional input (i.e. '5/10') is converted into |
| 2434 | * decimal values. |
| 2435 | * @param {Array} originalData The data in the appropriate format (see above) |
| 2436 | * @param {Number} rollPeriod The number of points over which to average the |
| 2437 | * data |
| 2438 | */ |
| 2439 | Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) { |
| 2440 | if (originalData.length < 2) |
| 2441 | return originalData; |
| 2442 | var rollPeriod = Math.min(rollPeriod, originalData.length - 1); |
| 2443 | var rollingData = []; |
| 2444 | var sigma = this.attr_("sigma"); |
| 2445 | |
| 2446 | if (this.fractions_) { |
| 2447 | var num = 0; |
| 2448 | var den = 0; // numerator/denominator |
| 2449 | var mult = 100.0; |
| 2450 | for (var i = 0; i < originalData.length; i++) { |
| 2451 | num += originalData[i][1][0]; |
| 2452 | den += originalData[i][1][1]; |
| 2453 | if (i - rollPeriod >= 0) { |
| 2454 | num -= originalData[i - rollPeriod][1][0]; |
| 2455 | den -= originalData[i - rollPeriod][1][1]; |
| 2456 | } |
| 2457 | |
| 2458 | var date = originalData[i][0]; |
| 2459 | var value = den ? num / den : 0.0; |
| 2460 | if (this.attr_("errorBars")) { |
| 2461 | if (this.wilsonInterval_) { |
| 2462 | // For more details on this confidence interval, see: |
| 2463 | // http://en.wikipedia.org/wiki/Binomial_confidence_interval |
| 2464 | if (den) { |
| 2465 | var p = value < 0 ? 0 : value, n = den; |
| 2466 | var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n)); |
| 2467 | var denom = 1 + sigma * sigma / den; |
| 2468 | var low = (p + sigma * sigma / (2 * den) - pm) / denom; |
| 2469 | var high = (p + sigma * sigma / (2 * den) + pm) / denom; |
| 2470 | rollingData[i] = [date, |
| 2471 | [p * mult, (p - low) * mult, (high - p) * mult]]; |
| 2472 | } else { |
| 2473 | rollingData[i] = [date, [0, 0, 0]]; |
| 2474 | } |
| 2475 | } else { |
| 2476 | var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0; |
| 2477 | rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]]; |
| 2478 | } |
| 2479 | } else { |
| 2480 | rollingData[i] = [date, mult * value]; |
| 2481 | } |
| 2482 | } |
| 2483 | } else if (this.attr_("customBars")) { |
| 2484 | var low = 0; |
| 2485 | var mid = 0; |
| 2486 | var high = 0; |
| 2487 | var count = 0; |
| 2488 | for (var i = 0; i < originalData.length; i++) { |
| 2489 | var data = originalData[i][1]; |
| 2490 | var y = data[1]; |
| 2491 | rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]]; |
| 2492 | |
| 2493 | if (y != null && !isNaN(y)) { |
| 2494 | low += data[0]; |
| 2495 | mid += y; |
| 2496 | high += data[2]; |
| 2497 | count += 1; |
| 2498 | } |
| 2499 | if (i - rollPeriod >= 0) { |
| 2500 | var prev = originalData[i - rollPeriod]; |
| 2501 | if (prev[1][1] != null && !isNaN(prev[1][1])) { |
| 2502 | low -= prev[1][0]; |
| 2503 | mid -= prev[1][1]; |
| 2504 | high -= prev[1][2]; |
| 2505 | count -= 1; |
| 2506 | } |
| 2507 | } |
| 2508 | rollingData[i] = [originalData[i][0], [ 1.0 * mid / count, |
| 2509 | 1.0 * (mid - low) / count, |
| 2510 | 1.0 * (high - mid) / count ]]; |
| 2511 | } |
| 2512 | } else { |
| 2513 | // Calculate the rolling average for the first rollPeriod - 1 points where |
| 2514 | // there is not enough data to roll over the full number of points |
| 2515 | var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2); |
| 2516 | if (!this.attr_("errorBars")){ |
| 2517 | if (rollPeriod == 1) { |
| 2518 | return originalData; |
| 2519 | } |
| 2520 | |
| 2521 | for (var i = 0; i < originalData.length; i++) { |
| 2522 | var sum = 0; |
| 2523 | var num_ok = 0; |
| 2524 | for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { |
| 2525 | var y = originalData[j][1]; |
| 2526 | if (y == null || isNaN(y)) continue; |
| 2527 | num_ok++; |
| 2528 | sum += originalData[j][1]; |
| 2529 | } |
| 2530 | if (num_ok) { |
| 2531 | rollingData[i] = [originalData[i][0], sum / num_ok]; |
| 2532 | } else { |
| 2533 | rollingData[i] = [originalData[i][0], null]; |
| 2534 | } |
| 2535 | } |
| 2536 | |
| 2537 | } else { |
| 2538 | for (var i = 0; i < originalData.length; i++) { |
| 2539 | var sum = 0; |
| 2540 | var variance = 0; |
| 2541 | var num_ok = 0; |
| 2542 | for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) { |
| 2543 | var y = originalData[j][1][0]; |
| 2544 | if (y == null || isNaN(y)) continue; |
| 2545 | num_ok++; |
| 2546 | sum += originalData[j][1][0]; |
| 2547 | variance += Math.pow(originalData[j][1][1], 2); |
| 2548 | } |
| 2549 | if (num_ok) { |
| 2550 | var stddev = Math.sqrt(variance) / num_ok; |
| 2551 | rollingData[i] = [originalData[i][0], |
| 2552 | [sum / num_ok, sigma * stddev, sigma * stddev]]; |
| 2553 | } else { |
| 2554 | rollingData[i] = [originalData[i][0], [null, null, null]]; |
| 2555 | } |
| 2556 | } |
| 2557 | } |
| 2558 | } |
| 2559 | |
| 2560 | return rollingData; |
| 2561 | }; |
| 2562 | |
| 2563 | /** |
| 2564 | * Parses a date, returning the number of milliseconds since epoch. This can be |
| 2565 | * passed in as an xValueParser in the Dygraph constructor. |
| 2566 | * TODO(danvk): enumerate formats that this understands. |
| 2567 | * @param {String} A date in YYYYMMDD format. |
| 2568 | * @return {Number} Milliseconds since epoch. |
| 2569 | * @public |
| 2570 | */ |
| 2571 | Dygraph.dateParser = function(dateStr, self) { |
| 2572 | var dateStrSlashed; |
| 2573 | var d; |
| 2574 | if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12' |
| 2575 | dateStrSlashed = dateStr.replace("-", "/", "g"); |
| 2576 | while (dateStrSlashed.search("-") != -1) { |
| 2577 | dateStrSlashed = dateStrSlashed.replace("-", "/"); |
| 2578 | } |
| 2579 | d = Date.parse(dateStrSlashed); |
| 2580 | } else if (dateStr.length == 8) { // e.g. '20090712' |
| 2581 | // TODO(danvk): remove support for this format. It's confusing. |
| 2582 | dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) |
| 2583 | + "/" + dateStr.substr(6,2); |
| 2584 | d = Date.parse(dateStrSlashed); |
| 2585 | } else { |
| 2586 | // Any format that Date.parse will accept, e.g. "2009/07/12" or |
| 2587 | // "2009/07/12 12:34:56" |
| 2588 | d = Date.parse(dateStr); |
| 2589 | } |
| 2590 | |
| 2591 | if (!d || isNaN(d)) { |
| 2592 | self.error("Couldn't parse " + dateStr + " as a date"); |
| 2593 | } |
| 2594 | return d; |
| 2595 | }; |
| 2596 | |
| 2597 | /** |
| 2598 | * Detects the type of the str (date or numeric) and sets the various |
| 2599 | * formatting attributes in this.attrs_ based on this type. |
| 2600 | * @param {String} str An x value. |
| 2601 | * @private |
| 2602 | */ |
| 2603 | Dygraph.prototype.detectTypeFromString_ = function(str) { |
| 2604 | var isDate = false; |
| 2605 | if (str.indexOf('-') >= 0 || |
| 2606 | str.indexOf('/') >= 0 || |
| 2607 | isNaN(parseFloat(str))) { |
| 2608 | isDate = true; |
| 2609 | } else if (str.length == 8 && str > '19700101' && str < '20371231') { |
| 2610 | // TODO(danvk): remove support for this format. |
| 2611 | isDate = true; |
| 2612 | } |
| 2613 | |
| 2614 | if (isDate) { |
| 2615 | this.attrs_.xValueFormatter = Dygraph.dateString_; |
| 2616 | this.attrs_.xValueParser = Dygraph.dateParser; |
| 2617 | this.attrs_.xTicker = Dygraph.dateTicker; |
| 2618 | this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter; |
| 2619 | } else { |
| 2620 | this.attrs_.xValueFormatter = this.attrs_.xValueFormatter; |
| 2621 | this.attrs_.xValueParser = function(x) { return parseFloat(x); }; |
| 2622 | this.attrs_.xTicker = Dygraph.numericTicks; |
| 2623 | this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter; |
| 2624 | } |
| 2625 | }; |
| 2626 | |
| 2627 | /** |
| 2628 | * Parses a string in a special csv format. We expect a csv file where each |
| 2629 | * line is a date point, and the first field in each line is the date string. |
| 2630 | * We also expect that all remaining fields represent series. |
| 2631 | * if the errorBars attribute is set, then interpret the fields as: |
| 2632 | * date, series1, stddev1, series2, stddev2, ... |
| 2633 | * @param {Array.<Object>} data See above. |
| 2634 | * @private |
| 2635 | * |
| 2636 | * @return Array.<Object> An array with one entry for each row. These entries |
| 2637 | * are an array of cells in that row. The first entry is the parsed x-value for |
| 2638 | * the row. The second, third, etc. are the y-values. These can take on one of |
| 2639 | * three forms, depending on the CSV and constructor parameters: |
| 2640 | * 1. numeric value |
| 2641 | * 2. [ value, stddev ] |
| 2642 | * 3. [ low value, center value, high value ] |
| 2643 | */ |
| 2644 | Dygraph.prototype.parseCSV_ = function(data) { |
| 2645 | var ret = []; |
| 2646 | var lines = data.split("\n"); |
| 2647 | |
| 2648 | // Use the default delimiter or fall back to a tab if that makes sense. |
| 2649 | var delim = this.attr_('delimiter'); |
| 2650 | if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) { |
| 2651 | delim = '\t'; |
| 2652 | } |
| 2653 | |
| 2654 | var start = 0; |
| 2655 | if (this.labelsFromCSV_) { |
| 2656 | start = 1; |
| 2657 | this.attrs_.labels = lines[0].split(delim); |
| 2658 | } |
| 2659 | |
| 2660 | // Parse the x as a float or return null if it's not a number. |
| 2661 | var parseFloatOrNull = function(x) { |
| 2662 | var val = parseFloat(x); |
| 2663 | // isFinite() returns false for NaN and +/-Infinity. |
| 2664 | return isFinite(val) ? val : null; |
| 2665 | }; |
| 2666 | |
| 2667 | var xParser; |
| 2668 | var defaultParserSet = false; // attempt to auto-detect x value type |
| 2669 | var expectedCols = this.attr_("labels").length; |
| 2670 | var outOfOrder = false; |
| 2671 | for (var i = start; i < lines.length; i++) { |
| 2672 | var line = lines[i]; |
| 2673 | if (line.length == 0) continue; // skip blank lines |
| 2674 | if (line[0] == '#') continue; // skip comment lines |
| 2675 | var inFields = line.split(delim); |
| 2676 | if (inFields.length < 2) continue; |
| 2677 | |
| 2678 | var fields = []; |
| 2679 | if (!defaultParserSet) { |
| 2680 | this.detectTypeFromString_(inFields[0]); |
| 2681 | xParser = this.attr_("xValueParser"); |
| 2682 | defaultParserSet = true; |
| 2683 | } |
| 2684 | fields[0] = xParser(inFields[0], this); |
| 2685 | |
| 2686 | // If fractions are expected, parse the numbers as "A/B" |
| 2687 | if (this.fractions_) { |
| 2688 | for (var j = 1; j < inFields.length; j++) { |
| 2689 | // TODO(danvk): figure out an appropriate way to flag parse errors. |
| 2690 | var vals = inFields[j].split("/"); |
| 2691 | fields[j] = [parseFloatOrNull(vals[0]), parseFloatOrNull(vals[1])]; |
| 2692 | } |
| 2693 | } else if (this.attr_("errorBars")) { |
| 2694 | // If there are error bars, values are (value, stddev) pairs |
| 2695 | for (var j = 1; j < inFields.length; j += 2) |
| 2696 | fields[(j + 1) / 2] = [parseFloatOrNull(inFields[j]), |
| 2697 | parseFloatOrNull(inFields[j + 1])]; |
| 2698 | } else if (this.attr_("customBars")) { |
| 2699 | // Bars are a low;center;high tuple |
| 2700 | for (var j = 1; j < inFields.length; j++) { |
| 2701 | var vals = inFields[j].split(";"); |
| 2702 | fields[j] = [ parseFloatOrNull(vals[0]), |
| 2703 | parseFloatOrNull(vals[1]), |
| 2704 | parseFloatOrNull(vals[2]) ]; |
| 2705 | } |
| 2706 | } else { |
| 2707 | // Values are just numbers |
| 2708 | for (var j = 1; j < inFields.length; j++) { |
| 2709 | fields[j] = parseFloatOrNull(inFields[j]); |
| 2710 | } |
| 2711 | } |
| 2712 | if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) { |
| 2713 | outOfOrder = true; |
| 2714 | } |
| 2715 | ret.push(fields); |
| 2716 | |
| 2717 | if (fields.length != expectedCols) { |
| 2718 | this.error("Number of columns in line " + i + " (" + fields.length + |
| 2719 | ") does not agree with number of labels (" + expectedCols + |
| 2720 | ") " + line); |
| 2721 | } |
| 2722 | } |
| 2723 | |
| 2724 | if (outOfOrder) { |
| 2725 | this.warn("CSV is out of order; order it correctly to speed loading."); |
| 2726 | ret.sort(function(a,b) { return a[0] - b[0] }); |
| 2727 | } |
| 2728 | |
| 2729 | return ret; |
| 2730 | }; |
| 2731 | |
| 2732 | /** |
| 2733 | * The user has provided their data as a pre-packaged JS array. If the x values |
| 2734 | * are numeric, this is the same as dygraphs' internal format. If the x values |
| 2735 | * are dates, we need to convert them from Date objects to ms since epoch. |
| 2736 | * @param {Array.<Object>} data |
| 2737 | * @return {Array.<Object>} data with numeric x values. |
| 2738 | */ |
| 2739 | Dygraph.prototype.parseArray_ = function(data) { |
| 2740 | // Peek at the first x value to see if it's numeric. |
| 2741 | if (data.length == 0) { |
| 2742 | this.error("Can't plot empty data set"); |
| 2743 | return null; |
| 2744 | } |
| 2745 | if (data[0].length == 0) { |
| 2746 | this.error("Data set cannot contain an empty row"); |
| 2747 | return null; |
| 2748 | } |
| 2749 | |
| 2750 | if (this.attr_("labels") == null) { |
| 2751 | this.warn("Using default labels. Set labels explicitly via 'labels' " + |
| 2752 | "in the options parameter"); |
| 2753 | this.attrs_.labels = [ "X" ]; |
| 2754 | for (var i = 1; i < data[0].length; i++) { |
| 2755 | this.attrs_.labels.push("Y" + i); |
| 2756 | } |
| 2757 | } |
| 2758 | |
| 2759 | if (Dygraph.isDateLike(data[0][0])) { |
| 2760 | // Some intelligent defaults for a date x-axis. |
| 2761 | this.attrs_.xValueFormatter = Dygraph.dateString_; |
| 2762 | this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter; |
| 2763 | this.attrs_.xTicker = Dygraph.dateTicker; |
| 2764 | |
| 2765 | // Assume they're all dates. |
| 2766 | var parsedData = Dygraph.clone(data); |
| 2767 | for (var i = 0; i < data.length; i++) { |
| 2768 | if (parsedData[i].length == 0) { |
| 2769 | this.error("Row " + (1 + i) + " of data is empty"); |
| 2770 | return null; |
| 2771 | } |
| 2772 | if (parsedData[i][0] == null |
| 2773 | || typeof(parsedData[i][0].getTime) != 'function' |
| 2774 | || isNaN(parsedData[i][0].getTime())) { |
| 2775 | this.error("x value in row " + (1 + i) + " is not a Date"); |
| 2776 | return null; |
| 2777 | } |
| 2778 | parsedData[i][0] = parsedData[i][0].getTime(); |
| 2779 | } |
| 2780 | return parsedData; |
| 2781 | } else { |
| 2782 | // Some intelligent defaults for a numeric x-axis. |
| 2783 | this.attrs_.xValueFormatter = this.attrs_.yValueFormatter; |
| 2784 | this.attrs_.xTicker = Dygraph.numericTicks; |
| 2785 | return data; |
| 2786 | } |
| 2787 | }; |
| 2788 | |
| 2789 | /** |
| 2790 | * Parses a DataTable object from gviz. |
| 2791 | * The data is expected to have a first column that is either a date or a |
| 2792 | * number. All subsequent columns must be numbers. If there is a clear mismatch |
| 2793 | * between this.xValueParser_ and the type of the first column, it will be |
| 2794 | * fixed. Fills out rawData_. |
| 2795 | * @param {Array.<Object>} data See above. |
| 2796 | * @private |
| 2797 | */ |
| 2798 | Dygraph.prototype.parseDataTable_ = function(data) { |
| 2799 | var cols = data.getNumberOfColumns(); |
| 2800 | var rows = data.getNumberOfRows(); |
| 2801 | |
| 2802 | var indepType = data.getColumnType(0); |
| 2803 | if (indepType == 'date' || indepType == 'datetime') { |
| 2804 | this.attrs_.xValueFormatter = Dygraph.dateString_; |
| 2805 | this.attrs_.xValueParser = Dygraph.dateParser; |
| 2806 | this.attrs_.xTicker = Dygraph.dateTicker; |
| 2807 | this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter; |
| 2808 | } else if (indepType == 'number') { |
| 2809 | this.attrs_.xValueFormatter = this.attrs_.yValueFormatter; |
| 2810 | this.attrs_.xValueParser = function(x) { return parseFloat(x); }; |
| 2811 | this.attrs_.xTicker = Dygraph.numericTicks; |
| 2812 | this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter; |
| 2813 | } else { |
| 2814 | this.error("only 'date', 'datetime' and 'number' types are supported for " + |
| 2815 | "column 1 of DataTable input (Got '" + indepType + "')"); |
| 2816 | return null; |
| 2817 | } |
| 2818 | |
| 2819 | // Array of the column indices which contain data (and not annotations). |
| 2820 | var colIdx = []; |
| 2821 | var annotationCols = {}; // data index -> [annotation cols] |
| 2822 | var hasAnnotations = false; |
| 2823 | for (var i = 1; i < cols; i++) { |
| 2824 | var type = data.getColumnType(i); |
| 2825 | if (type == 'number') { |
| 2826 | colIdx.push(i); |
| 2827 | } else if (type == 'string' && this.attr_('displayAnnotations')) { |
| 2828 | // This is OK -- it's an annotation column. |
| 2829 | var dataIdx = colIdx[colIdx.length - 1]; |
| 2830 | if (!annotationCols.hasOwnProperty(dataIdx)) { |
| 2831 | annotationCols[dataIdx] = [i]; |
| 2832 | } else { |
| 2833 | annotationCols[dataIdx].push(i); |
| 2834 | } |
| 2835 | hasAnnotations = true; |
| 2836 | } else { |
| 2837 | this.error("Only 'number' is supported as a dependent type with Gviz." + |
| 2838 | " 'string' is only supported if displayAnnotations is true"); |
| 2839 | } |
| 2840 | } |
| 2841 | |
| 2842 | // Read column labels |
| 2843 | // TODO(danvk): add support back for errorBars |
| 2844 | var labels = [data.getColumnLabel(0)]; |
| 2845 | for (var i = 0; i < colIdx.length; i++) { |
| 2846 | labels.push(data.getColumnLabel(colIdx[i])); |
| 2847 | if (this.attr_("errorBars")) i += 1; |
| 2848 | } |
| 2849 | this.attrs_.labels = labels; |
| 2850 | cols = labels.length; |
| 2851 | |
| 2852 | var ret = []; |
| 2853 | var outOfOrder = false; |
| 2854 | var annotations = []; |
| 2855 | for (var i = 0; i < rows; i++) { |
| 2856 | var row = []; |
| 2857 | if (typeof(data.getValue(i, 0)) === 'undefined' || |
| 2858 | data.getValue(i, 0) === null) { |
| 2859 | this.warn("Ignoring row " + i + |
| 2860 | " of DataTable because of undefined or null first column."); |
| 2861 | continue; |
| 2862 | } |
| 2863 | |
| 2864 | if (indepType == 'date' || indepType == 'datetime') { |
| 2865 | row.push(data.getValue(i, 0).getTime()); |
| 2866 | } else { |
| 2867 | row.push(data.getValue(i, 0)); |
| 2868 | } |
| 2869 | if (!this.attr_("errorBars")) { |
| 2870 | for (var j = 0; j < colIdx.length; j++) { |
| 2871 | var col = colIdx[j]; |
| 2872 | row.push(data.getValue(i, col)); |
| 2873 | if (hasAnnotations && |
| 2874 | annotationCols.hasOwnProperty(col) && |
| 2875 | data.getValue(i, annotationCols[col][0]) != null) { |
| 2876 | var ann = {}; |
| 2877 | ann.series = data.getColumnLabel(col); |
| 2878 | ann.xval = row[0]; |
| 2879 | ann.shortText = String.fromCharCode(65 /* A */ + annotations.length) |
| 2880 | ann.text = ''; |
| 2881 | for (var k = 0; k < annotationCols[col].length; k++) { |
| 2882 | if (k) ann.text += "\n"; |
| 2883 | ann.text += data.getValue(i, annotationCols[col][k]); |
| 2884 | } |
| 2885 | annotations.push(ann); |
| 2886 | } |
| 2887 | } |
| 2888 | } else { |
| 2889 | for (var j = 0; j < cols - 1; j++) { |
| 2890 | row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]); |
| 2891 | } |
| 2892 | } |
| 2893 | if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) { |
| 2894 | outOfOrder = true; |
| 2895 | } |
| 2896 | |
| 2897 | // Strip out infinities, which give dygraphs problems later on. |
| 2898 | for (var j = 0; j < row.length; j++) { |
| 2899 | if (!isFinite(row[j])) row[j] = null; |
| 2900 | } |
| 2901 | ret.push(row); |
| 2902 | } |
| 2903 | |
| 2904 | if (outOfOrder) { |
| 2905 | this.warn("DataTable is out of order; order it correctly to speed loading."); |
| 2906 | ret.sort(function(a,b) { return a[0] - b[0] }); |
| 2907 | } |
| 2908 | this.rawData_ = ret; |
| 2909 | |
| 2910 | if (annotations.length > 0) { |
| 2911 | this.setAnnotations(annotations, true); |
| 2912 | } |
| 2913 | } |
| 2914 | |
| 2915 | // These functions are all based on MochiKit. |
| 2916 | Dygraph.update = function (self, o) { |
| 2917 | if (typeof(o) != 'undefined' && o !== null) { |
| 2918 | for (var k in o) { |
| 2919 | if (o.hasOwnProperty(k)) { |
| 2920 | self[k] = o[k]; |
| 2921 | } |
| 2922 | } |
| 2923 | } |
| 2924 | return self; |
| 2925 | }; |
| 2926 | |
| 2927 | Dygraph.isArrayLike = function (o) { |
| 2928 | var typ = typeof(o); |
| 2929 | if ( |
| 2930 | (typ != 'object' && !(typ == 'function' && |
| 2931 | typeof(o.item) == 'function')) || |
| 2932 | o === null || |
| 2933 | typeof(o.length) != 'number' || |
| 2934 | o.nodeType === 3 |
| 2935 | ) { |
| 2936 | return false; |
| 2937 | } |
| 2938 | return true; |
| 2939 | }; |
| 2940 | |
| 2941 | Dygraph.isDateLike = function (o) { |
| 2942 | if (typeof(o) != "object" || o === null || |
| 2943 | typeof(o.getTime) != 'function') { |
| 2944 | return false; |
| 2945 | } |
| 2946 | return true; |
| 2947 | }; |
| 2948 | |
| 2949 | Dygraph.clone = function(o) { |
| 2950 | // TODO(danvk): figure out how MochiKit's version works |
| 2951 | var r = []; |
| 2952 | for (var i = 0; i < o.length; i++) { |
| 2953 | if (Dygraph.isArrayLike(o[i])) { |
| 2954 | r.push(Dygraph.clone(o[i])); |
| 2955 | } else { |
| 2956 | r.push(o[i]); |
| 2957 | } |
| 2958 | } |
| 2959 | return r; |
| 2960 | }; |
| 2961 | |
| 2962 | |
| 2963 | /** |
| 2964 | * Get the CSV data. If it's in a function, call that function. If it's in a |
| 2965 | * file, do an XMLHttpRequest to get it. |
| 2966 | * @private |
| 2967 | */ |
| 2968 | Dygraph.prototype.start_ = function() { |
| 2969 | if (typeof this.file_ == 'function') { |
| 2970 | // CSV string. Pretend we got it via XHR. |
| 2971 | this.loadedEvent_(this.file_()); |
| 2972 | } else if (Dygraph.isArrayLike(this.file_)) { |
| 2973 | this.rawData_ = this.parseArray_(this.file_); |
| 2974 | this.predraw_(); |
| 2975 | } else if (typeof this.file_ == 'object' && |
| 2976 | typeof this.file_.getColumnRange == 'function') { |
| 2977 | // must be a DataTable from gviz. |
| 2978 | this.parseDataTable_(this.file_); |
| 2979 | this.predraw_(); |
| 2980 | } else if (typeof this.file_ == 'string') { |
| 2981 | // Heuristic: a newline means it's CSV data. Otherwise it's an URL. |
| 2982 | if (this.file_.indexOf('\n') >= 0) { |
| 2983 | this.loadedEvent_(this.file_); |
| 2984 | } else { |
| 2985 | var req = new XMLHttpRequest(); |
| 2986 | var caller = this; |
| 2987 | req.onreadystatechange = function () { |
| 2988 | if (req.readyState == 4) { |
| 2989 | if (req.status == 200) { |
| 2990 | caller.loadedEvent_(req.responseText); |
| 2991 | } |
| 2992 | } |
| 2993 | }; |
| 2994 | |
| 2995 | req.open("GET", this.file_, true); |
| 2996 | req.send(null); |
| 2997 | } |
| 2998 | } else { |
| 2999 | this.error("Unknown data format: " + (typeof this.file_)); |
| 3000 | } |
| 3001 | }; |
| 3002 | |
| 3003 | /** |
| 3004 | * Changes various properties of the graph. These can include: |
| 3005 | * <ul> |
| 3006 | * <li>file: changes the source data for the graph</li> |
| 3007 | * <li>errorBars: changes whether the data contains stddev</li> |
| 3008 | * </ul> |
| 3009 | * @param {Object} attrs The new properties and values |
| 3010 | */ |
| 3011 | Dygraph.prototype.updateOptions = function(attrs) { |
| 3012 | // TODO(danvk): this is a mess. Rethink this function. |
| 3013 | if ('rollPeriod' in attrs) { |
| 3014 | this.rollPeriod_ = attrs.rollPeriod; |
| 3015 | } |
| 3016 | if ('dateWindow' in attrs) { |
| 3017 | this.dateWindow_ = attrs.dateWindow; |
| 3018 | } |
| 3019 | |
| 3020 | // TODO(danvk): validate per-series options. |
| 3021 | // Supported: |
| 3022 | // strokeWidth |
| 3023 | // pointSize |
| 3024 | // drawPoints |
| 3025 | // highlightCircleSize |
| 3026 | |
| 3027 | Dygraph.update(this.user_attrs_, attrs); |
| 3028 | Dygraph.update(this.renderOptions_, attrs); |
| 3029 | |
| 3030 | this.labelsFromCSV_ = (this.attr_("labels") == null); |
| 3031 | |
| 3032 | // TODO(danvk): this doesn't match the constructor logic |
| 3033 | this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") }); |
| 3034 | if (attrs['file']) { |
| 3035 | this.file_ = attrs['file']; |
| 3036 | this.start_(); |
| 3037 | } else { |
| 3038 | this.predraw_(); |
| 3039 | } |
| 3040 | }; |
| 3041 | |
| 3042 | /** |
| 3043 | * Resizes the dygraph. If no parameters are specified, resizes to fill the |
| 3044 | * containing div (which has presumably changed size since the dygraph was |
| 3045 | * instantiated. If the width/height are specified, the div will be resized. |
| 3046 | * |
| 3047 | * This is far more efficient than destroying and re-instantiating a |
| 3048 | * Dygraph, since it doesn't have to reparse the underlying data. |
| 3049 | * |
| 3050 | * @param {Number} width Width (in pixels) |
| 3051 | * @param {Number} height Height (in pixels) |
| 3052 | */ |
| 3053 | Dygraph.prototype.resize = function(width, height) { |
| 3054 | if (this.resize_lock) { |
| 3055 | return; |
| 3056 | } |
| 3057 | this.resize_lock = true; |
| 3058 | |
| 3059 | if ((width === null) != (height === null)) { |
| 3060 | this.warn("Dygraph.resize() should be called with zero parameters or " + |
| 3061 | "two non-NULL parameters. Pretending it was zero."); |
| 3062 | width = height = null; |
| 3063 | } |
| 3064 | |
| 3065 | // TODO(danvk): there should be a clear() method. |
| 3066 | this.maindiv_.innerHTML = ""; |
| 3067 | this.attrs_.labelsDiv = null; |
| 3068 | |
| 3069 | if (width) { |
| 3070 | this.maindiv_.style.width = width + "px"; |
| 3071 | this.maindiv_.style.height = height + "px"; |
| 3072 | this.width_ = width; |
| 3073 | this.height_ = height; |
| 3074 | } else { |
| 3075 | this.width_ = this.maindiv_.offsetWidth; |
| 3076 | this.height_ = this.maindiv_.offsetHeight; |
| 3077 | } |
| 3078 | |
| 3079 | this.createInterface_(); |
| 3080 | this.predraw_(); |
| 3081 | |
| 3082 | this.resize_lock = false; |
| 3083 | }; |
| 3084 | |
| 3085 | /** |
| 3086 | * Adjusts the number of points in the rolling average. Updates the graph to |
| 3087 | * reflect the new averaging period. |
| 3088 | * @param {Number} length Number of points over which to average the data. |
| 3089 | */ |
| 3090 | Dygraph.prototype.adjustRoll = function(length) { |
| 3091 | this.rollPeriod_ = length; |
| 3092 | this.predraw_(); |
| 3093 | }; |
| 3094 | |
| 3095 | /** |
| 3096 | * Returns a boolean array of visibility statuses. |
| 3097 | */ |
| 3098 | Dygraph.prototype.visibility = function() { |
| 3099 | // Do lazy-initialization, so that this happens after we know the number of |
| 3100 | // data series. |
| 3101 | if (!this.attr_("visibility")) { |
| 3102 | this.attrs_["visibility"] = []; |
| 3103 | } |
| 3104 | while (this.attr_("visibility").length < this.rawData_[0].length - 1) { |
| 3105 | this.attr_("visibility").push(true); |
| 3106 | } |
| 3107 | return this.attr_("visibility"); |
| 3108 | }; |
| 3109 | |
| 3110 | /** |
| 3111 | * Changes the visiblity of a series. |
| 3112 | */ |
| 3113 | Dygraph.prototype.setVisibility = function(num, value) { |
| 3114 | var x = this.visibility(); |
| 3115 | if (num < 0 || num >= x.length) { |
| 3116 | this.warn("invalid series number in setVisibility: " + num); |
| 3117 | } else { |
| 3118 | x[num] = value; |
| 3119 | this.predraw_(); |
| 3120 | } |
| 3121 | }; |
| 3122 | |
| 3123 | /** |
| 3124 | * Update the list of annotations and redraw the chart. |
| 3125 | */ |
| 3126 | Dygraph.prototype.setAnnotations = function(ann, suppressDraw) { |
| 3127 | // Only add the annotation CSS rule once we know it will be used. |
| 3128 | Dygraph.addAnnotationRule(); |
| 3129 | this.annotations_ = ann; |
| 3130 | this.layout_.setAnnotations(this.annotations_); |
| 3131 | if (!suppressDraw) { |
| 3132 | this.predraw_(); |
| 3133 | } |
| 3134 | }; |
| 3135 | |
| 3136 | /** |
| 3137 | * Return the list of annotations. |
| 3138 | */ |
| 3139 | Dygraph.prototype.annotations = function() { |
| 3140 | return this.annotations_; |
| 3141 | }; |
| 3142 | |
| 3143 | /** |
| 3144 | * Get the index of a series (column) given its name. The first column is the |
| 3145 | * x-axis, so the data series start with index 1. |
| 3146 | */ |
| 3147 | Dygraph.prototype.indexFromSetName = function(name) { |
| 3148 | var labels = this.attr_("labels"); |
| 3149 | for (var i = 0; i < labels.length; i++) { |
| 3150 | if (labels[i] == name) return i; |
| 3151 | } |
| 3152 | return null; |
| 3153 | }; |
| 3154 | |
| 3155 | Dygraph.addAnnotationRule = function() { |
| 3156 | if (Dygraph.addedAnnotationCSS) return; |
| 3157 | |
| 3158 | var rule = "border: 1px solid black; " + |
| 3159 | "background-color: white; " + |
| 3160 | "text-align: center;"; |
| 3161 | |
| 3162 | var styleSheetElement = document.createElement("style"); |
| 3163 | styleSheetElement.type = "text/css"; |
| 3164 | document.getElementsByTagName("head")[0].appendChild(styleSheetElement); |
| 3165 | |
| 3166 | // Find the first style sheet that we can access. |
| 3167 | // We may not add a rule to a style sheet from another domain for security |
| 3168 | // reasons. This sometimes comes up when using gviz, since the Google gviz JS |
| 3169 | // adds its own style sheets from google.com. |
| 3170 | for (var i = 0; i < document.styleSheets.length; i++) { |
| 3171 | if (document.styleSheets[i].disabled) continue; |
| 3172 | var mysheet = document.styleSheets[i]; |
| 3173 | try { |
| 3174 | if (mysheet.insertRule) { // Firefox |
| 3175 | var idx = mysheet.cssRules ? mysheet.cssRules.length : 0; |
| 3176 | mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx); |
| 3177 | } else if (mysheet.addRule) { // IE |
| 3178 | mysheet.addRule(".dygraphDefaultAnnotation", rule); |
| 3179 | } |
| 3180 | Dygraph.addedAnnotationCSS = true; |
| 3181 | return; |
| 3182 | } catch(err) { |
| 3183 | // Was likely a security exception. |
| 3184 | } |
| 3185 | } |
| 3186 | |
| 3187 | this.warn("Unable to add default annotation CSS rule; display may be off."); |
| 3188 | } |
| 3189 | |
| 3190 | /** |
| 3191 | * Create a new canvas element. This is more complex than a simple |
| 3192 | * document.createElement("canvas") because of IE and excanvas. |
| 3193 | */ |
| 3194 | Dygraph.createCanvas = function() { |
| 3195 | var canvas = document.createElement("canvas"); |
| 3196 | |
| 3197 | isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); |
| 3198 | if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) { |
| 3199 | canvas = G_vmlCanvasManager.initElement(canvas); |
| 3200 | } |
| 3201 | |
| 3202 | return canvas; |
| 3203 | }; |
| 3204 | |
| 3205 | |
| 3206 | /** |
| 3207 | * A wrapper around Dygraph that implements the gviz API. |
| 3208 | * @param {Object} container The DOM object the visualization should live in. |
| 3209 | */ |
| 3210 | Dygraph.GVizChart = function(container) { |
| 3211 | this.container = container; |
| 3212 | } |
| 3213 | |
| 3214 | Dygraph.GVizChart.prototype.draw = function(data, options) { |
| 3215 | // Clear out any existing dygraph. |
| 3216 | // TODO(danvk): would it make more sense to simply redraw using the current |
| 3217 | // date_graph object? |
| 3218 | this.container.innerHTML = ''; |
| 3219 | if (typeof(this.date_graph) != 'undefined') { |
| 3220 | this.date_graph.destroy(); |
| 3221 | } |
| 3222 | |
| 3223 | this.date_graph = new Dygraph(this.container, data, options); |
| 3224 | } |
| 3225 | |
| 3226 | /** |
| 3227 | * Google charts compatible setSelection |
| 3228 | * Only row selection is supported, all points in the row will be highlighted |
| 3229 | * @param {Array} array of the selected cells |
| 3230 | * @public |
| 3231 | */ |
| 3232 | Dygraph.GVizChart.prototype.setSelection = function(selection_array) { |
| 3233 | var row = false; |
| 3234 | if (selection_array.length) { |
| 3235 | row = selection_array[0].row; |
| 3236 | } |
| 3237 | this.date_graph.setSelection(row); |
| 3238 | } |
| 3239 | |
| 3240 | /** |
| 3241 | * Google charts compatible getSelection implementation |
| 3242 | * @return {Array} array of the selected cells |
| 3243 | * @public |
| 3244 | */ |
| 3245 | Dygraph.GVizChart.prototype.getSelection = function() { |
| 3246 | var selection = []; |
| 3247 | |
| 3248 | var row = this.date_graph.getSelection(); |
| 3249 | |
| 3250 | if (row < 0) return selection; |
| 3251 | |
| 3252 | col = 1; |
| 3253 | for (var i in this.date_graph.layout_.datasets) { |
| 3254 | selection.push({row: row, column: col}); |
| 3255 | col++; |
| 3256 | } |
| 3257 | |
| 3258 | return selection; |
| 3259 | } |
| 3260 | |
| 3261 | // Older pages may still use this name. |
| 3262 | DateGraph = Dygraph; |