Home > other >  how to manipulate with the y-axis values in chartjs
how to manipulate with the y-axis values in chartjs

Time:11-06

Hi there to all of you,

How can I control the Y-axis values in Chart.js library? The data are displayed different in each chart, even though the code is the same for each chart.

The data in the first chart are shown like this enter image description here

while in the second chart the data are like this enter image description here

How can I make in that way that each chart has values 5, like 5, 10, 20, 25 because I never have values with type float.

Code looks like this:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: data.map(x => moment(x.date).format("MMM Do")),
        datasets: [{
            data: data.map(x => x.premium),
            backgroundColor: '#ffec87',
            borderColor: "#ffec87",
            borderWidth: 2,
            borderStyle: 'dotted'
        }]
    },
  options: {
    scales: {
      xAxis: { grid: { display: false } },
      yAxis: { grid: { borderDash: [3, 5] } }
    }
  }
});

Thanks a lot.

CodePudding user response:

in the options scales, yAxis add a stepsize

options: {
 scales: {
   xAxis: { grid: { display: false } },
   yAxis: { 
     grid: { borderDash: [3, 5] },
     ticks: {stepSize: 5}
   }
 }
}

CodePudding user response:

Alternatively you could set the min/max of the y-axis scale as shown in this example

https://www.chartjs.org/docs/latest/samples/scales/linear-min-max.html

scales: {
      y: {
        min: 0,
        max: 25,
      }
    }

I just found the place in the documentation where Amin's solution is discussed, I figure I'd put a reference here for convenience.

https://www.chartjs.org/docs/latest/samples/scales/linear-step-size.html

y: {
        title: {
          display: true,
          text: 'Value'
        },
        min: 0,
        max: 100,
        ticks: {
          // forces step size to be 50 units
          stepSize: 5
        }
   }
  • Related