[Chartjs]-Start bar-chart at 0 using ChartJS

3๐Ÿ‘

โœ…

After hours of working, finally i found a soulution. There is no chartjs configuration to do it and you have to draw it your self. Let do it in onComplete function

var ctx = document.getElementById("myChart").getContext('2d');
var datasets = [15, 2, 0, 11];
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["1", "2", "3", "4"],
    datasets: [{
      label: 'value',
      backgroundColor: '#F00',
      data: datasets
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    animation: {
      onComplete: function() {
        var dataSet = myChart.getDatasetMeta(0);
        dataSet.data.forEach(elm => { 
          if (datasets[elm._index] == 0) {
            ctx.fillStyle = '#F00';
            ctx.fillRect(elm._model.x - elm._view.width / 2, elm._model.y - 1, elm._view.width, 2);
          }
        })
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas class="canvasChart" id="myChart"></canvas>

3๐Ÿ‘

You can try beginAtZero:true config option.

options: {
  legend: { display: false },
  scales: {
      yAxes: [{
          display: false,
          ticks: {
                beginAtZero:true
            }
      }],
      xAxes: [{
          display: true,
      }],
  },
  title: {
    display: false,
  }
}

1๐Ÿ‘

Because your Y-axis values starts from 0 to something. So, if your value is 0 in X-Axis than it would be null and wonโ€™t show you bar of 0. So, if you want 0 to appear in chart your starting point should be less than the 0.

1๐Ÿ‘

I believe you said you were using chartsjs. This question already has an answer here.

0๐Ÿ‘

Try this, chart will start with zero.

   options: {
        responsive: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

Leave a comment