Chartjs-Dynamic maximum y-axis value on Chart.js

3👍

The easiest would be to define the data in a variable outside of the chart configuration and then use Math.max() to define scales.y.max.

scales: {
  y: {
    max: Math.max(...data)        
  },

Please take a look at the following runnable code derived from the Chart.js documentation and see how it works.

let data = [650, 595, 999, 815, 56, 155, 440];

new Chart('myChart', {
  type: 'line',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'My First Dataset',
      data: data,
      fill: false,
      borderColor: 'rgb(75, 192, 192)',
      lineTension: 0.1
    }]
  },
  options: {
    responsive: true,
    plugins: {
      tooltip: {
        mode: 'index',
        intersect: false,
      }
    },
    scales: {
      y: {
        title: {
          display: true,
          text: 'Value'
        },
        max: Math.max(...data)        
      },
      x: {
        title: {
          display: true,
          text: 'Month'
        }
      }      
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta.13/chart.js"></script>
<canvas id="myChart" height="100"></canvas>

Leave a comment