Skip to content
Snippets Groups Projects
dygraph-combined-dev.js 401 KiB
Newer Older
  • Learn to ignore specific revisions
  • Laura Cappelli's avatar
    Laura Cappelli committed
    4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000
          }
        }
        return 0;
      }
    };
    
    Dygraph.prototype.animateSelection_ = function(direction) {
      var totalSteps = 10;
      var millis = 30;
      if (this.fadeLevel === undefined) this.fadeLevel = 0;
      if (this.animateId === undefined) this.animateId = 0;
      var start = this.fadeLevel;
      var steps = direction < 0 ? start : totalSteps - start;
      if (steps <= 0) {
        if (this.fadeLevel) {
          this.updateSelection_(1.0);
        }
        return;
      }
    
      var thisId = ++this.animateId;
      var that = this;
      Dygraph.repeatAndCleanup(
        function(n) {
          // ignore simultaneous animations
          if (that.animateId != thisId) return;
    
          that.fadeLevel += direction;
          if (that.fadeLevel === 0) {
            that.clearSelection();
          } else {
            that.updateSelection_(that.fadeLevel / totalSteps);
          }
        },
        steps, millis, function() {});
    };
    
    /**
     * Draw dots over the selectied points in the data series. This function
     * takes care of cleanup of previously-drawn dots.
     * @private
     */
    Dygraph.prototype.updateSelection_ = function(opt_animFraction) {
      /*var defaultPrevented = */
      this.cascadeEvents_('select', {
        selectedRow: this.lastRow_,
        selectedX: this.lastx_,
        selectedPoints: this.selPoints_
      });
      // TODO(danvk): use defaultPrevented here?
    
      // Clear the previously drawn vertical, if there is one
      var i;
      var ctx = this.canvas_ctx_;
      if (this.getOption('highlightSeriesOpts')) {
        ctx.clearRect(0, 0, this.width_, this.height_);
        var alpha = 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha');
        if (alpha) {
          // Activating background fade includes an animation effect for a gradual
          // fade. TODO(klausw): make this independently configurable if it causes
          // issues? Use a shared preference to control animations?
          var animateBackgroundFade = true;
          if (animateBackgroundFade) {
            if (opt_animFraction === undefined) {
              // start a new animation
              this.animateSelection_(1);
              return;
            }
            alpha *= opt_animFraction;
          }
          ctx.fillStyle = 'rgba(255,255,255,' + alpha + ')';
          ctx.fillRect(0, 0, this.width_, this.height_);
        }
    
        // Redraw only the highlighted series in the interactive canvas (not the
        // static plot canvas, which is where series are usually drawn).
        this.plotter_._renderLineChart(this.highlightSet_, ctx);
      } else if (this.previousVerticalX_ >= 0) {
        // Determine the maximum highlight circle size.
        var maxCircleSize = 0;
        var labels = this.attr_('labels');
        for (i = 1; i < labels.length; i++) {
          var r = this.getNumericOption('highlightCircleSize', labels[i]);
          if (r > maxCircleSize) maxCircleSize = r;
        }
        var px = this.previousVerticalX_;
        ctx.clearRect(px - maxCircleSize - 1, 0,
                      2 * maxCircleSize + 2, this.height_);
      }
    
      if (this.isUsingExcanvas_ && this.currentZoomRectArgs_) {
        Dygraph.prototype.drawZoomRect_.apply(this, this.currentZoomRectArgs_);
      }
    
      if (this.selPoints_.length > 0) {
        // Draw colored circles over the center of each selected point
        var canvasx = this.selPoints_[0].canvasx;
        ctx.save();
        for (i = 0; i < this.selPoints_.length; i++) {
          var pt = this.selPoints_[i];
          if (!Dygraph.isOK(pt.canvasy)) continue;
    
          var circleSize = this.getNumericOption('highlightCircleSize', pt.name);
          var callback = this.getFunctionOption("drawHighlightPointCallback", pt.name);
          var color = this.plotter_.colors[pt.name];
          if (!callback) {
            callback = Dygraph.Circles.DEFAULT;
          }
          ctx.lineWidth = this.getNumericOption('strokeWidth', pt.name);
          ctx.strokeStyle = color;
          ctx.fillStyle = color;
          callback.call(this, this, pt.name, ctx, canvasx, pt.canvasy,
              color, circleSize, pt.idx);
        }
        ctx.restore();
    
        this.previousVerticalX_ = canvasx;
      }
    };
    
    /**
     * Manually set the selected points and display information about them in the
     * legend. The selection can be cleared using clearSelection() and queried
     * using getSelection().
     * @param {number} row Row number that should be highlighted (i.e. appear with
     * hover dots on the chart).
     * @param {seriesName} optional series name to highlight that series with the
     * the highlightSeriesOpts setting.
     * @param { locked } optional If true, keep seriesName selected when mousing
     * over the graph, disabling closest-series highlighting. Call clearSelection()
     * to unlock it.
     */
    Dygraph.prototype.setSelection = function(row, opt_seriesName, opt_locked) {
      // Extract the points we've selected
      this.selPoints_ = [];
    
      var changed = false;
      if (row !== false && row >= 0) {
        if (row != this.lastRow_) changed = true;
        this.lastRow_ = row;
        for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) {
          var points = this.layout_.points[setIdx];
          // Check if the point at the appropriate index is the point we're looking
          // for.  If it is, just use it, otherwise search the array for a point
          // in the proper place.
          var setRow = row - this.getLeftBoundary_(setIdx);
          if (setRow < points.length && points[setRow].idx == row) {
            var point = points[setRow];
            if (point.yval !== null) this.selPoints_.push(point);
          } else {
            for (var pointIdx = 0; pointIdx < points.length; ++pointIdx) {
              var point = points[pointIdx];
              if (point.idx == row) {
                if (point.yval !== null) {
                  this.selPoints_.push(point);
                }
                break;
              }
            }
          }
        }
      } else {
        if (this.lastRow_ >= 0) changed = true;
        this.lastRow_ = -1;
      }
    
      if (this.selPoints_.length) {
        this.lastx_ = this.selPoints_[0].xval;
      } else {
        this.lastx_ = -1;
      }
    
      if (opt_seriesName !== undefined) {
        if (this.highlightSet_ !== opt_seriesName) changed = true;
        this.highlightSet_ = opt_seriesName;
      }
    
      if (opt_locked !== undefined) {
        this.lockedSet_ = opt_locked;
      }
    
      if (changed) {
        this.updateSelection_(undefined);
      }
      return changed;
    };
    
    /**
     * The mouse has left the canvas. Clear out whatever artifacts remain
     * @param {Object} event the mouseout event from the browser.
     * @private
     */
    Dygraph.prototype.mouseOut_ = function(event) {
      if (this.getFunctionOption("unhighlightCallback")) {
        this.getFunctionOption("unhighlightCallback").call(this, event);
      }
    
      if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_) {
        this.clearSelection();
      }
    };
    
    /**
     * Clears the current selection (i.e. points that were highlighted by moving
     * the mouse over the chart).
     */
    Dygraph.prototype.clearSelection = function() {
      this.cascadeEvents_('deselect', {});
    
      this.lockedSet_ = false;
      // Get rid of the overlay data
      if (this.fadeLevel) {
        this.animateSelection_(-1);
        return;
      }
      this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
      this.fadeLevel = 0;
      this.selPoints_ = [];
      this.lastx_ = -1;
      this.lastRow_ = -1;
      this.highlightSet_ = null;
    };
    
    /**
     * Returns the number of the currently selected row. To get data for this row,
     * you can use the getValue method.
     * @return {number} row number, or -1 if nothing is selected
     */
    Dygraph.prototype.getSelection = function() {
      if (!this.selPoints_ || this.selPoints_.length < 1) {
        return -1;
      }
    
      for (var setIdx = 0; setIdx < this.layout_.points.length; setIdx++) {
        var points = this.layout_.points[setIdx];
        for (var row = 0; row < points.length; row++) {
          if (points[row].x == this.selPoints_[0].x) {
            return points[row].idx;
          }
        }
      }
      return -1;
    };
    
    /**
     * Returns the name of the currently-highlighted series.
     * Only available when the highlightSeriesOpts option is in use.
     */
    Dygraph.prototype.getHighlightSeries = function() {
      return this.highlightSet_;
    };
    
    /**
     * Returns true if the currently-highlighted series was locked
     * via setSelection(..., seriesName, true).
     */
    Dygraph.prototype.isSeriesLocked = function() {
      return this.lockedSet_;
    };
    
    /**
     * Fires when there's data available to be graphed.
     * @param {string} data Raw CSV data to be plotted
     * @private
     */
    Dygraph.prototype.loadedEvent_ = function(data) {
      this.rawData_ = this.parseCSV_(data);
      this.cascadeDataDidUpdateEvent_();
      this.predraw_();
    };
    
    /**
     * Add ticks on the x-axis representing years, months, quarters, weeks, or days
     * @private
     */
    Dygraph.prototype.addXTicks_ = function() {
      // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
      var range;
      if (this.dateWindow_) {
        range = [this.dateWindow_[0], this.dateWindow_[1]];
      } else {
        range = this.xAxisExtremes();
      }
    
      var xAxisOptionsView = this.optionsViewForAxis_('x');
      var xTicks = xAxisOptionsView('ticker')(
          range[0],
          range[1],
          this.plotter_.area.w,  // TODO(danvk): should be area.width
          xAxisOptionsView,
          this);
      // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
      // console.log(msg);
      this.layout_.setXTicks(xTicks);
    };
    
    /**
     * Returns the correct handler class for the currently set options.
     * @private
     */
    Dygraph.prototype.getHandlerClass_ = function() {
      var handlerClass;
      if (this.attr_('dataHandler')) {
        handlerClass =  this.attr_('dataHandler');
      } else if (this.fractions_) {
        if (this.getBooleanOption('errorBars')) {
          handlerClass = Dygraph.DataHandlers.FractionsBarsHandler;
        } else {
          handlerClass = Dygraph.DataHandlers.DefaultFractionHandler;
        }
      } else if (this.getBooleanOption('customBars')) {
        handlerClass = Dygraph.DataHandlers.CustomBarsHandler;
      } else if (this.getBooleanOption('errorBars')) {
        handlerClass = Dygraph.DataHandlers.ErrorBarsHandler;
      } else {
        handlerClass = Dygraph.DataHandlers.DefaultHandler;
      }
      return handlerClass;
    };
    
    /**
     * @private
     * This function is called once when the chart's data is changed or the options
     * dictionary is updated. It is _not_ called when the user pans or zooms. The
     * idea is that values derived from the chart's data can be computed here,
     * rather than every time the chart is drawn. This includes things like the
     * number of axes, rolling averages, etc.
     */
    Dygraph.prototype.predraw_ = function() {
      var start = new Date();
      
      // Create the correct dataHandler
      this.dataHandler_ = new (this.getHandlerClass_())();
    
      this.layout_.computePlotArea();
    
      // TODO(danvk): move more computations out of drawGraph_ and into here.
      this.computeYAxes_();
    
      if (!this.is_initial_draw_) {
        this.canvas_ctx_.restore();
        this.hidden_ctx_.restore();
      }
    
      this.canvas_ctx_.save();
      this.hidden_ctx_.save();
    
      // Create a new plotter.
      this.plotter_ = new DygraphCanvasRenderer(this,
                                                this.hidden_,
                                                this.hidden_ctx_,
                                                this.layout_);
    
      // The roller sits in the bottom left corner of the chart. We don't know where
      // this will be until the options are available, so it's positioned here.
      this.createRollInterface_();
    
      this.cascadeEvents_('predraw');
    
      // Convert the raw data (a 2D array) into the internal format and compute
      // rolling averages.
      this.rolledSeries_ = [null];  // x-axis is the first series and it's special
      for (var i = 1; i < this.numColumns(); i++) {
        // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too.
        var series = this.dataHandler_.extractSeries(this.rawData_, i, this.attributes_);
        if (this.rollPeriod_ > 1) {
          series = this.dataHandler_.rollingAverage(series, this.rollPeriod_, this.attributes_);
        }
        
        this.rolledSeries_.push(series);
      }
    
      // If the data or options have changed, then we'd better redraw.
      this.drawGraph_();
    
      // This is used to determine whether to do various animations.
      var end = new Date();
      this.drawingTimeMs_ = (end - start);
    };
    
    /**
     * Point structure.
     *
     * xval_* and yval_* are the original unscaled data values,
     * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
     * yval_stacked is the cumulative Y value used for stacking graphs,
     * and bottom/top/minus/plus are used for error bar graphs.
     *
     * @typedef {{
     *     idx: number,
     *     name: string,
     *     x: ?number,
     *     xval: ?number,
     *     y_bottom: ?number,
     *     y: ?number,
     *     y_stacked: ?number,
     *     y_top: ?number,
     *     yval_minus: ?number,
     *     yval: ?number,
     *     yval_plus: ?number,
     *     yval_stacked
     * }}
     */
    Dygraph.PointType = undefined;
    
    /**
     * Calculates point stacking for stackedGraph=true.
     *
     * For stacking purposes, interpolate or extend neighboring data across
     * NaN values based on stackedGraphNaNFill settings. This is for display
     * only, the underlying data value as shown in the legend remains NaN.
     *
     * @param {Array.<Dygraph.PointType>} points Point array for a single series.
     *     Updates each Point's yval_stacked property.
     * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
     *     values for the series seen so far. Index is the row number. Updated
     *     based on the current series's values.
     * @param {Array.<number>} seriesExtremes Min and max values, updated
     *     to reflect the stacked values.
     * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
     *     'none'.
     * @private
     */
    Dygraph.stackPoints_ = function(
        points, cumulativeYval, seriesExtremes, fillMethod) {
      var lastXval = null;
      var prevPoint = null;
      var nextPoint = null;
      var nextPointIdx = -1;
    
      // Find the next stackable point starting from the given index.
      var updateNextPoint = function(idx) {
        // If we've previously found a non-NaN point and haven't gone past it yet,
        // just use that.
        if (nextPointIdx >= idx) return;
    
        // We haven't found a non-NaN point yet or have moved past it,
        // look towards the right to find a non-NaN point.
        for (var j = idx; j < points.length; ++j) {
          // Clear out a previously-found point (if any) since it's no longer
          // valid, we shouldn't use it for interpolation anymore.
          nextPoint = null;
          if (!isNaN(points[j].yval) && points[j].yval !== null) {
            nextPointIdx = j;
            nextPoint = points[j];
            break;
          }
        }
      };
    
      for (var i = 0; i < points.length; ++i) {
        var point = points[i];
        var xval = point.xval;
        if (cumulativeYval[xval] === undefined) {
          cumulativeYval[xval] = 0;
        }
    
        var actualYval = point.yval;
        if (isNaN(actualYval) || actualYval === null) {
          if(fillMethod == 'none') {
            actualYval = 0;
          } else {
            // Interpolate/extend for stacking purposes if possible.
            updateNextPoint(i);
            if (prevPoint && nextPoint && fillMethod != 'none') {
              // Use linear interpolation between prevPoint and nextPoint.
              actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) *
                  ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval));
            } else if (prevPoint && fillMethod == 'all') {
              actualYval = prevPoint.yval;
            } else if (nextPoint && fillMethod == 'all') {
              actualYval = nextPoint.yval;
            } else {
              actualYval = 0;
            }
          }
        } else {
          prevPoint = point;
        }
    
        var stackedYval = cumulativeYval[xval];
        if (lastXval != xval) {
          // If an x-value is repeated, we ignore the duplicates.
          stackedYval += actualYval;
          cumulativeYval[xval] = stackedYval;
        }
        lastXval = xval;
    
        point.yval_stacked = stackedYval;
    
        if (stackedYval > seriesExtremes[1]) {
          seriesExtremes[1] = stackedYval;
        }
        if (stackedYval < seriesExtremes[0]) {
          seriesExtremes[0] = stackedYval;
        }
      }
    };
    
    
    /**
     * Loop over all fields and create datasets, calculating extreme y-values for
     * each series and extreme x-indices as we go.
     *
     * dateWindow is passed in as an explicit parameter so that we can compute
     * extreme values "speculatively", i.e. without actually setting state on the
     * dygraph.
     *
     * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
     *     rolledSeries[seriesIndex][row] = raw point, where
     *     seriesIndex is the column number starting with 1, and
     *     rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
     * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
     * @return {{
     *     points: Array.<Array.<Dygraph.PointType>>,
     *     seriesExtremes: Array.<Array.<number>>,
     *     boundaryIds: Array.<number>}}
     * @private
     */
    Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
      var boundaryIds = [];
      var points = [];
      var cumulativeYval = [];  // For stacked series.
      var extremes = {};  // series name -> [low, high]
      var seriesIdx, sampleIdx;
      var firstIdx, lastIdx;
      var axisIdx;
      
      // Loop over the fields (series).  Go from the last to the first,
      // because if they're stacked that's how we accumulate the values.
      var num_series = rolledSeries.length - 1;
      var series;
      for (seriesIdx = num_series; seriesIdx >= 1; seriesIdx--) {
        if (!this.visibility()[seriesIdx - 1]) continue;
    
        // Prune down to the desired range, if necessary (for zooming)
        // Because there can be lines going to points outside of the visible area,
        // we actually prune to visible points, plus one on either side.
        if (dateWindow) {
          series = rolledSeries[seriesIdx];
          var low = dateWindow[0];
          var high = dateWindow[1];
    
          // TODO(danvk): do binary search instead of linear search.
          // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
          firstIdx = null; 
          lastIdx = null;
          for (sampleIdx = 0; sampleIdx < series.length; sampleIdx++) {
            if (series[sampleIdx][0] >= low && firstIdx === null) {
              firstIdx = sampleIdx;
            }
            if (series[sampleIdx][0] <= high) {
              lastIdx = sampleIdx;
            }
          }
    
          if (firstIdx === null) firstIdx = 0;
          var correctedFirstIdx = firstIdx;
          var isInvalidValue = true;
          while (isInvalidValue && correctedFirstIdx > 0) {
            correctedFirstIdx--;
            // check if the y value is null.
            isInvalidValue = series[correctedFirstIdx][1] === null;
          }
    
          if (lastIdx === null) lastIdx = series.length - 1;
          var correctedLastIdx = lastIdx;
          isInvalidValue = true;
          while (isInvalidValue && correctedLastIdx < series.length - 1) {
            correctedLastIdx++;
            isInvalidValue = series[correctedLastIdx][1] === null;
          }
    
          if (correctedFirstIdx!==firstIdx) {
            firstIdx = correctedFirstIdx;
          }
          if (correctedLastIdx !== lastIdx) {
            lastIdx = correctedLastIdx;
          }
          
          boundaryIds[seriesIdx-1] = [firstIdx, lastIdx];
          
          // .slice's end is exclusive, we want to include lastIdx.
          series = series.slice(firstIdx, lastIdx + 1);
        } else {
          series = rolledSeries[seriesIdx];
          boundaryIds[seriesIdx-1] = [0, series.length-1];
        }
    
        var seriesName = this.attr_("labels")[seriesIdx];
        var seriesExtremes = this.dataHandler_.getExtremeYValues(series, 
            dateWindow, this.getBooleanOption("stepPlot",seriesName));
    
        var seriesPoints = this.dataHandler_.seriesToPoints(series, 
            seriesName, boundaryIds[seriesIdx-1][0]);
    
        if (this.getBooleanOption("stackedGraph")) {
          axisIdx = this.attributes_.axisForSeries(seriesName);
          if (cumulativeYval[axisIdx] === undefined) {
            cumulativeYval[axisIdx] = [];
          }
          Dygraph.stackPoints_(seriesPoints, cumulativeYval[axisIdx], seriesExtremes,
                               this.getBooleanOption("stackedGraphNaNFill"));
        }
    
        extremes[seriesName] = seriesExtremes;
        points[seriesIdx] = seriesPoints;
      }
    
      return { points: points, extremes: extremes, boundaryIds: boundaryIds };
    };
    
    /**
     * Update the graph with new data. This method is called when the viewing area
     * has changed. If the underlying data or options have changed, predraw_ will
     * be called before drawGraph_ is called.
     *
     * @private
     */
    Dygraph.prototype.drawGraph_ = function() {
      var start = new Date();
    
      // This is used to set the second parameter to drawCallback, below.
      var is_initial_draw = this.is_initial_draw_;
      this.is_initial_draw_ = false;
    
      this.layout_.removeAllDatasets();
      this.setColors_();
      this.attrs_.pointSize = 0.5 * this.getNumericOption('highlightCircleSize');
    
      var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_);
      var points = packed.points;
      var extremes = packed.extremes;
      this.boundaryIds_ = packed.boundaryIds;
    
      this.setIndexByName_ = {};
      var labels = this.attr_("labels");
      if (labels.length > 0) {
        this.setIndexByName_[labels[0]] = 0;
      }
      var dataIdx = 0;
      for (var i = 1; i < points.length; i++) {
        this.setIndexByName_[labels[i]] = i;
        if (!this.visibility()[i - 1]) continue;
        this.layout_.addDataset(labels[i], points[i]);
        this.datasetIndex_[i] = dataIdx++;
      }
    
      this.computeYAxisRanges_(extremes);
      this.layout_.setYAxes(this.axes_);
    
      this.addXTicks_();
    
      // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
      var tmp_zoomed_x = this.zoomed_x_;
      // Tell PlotKit to use this new data and render itself
      this.zoomed_x_ = tmp_zoomed_x;
      this.layout_.evaluate();
      this.renderGraph_(is_initial_draw);
    
      if (this.getStringOption("timingName")) {
        var end = new Date();
        console.log(this.getStringOption("timingName") + " - drawGraph: " + (end - start) + "ms");
      }
    };
    
    /**
     * This does the work of drawing the chart. It assumes that the layout and axis
     * scales have already been set (e.g. by predraw_).
     *
     * @private
     */
    Dygraph.prototype.renderGraph_ = function(is_initial_draw) {
      this.cascadeEvents_('clearChart');
      this.plotter_.clear();
    
      if (this.getFunctionOption('underlayCallback')) {
        // NOTE: we pass the dygraph object to this callback twice to avoid breaking
        // users who expect a deprecated form of this callback.
        this.getFunctionOption('underlayCallback').call(this,
            this.hidden_ctx_, this.layout_.getPlotArea(), this, this);
      }
    
      var e = {
        canvas: this.hidden_,
        drawingContext: this.hidden_ctx_
      };
      this.cascadeEvents_('willDrawChart', e);
      this.plotter_.render();
      this.cascadeEvents_('didDrawChart', e);
      this.lastRow_ = -1;  // because plugins/legend.js clears the legend
    
      // TODO(danvk): is this a performance bottleneck when panning?
      // The interaction canvas should already be empty in that situation.
      this.canvas_.getContext('2d').clearRect(0, 0, this.width_, this.height_);
    
      if (this.getFunctionOption("drawCallback") !== null) {
        this.getFunctionOption("drawCallback").call(this, this, is_initial_draw);
      }
      if (is_initial_draw) {
        this.readyFired_ = true;
        while (this.readyFns_.length > 0) {
          var fn = this.readyFns_.pop();
          fn(this);
        }
      }
    };
    
    /**
     * @private
     * Determine properties of the y-axes which are independent of the data
     * currently being displayed. This includes things like the number of axes and
     * the style of the axes. It does not include the range of each axis and its
     * tick marks.
     * This fills in this.axes_.
     * axes_ = [ { options } ]
     *   indices are into the axes_ array.
     */
    Dygraph.prototype.computeYAxes_ = function() {
      // Preserve valueWindow settings if they exist, and if the user hasn't
      // specified a new valueRange.
      var valueWindows, axis, index, opts, v;
      if (this.axes_ !== undefined && this.user_attrs_.hasOwnProperty("valueRange") === false) {
        valueWindows = [];
        for (index = 0; index < this.axes_.length; index++) {
          valueWindows.push(this.axes_[index].valueWindow);
        }
      }
    
      // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
      // data computation as well as options storage.
      // Go through once and add all the axes.
      this.axes_ = [];
    
      for (axis = 0; axis < this.attributes_.numAxes(); axis++) {
        // Add a new axis, making a copy of its per-axis options.
        opts = { g : this };
        Dygraph.update(opts, this.attributes_.axisOptions(axis));
        this.axes_[axis] = opts;
      }
    
    
      // Copy global valueRange option over to the first axis.
      // NOTE(konigsberg): Are these two statements necessary?
      // I tried removing it. The automated tests pass, and manually
      // messing with tests/zoom.html showed no trouble.
      v = this.attr_('valueRange');
      if (v) this.axes_[0].valueRange = v;
    
      if (valueWindows !== undefined) {
        // Restore valueWindow settings.
    
        // When going from two axes back to one, we only restore
        // one axis.
        var idxCount = Math.min(valueWindows.length, this.axes_.length);
    
        for (index = 0; index < idxCount; index++) {
          this.axes_[index].valueWindow = valueWindows[index];
        }
      }
    
      for (axis = 0; axis < this.axes_.length; axis++) {
        if (axis === 0) {
          opts = this.optionsViewForAxis_('y' + (axis ? '2' : ''));
          v = opts("valueRange");
          if (v) this.axes_[axis].valueRange = v;
        } else {  // To keep old behavior
          var axes = this.user_attrs_.axes;
          if (axes && axes.y2) {
            v = axes.y2.valueRange;
            if (v) this.axes_[axis].valueRange = v;
          }
        }
      }
    };
    
    /**
     * Returns the number of y-axes on the chart.
     * @return {number} the number of axes.
     */
    Dygraph.prototype.numAxes = function() {
      return this.attributes_.numAxes();
    };
    
    /**
     * @private
     * Returns axis properties for the given series.
     * @param {string} setName The name of the series for which to get axis
     * properties, e.g. 'Y1'.
     * @return {Object} The axis properties.
     */
    Dygraph.prototype.axisPropertiesForSeries = function(series) {
      // TODO(danvk): handle errors.
      return this.axes_[this.attributes_.axisForSeries(series)];
    };
    
    /**
     * @private
     * Determine the value range and tick marks for each axis.
     * @param {Object} extremes A mapping from seriesName -> [low, high]
     * This fills in the valueRange and ticks fields in each entry of this.axes_.
     */
    Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
      var isNullUndefinedOrNaN = function(num) {
        return isNaN(parseFloat(num));
      };
      var numAxes = this.attributes_.numAxes();
      var ypadCompat, span, series, ypad;
      
      var p_axis;
    
      // Compute extreme values, a span and tick marks for each axis.
      for (var i = 0; i < numAxes; i++) {
        var axis = this.axes_[i];
        var logscale = this.attributes_.getForAxis("logscale", i);
        var includeZero = this.attributes_.getForAxis("includeZero", i);
        var independentTicks = this.attributes_.getForAxis("independentTicks", i);
        series = this.attributes_.seriesForAxis(i);
    
        // Add some padding. This supports two Y padding operation modes:
        //
        // - backwards compatible (yRangePad not set):
        //   10% padding for automatic Y ranges, but not for user-supplied
        //   ranges, and move a close-to-zero edge to zero except if
        //   avoidMinZero is set, since drawing at the edge results in
        //   invisible lines. Unfortunately lines drawn at the edge of a
        //   user-supplied range will still be invisible. If logscale is
        //   set, add a variable amount of padding at the top but
        //   none at the bottom.
        //
        // - new-style (yRangePad set by the user):
        //   always add the specified Y padding.
        //
        ypadCompat = true;
        ypad = 0.1; // add 10%
        if (this.getNumericOption('yRangePad') !== null) {
          ypadCompat = false;
          // Convert pixel padding to ratio
          ypad = this.getNumericOption('yRangePad') / this.plotter_.area.h;
        }
    
        if (series.length === 0) {
          // If no series are defined or visible then use a reasonable default
          axis.extremeRange = [0, 1];
        } else {
          // Calculate the extremes of extremes.
          var minY = Infinity;  // extremes[series[0]][0];
          var maxY = -Infinity;  // extremes[series[0]][1];
          var extremeMinY, extremeMaxY;
    
          for (var j = 0; j < series.length; j++) {
            // this skips invisible series
            if (!extremes.hasOwnProperty(series[j])) continue;
    
            // Only use valid extremes to stop null data series' from corrupting the scale.
            extremeMinY = extremes[series[j]][0];
            if (extremeMinY !== null) {
              minY = Math.min(extremeMinY, minY);
            }
            extremeMaxY = extremes[series[j]][1];
            if (extremeMaxY !== null) {
              maxY = Math.max(extremeMaxY, maxY);
            }
          }
    
          // Include zero if requested by the user.
          if (includeZero && !logscale) {
            if (minY > 0) minY = 0;
            if (maxY < 0) maxY = 0;
          }
    
          // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
          if (minY == Infinity) minY = 0;
          if (maxY == -Infinity) maxY = 1;
    
          span = maxY - minY;
          // special case: if we have no sense of scale, center on the sole value.
          if (span === 0) {
            if (maxY !== 0) {
              span = Math.abs(maxY);
            } else {
              // ... and if the sole value is zero, use range 0-1.
              maxY = 1;
              span = 1;
            }
          }
    
          var maxAxisY, minAxisY;
          if (logscale) {
            if (ypadCompat) {
              maxAxisY = maxY + ypad * span;
              minAxisY = minY;
            } else {
              var logpad = Math.exp(Math.log(span) * ypad);
              maxAxisY = maxY * logpad;
              minAxisY = minY / logpad;
            }
          } else {
            maxAxisY = maxY + ypad * span;
            minAxisY = minY - ypad * span;
    
            // Backwards-compatible behavior: Move the span to start or end at zero if it's
            // close to zero, but not if avoidMinZero is set.
            if (ypadCompat && !this.getBooleanOption("avoidMinZero")) {
              if (minAxisY < 0 && minY >= 0) minAxisY = 0;
              if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
            }
          }
          axis.extremeRange = [minAxisY, maxAxisY];
        }
        if (axis.valueWindow) {
          // This is only set if the user has zoomed on the y-axis. It is never set
          // by a user. It takes precedence over axis.valueRange because, if you set
          // valueRange, you'd still expect to be able to pan.
          axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
        } else if (axis.valueRange) {
          // This is a user-set value range for this axis.
          var y0 = isNullUndefinedOrNaN(axis.valueRange[0]) ? axis.extremeRange[0] : axis.valueRange[0];
          var y1 = isNullUndefinedOrNaN(axis.valueRange[1]) ? axis.extremeRange[1] : axis.valueRange[1];
          if (!ypadCompat) {
            if (axis.logscale) {
              var logpad = Math.exp(Math.log(span) * ypad);
              y0 *= logpad;
              y1 /= logpad;
            } else {
              span = y1 - y0;
              y0 -= span * ypad;
              y1 += span * ypad;
            }
          }
          axis.computedValueRange = [y0, y1];
        } else {
          axis.computedValueRange = axis.extremeRange;
        }
        
        
        if (independentTicks) {
          axis.independentTicks = independentTicks;
          var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
          var ticker = opts('ticker');
          axis.ticks = ticker(axis.computedValueRange[0],
                  axis.computedValueRange[1],
                  this.plotter_.area.h,
                  opts,
                  this);
          // Define the first independent axis as primary axis.
          if (!p_axis) p_axis = axis;
        }
      }
      if (p_axis === undefined) {
        throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
      }
      // Add ticks. By default, all axes inherit the tick positions of the
      // primary axis. However, if an axis is specifically marked as having
      // independent ticks, then that is permissible as well.
      for (var i = 0; i < numAxes; i++) {
        var axis = this.axes_[i];
        
        if (!axis.independentTicks) {
          var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
          var ticker = opts('ticker');
          var p_ticks = p_axis.ticks;
          var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
          var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
          var tick_values = [];
          for (var k = 0; k < p_ticks.length; k++) {
            var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
            var y_val = axis.computedValueRange[0] + y_frac * scale;
            tick_values.push(y_val);
          }
    
          axis.ticks = ticker(axis.computedValueRange[0],
                              axis.computedValueRange[1],
                              this.plotter_.area.h,
                              opts,
                              this,
                              tick_values);
        }
      }
    };
    
    /**
     * Detects the type of the str (date or numeric) and sets the various
     * formatting attributes in this.attrs_ based on this type.
     * @param {string} str An x value.
     * @private
     */
    Dygraph.prototype.detectTypeFromString_ = function(str) {
      var isDate = false;
      var dashPos = str.indexOf('-');  // could be 2006-01-01 _or_ 1.0e-2
      if ((dashPos > 0 && (str[dashPos-1] != 'e' && str[dashPos-1] != 'E')) ||
          str.indexOf('/') >= 0 ||
          isNaN(parseFloat(str))) {
        isDate = true;
      } else if (str.length == 8 && str > '19700101' && str < '20371231') {
        // TODO(danvk): remove support for this format.
        isDate = true;
      }
    
      this.setXAxisOptions_(isDate);