Wasn't supposed to go in this branch.
[dygraphs.git] / dygraph.js
index 796cc99..8741bf0 100644 (file)
@@ -96,9 +96,7 @@ Dygraph.DEFAULT_ATTRS = {
   labelsKMG2: false,
   showLabelsOnHighlight: true,
 
-  yValueFormatter: function(x, opt_numDigits) {
-    return x.toPrecision(opt_numDigits || 2);
-  },
+  yValueFormatter: function(x) { return Dygraph.round_(x, 2); },
 
   strokeWidth: 1.0,
 
@@ -196,7 +194,6 @@ Dygraph.prototype.__init__ = function(div, file, attrs) {
   this.wilsonInterval_ = attrs.wilsonInterval || true;
   this.is_initial_draw_ = true;
   this.annotations_ = [];
-  this.numDigits_ = 2;
 
   // Clear the div. This ensure that, if multiple dygraphs are passed the same
   // div, then only one will be drawn.
@@ -306,7 +303,7 @@ Dygraph.prototype.error = function(message) {
 
 /**
  * Returns the current rolling period, as set by the user or an option.
- * @return {Number} The number of points in the rolling window
+ * @return {Number} The number of days in the rolling window
  */
 Dygraph.prototype.rollPeriod = function() {
   return this.rollPeriod_;
@@ -801,19 +798,6 @@ Dygraph.prototype.dragGetY_ = function(e, context) {
 // panning behavior.
 //
 Dygraph.startPan = function(event, g, context) {
-  // have to be zoomed in to pan.
-  // TODO(konigsberg): Let's loosen this zoom-to-pan restriction, also
-  // perhaps create panning boundaries? A more flexible pan would make it,
-  // ahem, 'pan-useful'.
-  var zoomedY = false;
-  for (var i = 0; i < g.axes_.length; i++) {
-    if (g.axes_[i].valueWindow || g.axes_[i].valueRange) {
-      zoomedY = true;
-      break;
-    }
-  }
-  if (!g.dateWindow_ && !zoomedY) return;
-
   context.isPanning = true;
   var xRange = g.xAxisRange();
   context.dateRange = xRange[1] - xRange[0];
@@ -1409,7 +1393,7 @@ Dygraph.prototype.updateSelection_ = function() {
         }
         var point = this.selPoints_[i];
         var c = new RGBColor(this.plotter_.colors[point.name]);
-        var yval = fmtFunc(point.yval, this.numDigits_ + 1);  // In tenths.
+        var yval = fmtFunc(point.yval);
         replace += " <b><font color='" + c.toHex() + "'>"
                 + point.name + "</font></b>:"
                 + yval;
@@ -1592,6 +1576,18 @@ Dygraph.dateString_ = function(date, self) {
 };
 
 /**
+ * Round a number to the specified number of digits past the decimal point.
+ * @param {Number} num The number to round
+ * @param {Number} places The number of decimals to which to round
+ * @return {Number} The rounded number
+ * @private
+ */
+Dygraph.round_ = function(num, places) {
+  var shift = Math.pow(10, places);
+  return Math.round(num * shift)/shift;
+};
+
+/**
  * Fires when there's data available to be graphed.
  * @param {String} data Raw CSV data to be plotted
  * @private
@@ -1620,12 +1616,8 @@ Dygraph.prototype.addXTicks_ = function() {
     endDate   = this.rawData_[this.rawData_.length - 1][0];
   }
 
-  var ret = this.attr_('xTicker')(startDate, endDate, this);
-  if (ret.ticks !== undefined) {  // Used numericTicks()?
-    this.layout_.updateOptions({xTicks: ret.ticks});
-  } else {  // Used dateTicker() instead.
-    this.layout_.updateOptions({xTicks: ret});
-  }
+  var xTicks = this.attr_('xTicker')(startDate, endDate, this);
+  this.layout_.updateOptions({xTicks: xTicks});
 };
 
 // Time granularity enumeration
@@ -1649,7 +1641,7 @@ Dygraph.QUARTERLY = 16;
 Dygraph.BIANNUAL = 17;
 Dygraph.ANNUAL = 18;
 Dygraph.DECADAL = 19;
-Dygraph.CENTENIAL = 20;
+Dygraph.CENTENNIAL = 20;
 Dygraph.NUM_GRANULARITIES = 21;
 
 Dygraph.SHORT_SPACINGS = [];
@@ -1686,7 +1678,7 @@ Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
     if (granularity == Dygraph.BIANNUAL) num_months = 2;
     if (granularity == Dygraph.ANNUAL) num_months = 1;
     if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
-    if (granularity == Dygraph.CENTENIAL) { num_months = 1; year_mod = 100; }
+    if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
 
     var msInYear = 365.2524 * 24 * 3600 * 1000;
     var num_years = 1.0 * (end_time - start_time) / msInYear;
@@ -1759,7 +1751,7 @@ Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
     } else if (granularity == Dygraph.DECADAL) {
       months = [ 0 ];
       year_mod = 10;
-    } else if (granularity == Dygraph.CENTENIAL) {
+    } else if (granularity == Dygraph.CENTENNIAL) {
       months = [ 0 ];
       year_mod = 100;
     } else {
@@ -1809,43 +1801,6 @@ Dygraph.dateTicker = function(startDate, endDate, self) {
 };
 
 /**
- * Determine the number of significant figures in a Number up to the specified
- * precision.  Note that there is no way to determine if a trailing '0' is
- * significant or not, so by convention we return 1 for all of the following
- * inputs: 1, 1.0, 1.00, 1.000 etc.
- * @param {Number} x The input value.
- * @param {Number} opt_maxPrecision Optional maximum precision to consider.
- *                                  Default and maximum allowed value is 13.
- * @return {Number} The number of significant figures which is >= 1.
- */
-Dygraph.significantFigures = function(x, opt_maxPrecision) {
-  var precision = Math.max(opt_maxPrecision || 13, 13);
-
-  // Convert the number to it's exponential notation form and work backwards,
-  // ignoring the 'e+xx' bit.  This may seem like a hack, but doing a loop and
-  // dividing by 10 leads to roundoff errors.  By using toExponential(), we let
-  // the JavaScript interpreter handle the low level bits of the Number for us.
-  var s = x.toExponential(precision);
-  var ePos = s.lastIndexOf('e');  // -1 case handled by return below.
-
-  for (var i = ePos - 1; i >= 0; i--) {
-    if (s[i] == '.') {
-      // Got to the decimal place.  We'll call this 1 digit of precision because
-      // we can't know for sure how many trailing 0s are significant.
-      return 1;
-    } else if (s[i] != '0') {
-      // Found the first non-zero digit.  Return the number of characters
-      // except for the '.'.
-      return i;  // This is i - 1 + 1 (-1 is for '.', +1 is for 0 based index).
-    }
-  }
-
-  // Occurs if toExponential() doesn't return a string containing 'e', which
-  // should never happen.
-  return 1;
-};
-
-/**
  * Add ticks when the x axis has numbers on it (instead of dates)
  * @param {Number} startDate Start of the date window (millis since epoch)
  * @param {Number} endDate End of the date window (millis since epoch)
@@ -1863,7 +1818,7 @@ Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
   var ticks = [];
   if (vals) {
     for (var i = 0; i < vals.length; i++) {
-      ticks[i] = {v: vals[i]};
+      ticks.push({v: vals[i]});
     }
   } else {
     // Basic idea:
@@ -1902,7 +1857,7 @@ Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
     if (low_val > high_val) scale *= -1;
     for (var i = 0; i < nTicks; i++) {
       var tickV = low_val + i * scale;
-      ticks[i] = {v: tickV};
+      ticks.push( {v: tickV} );
     }
   }
 
@@ -1918,36 +1873,30 @@ Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
     k = 1024;
     k_labels = [ "k", "M", "G", "T" ];
   }
-  var formatter = attr('yAxisLabelFormatter') ?
-      attr('yAxisLabelFormatter') : attr('yValueFormatter');
-
-  // Determine the number of decimal places needed for the labels below by
-  // taking the maximum number of significant figures for any label.  We must
-  // take the max because we can't tell if trailing 0s are significant.
-  var numDigits = 0;
-  for (var i = 0; i < ticks.length; i++) {
-    var tickV = ticks[i].v;
-    numDigits = Math.max(Dygraph.significantFigures(tickV), numDigits);
-  }
+  var formatter = attr('yAxisLabelFormatter') ? attr('yAxisLabelFormatter') : attr('yValueFormatter'); 
 
   for (var i = 0; i < ticks.length; i++) {
     var tickV = ticks[i].v;
     var absTickV = Math.abs(tickV);
-    var label = (formatter !== undefined) ?
-        formatter(tickV, numDigits) : tickV.toPrecision(numDigits);
-    if (k_labels.length > 0) {
+    var label;
+    if (formatter != undefined) {
+      label = formatter(tickV);
+    } else {
+      label = Dygraph.round_(tickV, 2);
+    }
+    if (k_labels.length) {
       // Round up to an appropriate unit.
       var n = k*k*k*k;
       for (var j = 3; j >= 0; j--, n /= k) {
         if (absTickV >= n) {
-          label = (tickV / n).toPrecision(numDigits) + k_labels[j];
+          label = Dygraph.round_(tickV / n, 1) + k_labels[j];
           break;
         }
       }
     }
     ticks[i].label = label;
   }
-  return {ticks: ticks, numDigits: numDigits};
+  return ticks;
 };
 
 // Computes the range of the data series (including confidence intervals).
@@ -2138,9 +2087,12 @@ Dygraph.prototype.drawGraph_ = function() {
     this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
   }
 
-  this.computeYAxisRanges_(extremes);
-  this.layout_.updateOptions( { yAxes: this.axes_,
-                                seriesToAxisMap: this.seriesToAxisMap_
+  // TODO(danvk): this method doesn't need to return anything.
+  var out = this.computeYAxisRanges_(extremes);
+  var axes = out[0];
+  var seriesToAxisMap = out[1];
+  this.layout_.updateOptions( { yAxes: axes,
+                                seriesToAxisMap: seriesToAxisMap
                               } );
 
   this.addXTicks_();
@@ -2319,13 +2271,11 @@ Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
     // primary axis. However, if an axis is specifically marked as having
     // independent ticks, then that is permissible as well.
     if (i == 0 || axis.independentTicks) {
-      var ret =
+      axis.ticks =
         Dygraph.numericTicks(axis.computedValueRange[0],
                              axis.computedValueRange[1],
                              this,
                              axis);
-      axis.ticks = ret.ticks;
-      this.numDigits_ = ret.numDigits;
     } else {
       var p_axis = this.axes_[0];
       var p_ticks = p_axis.ticks;
@@ -2338,14 +2288,14 @@ Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
         tick_values.push(y_val);
       }
 
-      var ret =
+      axis.ticks =
         Dygraph.numericTicks(axis.computedValueRange[0],
                              axis.computedValueRange[1],
                              this, axis, tick_values);
-      axis.ticks = ret.ticks;
-      this.numDigits_ = ret.numDigits;
     }
   }
+
+  return [this.axes_, this.seriesToAxisMap_];
 };
  
 /**
@@ -2357,8 +2307,7 @@ Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
  * Note that this is where fractional input (i.e. '5/10') is converted into
  *   decimal values.
  * @param {Array} originalData The data in the appropriate format (see above)
- * @param {Number} rollPeriod The number of points over which to average the
- *                            data
+ * @param {Number} rollPeriod The number of days over which to average the data
  */
 Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
   if (originalData.length < 2)
@@ -2435,7 +2384,7 @@ Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
     }
   } else {
     // Calculate the rolling average for the first rollPeriod - 1 points where
-    // there is not enough data to roll over the full number of points
+    // there is not enough data to roll over the full number of days
     var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
     if (!this.attr_("errorBars")){
       if (rollPeriod == 1) {
@@ -3007,9 +2956,9 @@ Dygraph.prototype.resize = function(width, height) {
 };
 
 /**
- * Adjusts the number of points in the rolling average. Updates the graph to
+ * Adjusts the number of days in the rolling average. Updates the graph to
  * reflect the new averaging period.
- * @param {Number} length Number of points over which to average the data.
+ * @param {Number} length Number of days over which to average the data.
  */
 Dygraph.prototype.adjustRoll = function(length) {
   this.rollPeriod_ = length;