Chart.js divide stepSize in equal amount of steps

3.4k Views Asked by At

Using chart.js 3.x how to divide the Y-Axis in an equal number of steps that should not exceed more than the total number of three steps.

Example chart,
I have set the step size which will divide the Y-Axis into three equal steps but it is ignored.
https://jsfiddle.net/0awxe539/3/

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

I want to have the Y-Axis divided into max three equal steps.
If min is 0 and max is 0.5 then the chart should have steps 0, 0.25 and 0.5.

Adding maxTicksLimit:3 has some random behaviour and some times I see only 2 ticks and not three.

Also my chart data is dynamic and I am caculating and updating min, max and stepSize at the run time.

1

There are 1 best solutions below

1
On

I think you can't use both maxTicksLimit and stepsize together. One way to solve it is to declare the data before the config and calculate stepSize there. Then you can put max, min and stepsize values from there. I also used 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'
        }
      }
    }
  }
};