Derived Axis Type

Derived Axis Type - 图1

config setup

  1. const config = {
  2. type: 'line',
  3. data,
  4. options: {
  5. responsive: true,
  6. scales: {
  7. x: {
  8. display: true,
  9. },
  10. y: {
  11. display: true,
  12. type: 'log2',
  13. }
  14. }
  15. }
  16. };
  1. const DATA_COUNT = 12;
  2. const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 1000};
  3. const labels = Utils.months({count: DATA_COUNT});
  4. const data = {
  5. labels: labels,
  6. datasets: [
  7. {
  8. label: 'My First dataset',
  9. data: Utils.numbers(NUMBER_CFG),
  10. borderColor: Utils.CHART_COLORS.red,
  11. backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5),
  12. fill: false,
  13. }
  14. ],
  15. };

Log2 axis implementation

  1. import {Scale, LinearScale} from 'chart.js';
  2. export default class Log2Axis extends Scale {
  3. constructor(cfg) {
  4. super(cfg);
  5. this._startValue = undefined;
  6. this._valueRange = 0;
  7. }
  8. parse(raw, index) {
  9. const value = LinearScale.prototype.parse.apply(this, [raw, index]);
  10. return isFinite(value) && value > 0 ? value : null;
  11. }
  12. determineDataLimits() {
  13. const {min, max} = this.getMinMax(true);
  14. this.min = isFinite(min) ? Math.max(0, min) : null;
  15. this.max = isFinite(max) ? Math.max(0, max) : null;
  16. }
  17. buildTicks() {
  18. const ticks = [];
  19. let power = Math.floor(Math.log2(this.min || 1));
  20. let maxPower = Math.ceil(Math.log2(this.max || 2));
  21. while (power <= maxPower) {
  22. ticks.push({value: Math.pow(2, power)});
  23. power += 1;
  24. }
  25. this.min = ticks[0].value;
  26. this.max = ticks[ticks.length - 1].value;
  27. return ticks;
  28. }
  29. /**
  30. * @protected
  31. */
  32. configure() {
  33. const start = this.min;
  34. super.configure();
  35. this._startValue = Math.log2(start);
  36. this._valueRange = Math.log2(this.max) - Math.log2(start);
  37. }
  38. getPixelForValue(value) {
  39. if (value === undefined || value === 0) {
  40. value = this.min;
  41. }
  42. return this.getPixelForDecimal(value === this.min ? 0
  43. : (Math.log2(value) - this._startValue) / this._valueRange);
  44. }
  45. getValueForPixel(pixel) {
  46. const decimal = this.getDecimalForPixel(pixel);
  47. return Math.pow(2, this._startValue + decimal * this._valueRange);
  48. }
  49. }
  50. Log2Axis.id = 'log2';
  51. Log2Axis.defaults = {};
  52. // The derived axis is registered like this:
  53. // Chart.register(Log2Axis);