[Chartjs]-ChartJs bar chart – keep bars left instead of equally spread across the width

5👍

You can provide a labels array padded with empty strings to the required length, e.g. 15.

This will ensure a consistent number of categories on the axis, and thus ensure that the bars will stay the same width and left-aligned even when there are less bars (Fiddle).

(If you like, you can also pad the data array with 0‘s for consistency, but it’s not necessary – the labels array is what determines the axis looks like.)

var data = [12, 19, 3, 5, 2];
var labels = ["a", "b", "c", "d", "e"];

for (var i = labels.length; i < 15; i++) {
  labels.push("");
}

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: 'Count',
      data: data
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  } 
});

Leave a comment