YAxisScale.fromRange constructor

YAxisScale.fromRange(
  1. double min,
  2. double max, {
  3. int intermediateLabelCount = 3,
})

Implementation

factory YAxisScale.fromRange(double min, double max, {int intermediateLabelCount = 3}) {
  if (!min.isFinite || !max.isFinite || min > max) {
    throw ArgumentError('Y-axis range must be finite and ordered.');
  }
  if (intermediateLabelCount < 0) {
    throw RangeError.value(intermediateLabelCount, 'intermediateLabelCount', 'Must not be negative.');
  }
  final intervals = intermediateLabelCount + 1;
  min = min < 0 ? min : 0;
  max = max > 0 ? max : 0;
  if (min == max) max = 1;

  if (intervals == 1 && min < 0 && max > 0) {
    return YAxisScale._(min, max, [min, max]);
  }
  final negativeIntervals = min == 0
      ? 0
      : max == 0
          ? intervals
          : (intervals * -min / (max - min)).round().clamp(1, intervals - 1);
  final positiveIntervals = intervals - negativeIntervals;
  final rawStep = math.max(negativeIntervals == 0 ? 0.0 : -min / negativeIntervals,
      positiveIntervals == 0 ? 0.0 : max / positiveIntervals);
  final magnitude = math.pow(10, (math.log(rawStep) / math.ln10).floor()).toDouble();
  final fraction = rawStep / magnitude;
  final factor =
      const [1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 5.0, 7.5, 10.0].firstWhere((value) => value >= fraction - 1e-10);
  final step = factor * magnitude;
  final lower = -negativeIntervals * step;
  final upper = positiveIntervals * step;
  return YAxisScale._(
      lower, upper, [for (var index = 0; index <= intervals; index++) (index - negativeIntervals) * step]);
}