Chartjs-Setting exact value in X and Y Axes in chart.js

0๐Ÿ‘

โœ…

I think you could use min and max options, instead of suggestedMin and suggestedMax which are useful for extending the range of the axis but maintaining the auto fit behaviour.

const ctx = document.getElementById("myChart");
const data = [{x:0, y:10}, {x:1, y:20}, {x:2, y:30}, {x:3, y:53}, {x:4, y:40}, {x:5, y:21}, {x:6, y:10}];
const myChart = new Chart(ctx, {
   type: 'scatter',
   data: {
     datasets: [{
        label: 'Tiempo-Hole',
        borderColor: 'red',
        fill: false,
        pointRadius: 0,
        data,
        showLine: true,
        clip: 10
     }],
   },
   options: {    
     scales: {
       yAxes: [{
         display: true,
         ticks: {
           min: 0,  
           max: data.reduce(function (max, item) {
             return ( max > item.y ? max : item.y);
           }),
           stepSize: data.reduce(function (max, item) {
             return ( max > item.y ? max : item.y);
           }) / 10,
           callback: (value) => Math.trunc(value),
           beginAtZero: true
         }
       }],
       xAxes: [{
         display: true,
         ticks: {
           min: 0,    
           max: data.reduce(function (max, item) {
             return ( max > item.x ? max : item.x);
           }),
           beginAtZero: true   
         }
       }]
     }
   }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Leave a comment