ticks.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Calculate tick step.
  3. * Implementation from d3-array (ticks.js)
  4. * https://github.com/d3/d3-array/blob/master/src/ticks.js
  5. * @param start Start value
  6. * @param stop End value
  7. * @param count Ticks count
  8. */
  9. export function tickStep(start: number, stop: number, count: number): number {
  10. let e10 = Math.sqrt(50),
  11. e5 = Math.sqrt(10),
  12. e2 = Math.sqrt(2);
  13. let step0 = Math.abs(stop - start) / Math.max(0, count),
  14. step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
  15. error = step0 / step1;
  16. if (error >= e10) {
  17. step1 *= 10;
  18. } else if (error >= e5) {
  19. step1 *= 5;
  20. } else if (error >= e2) {
  21. step1 *= 2;
  22. }
  23. return stop < start ? -step1 : step1;
  24. }
  25. export function getScaledDecimals(decimals, tick_size) {
  26. return decimals - Math.floor(Math.log(tick_size) / Math.LN10);
  27. }
  28. /**
  29. * Calculate tick size based on min and max values, number of ticks and precision.
  30. * @param min Axis minimum
  31. * @param max Axis maximum
  32. * @param noTicks Number of ticks
  33. * @param tickDecimals Tick decimal precision
  34. */
  35. export function getFlotTickSize(min: number, max: number, noTicks: number, tickDecimals: number) {
  36. var delta = (max - min) / noTicks,
  37. dec = -Math.floor(Math.log(delta) / Math.LN10),
  38. maxDec = tickDecimals;
  39. var magn = Math.pow(10, -dec),
  40. norm = delta / magn, // norm is between 1.0 and 10.0
  41. size;
  42. if (norm < 1.5) {
  43. size = 1;
  44. } else if (norm < 3) {
  45. size = 2;
  46. // special case for 2.5, requires an extra decimal
  47. if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
  48. size = 2.5;
  49. ++dec;
  50. }
  51. } else if (norm < 7.5) {
  52. size = 5;
  53. } else {
  54. size = 10;
  55. }
  56. size *= magn;
  57. return size;
  58. }