quantile.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * 计算几分位 https://github.com/simple-statistics/simple-statistics/blob/master/src/quantile_sorted.js
  3. * @param x 数组
  4. * @param p 百分比
  5. */
  6. function quantileSorted(x, p) {
  7. var idx = x.length * p;
  8. /*if (x.length === 0) { // 当前场景这些条件不可能命中
  9. throw new Error('quantile requires at least one value.');
  10. } else if (p < 0 || p > 1) {
  11. throw new Error('quantiles must be between 0 and 1');
  12. } else */
  13. if (p === 1) {
  14. // If p is 1, directly return the last element
  15. return x[x.length - 1];
  16. }
  17. else if (p === 0) {
  18. // If p is 0, directly return the first element
  19. return x[0];
  20. }
  21. else if (idx % 1 !== 0) {
  22. // If p is not integer, return the next element in array
  23. return x[Math.ceil(idx) - 1];
  24. }
  25. else if (x.length % 2 === 0) {
  26. // If the list has even-length, we'll take the average of this number
  27. // and the next value, if there is one
  28. return (x[idx - 1] + x[idx]) / 2;
  29. }
  30. else {
  31. // Finally, in the simple case of an integer value
  32. // with an odd-length list, return the x value at the index.
  33. return x[idx];
  34. }
  35. }
  36. export default function calculateTicks(cfg) {
  37. var tickCount = cfg.tickCount, values = cfg.values;
  38. if (!values || !values.length) {
  39. return [];
  40. }
  41. var sorted = values.slice().sort(function (a, b) {
  42. return a - b;
  43. });
  44. var ticks = [];
  45. for (var i = 0; i < tickCount; i++) {
  46. var p = i / (tickCount - 1);
  47. ticks.push(quantileSorted(sorted, p));
  48. }
  49. return ticks;
  50. }
  51. //# sourceMappingURL=quantile.js.map