Chartjs-Chartjs y-axis min value to be 0, but not to be shown always

1👍

You can make use of min property. The calculation will be based on your requirement, but you can take below example as a reference. I am getting minimum value from my dataset and subtracting it with some predefined value (say 1000).

  const ctx = document.getElementById('myChart');
  
  const data = [36000, 34650, 30205, 35555, 36632, 37092, 38990];

  let min = Math.min(...data);
    min = min < 0 ? 0 : min - 1000;
  
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
      datasets: [{
        label: 'My First Dataset',
        data: data,
        fill: false,
        borderColor: 'rgb(75, 192, 192)',
        tension: 0.1
      }]
    },
    options: {
      elements: {
        line: {
          tension: 0.4
        },
      },
      scales: {
        x: {
          grid: {
            display: false
          }
        },
        y: {
          min: min,
          ticks: {
            maxTicksLimit: 25,
            autoSkip: true,
            callback: function(value) {
              if (value % 1 === 0 && value >= 0) {
                return value;
              }
            }
          },
        }
      }
    }
  });
<div>
  <canvas id="myChart"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Leave a comment