首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Chart.js中更改对数刻度的底

在Chart.js中更改对数刻度的底
EN

Stack Overflow用户
提问于 2018-08-06 10:05:51
回答 1查看 446关注 0票数 4

existing Logarithmic Axis默认以10为底。有没有办法将刻度更改为不同底的对数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-30 17:56:12

您可以实现自定义刻度来更改日志刻度的基数,如下所示:

代码语言:javascript
复制
class Log2Axis extends Chart.Scale {
  constructor(cfg) {
    super(cfg);
    this._startValue = undefined;
    this._valueRange = 0;
  }

  parse(raw, index) {
    const value = Chart.LinearScale.prototype.parse.apply(this, [raw, index]);
    return isFinite(value) && value > 0 ? value : null;
  }

  determineDataLimits() {
    const {
      min,
      max
    } = this.getMinMax(true);
    this.min = isFinite(min) ? Math.max(0, min) : null;
    this.max = isFinite(max) ? Math.max(0, max) : null;
  }

  buildTicks() {
    const ticks = [];

    let power = Math.floor(Math.log2(this.min || 1));
    let maxPower = Math.ceil(Math.log2(this.max || 2));
    while (power <= maxPower) {
      ticks.push({
        value: Math.pow(2, power)
      });
      power += 1;
    }

    this.min = ticks[0].value;
    this.max = ticks[ticks.length - 1].value;
    return ticks;
  }

  /**
   * @protected
   */
  configure() {
    const start = this.min;

    super.configure();

    this._startValue = Math.log2(start);
    this._valueRange = Math.log2(this.max) - Math.log2(start);
  }

  getPixelForValue(value) {
    if (value === undefined || value === 0) {
      value = this.min;
    }

    return this.getPixelForDecimal(value === this.min ? 0 :
      (Math.log2(value) - this._startValue) / this._valueRange);
  }

  getValueForPixel(pixel) {
    const decimal = this.getDecimalForPixel(pixel);
    return Math.pow(2, this._startValue + decimal * this._valueRange);
  }
}

Log2Axis.id = 'log2';
Log2Axis.defaults = {};

Chart.register(Log2Axis);

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Black", "White"],
    datasets: [{
      label: '# of Votes',
      data: [8, 3, 60, 20, 130, 80, 1030, 250],
      backgroundColor: 'pink',
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      x: {
        display: true
      },
      y: {
        display: true,
        type: 'log2',
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
代码语言:javascript
复制
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
</body>

小提琴链接:https://jsfiddle.net/Leelenaleee/oyLf0wed/6/

感谢为此制作样本的chart.js团队:https://www.chartjs.org/docs/master/samples/advanced/derived-axis-type.html

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51699747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档