0

使用chart.js 3.x如何将 Y 轴分成相等的步数,但不应超过三步的总数。

示例图表,
我设置了将 Y 轴分成三个相等的步长的步长,但它被忽略了。
https://jsfiddle.net/0awxe539/3/

Step size calculation: 
stepSize = ((Math.abs(min) + max) / 2); 

我想让 Y 轴分成最多三个相等的步长。
如果min is 0max is 0.5然后 图表应该有步骤00.250.5

添加maxTicksLimit:3有一些随机行为,有时我只看到 2 个刻度而不是 3 个。

此外,我的图表数据是动态的,我在运行时计算和更新 min、max 和 stepSize。

4

1 回答 1

0

我认为您不能同时使用 maxTicksLimit 和 stepsize 。解决它的一种方法是在配置之前声明数据并在那里计算 stepSize。然后你可以从那里输入最大值、最小值和步长值。我也使用了fixedStepSize。

let data =[
    {x:1, y:0.49},
  {x:2, y:0.6},
  {x:3, y:-0.18},
  {x:4, y:0.76},
  {x:5, y:0.48},
  {x:6, y:0.76},
  {x:7, y:0.1},
  {x:8, y:-0.24},
  {x:9, y:0.34},
  {x:10, y:0.42},
  {x:11, y:0.79},
  {x:12, y:-0.21}
]

let values = data.map(item => item.y)
let min = Math.min(...values)
let max = Math.max(...values)
let stepSize = ((Math.abs(min) + max) / 2); 

var config = {
  type: 'scatter',
  data: {
    datasets: [{
      label: "My First dataset",
      backgroundColor: chartColors.red,
      borderColor: chartColors.red,
      showLine: true,
      data: data,
      lineTension: 0,
      fill: false,
    },]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js Line Chart'
    },
    tooltips: {
      mode: 'label',
    },
    hover: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: {
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Test'  
        },
        ticks:
        {
            min: 1,
            max:17,
            stepSize: 5,
        },
        distribution: 'linear',
      },
      yAxes: {
        display: true,
        beginAtZero: true,
        type: 'linear',
        max: max,
        min: min,
        ticks: {
          fontColor: "#ffffff",
          stepSize: stepSize,
          fixedStepSize:stepSize,
        },
        scaleLabel: {
          display: true,
          labelString: 'Value'
        }
      }
    }
  }
};
于 2020-11-26T17:55:48.607 回答