[Chartjs]-ChartJS bar chart fixed width for dynamic data sets

3👍

You can divide the “categoryPercentage” into as many columns as possible and multiply by the number of columns in the current dataset

https://jsfiddle.net/qrwvvtxs/2/

var barChartData1 = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: 'Dataset 1',
    data: [3,2,7,4,5,7,6]
  }, {
    label: 'Dataset 2',
    backgroundColor: "#faa",
    data: [11,13,21,13,16,21,18]
  }]
};
var barChartData2 = {
  labels: ["January"],
  datasets: [{
    label: 'Dataset 1',
    data: [6]
  }, {
    label: 'Dataset 2',
    backgroundColor: "#faa",
    data: [11]
  }]
};

var ctx1 = document.getElementById("canvas1").getContext("2d");
var ctx2 = document.getElementById("canvas2").getContext("2d");
var myBar1 = new Chart(ctx1, {
  type: 'bar',
  data: barChartData1,
  options: {
    responsive: true,
    scales: {
      xAxes: [{
          barPercentage: 1,
          categoryPercentage: 0.5 / 10 * barChartData1.datasets[0].data.length
      }],
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});
var myBar2 = new Chart(ctx2, {
  type: 'bar',
  data: barChartData2,
  options: {
    responsive: true,
    scales: {
      xAxes: [{
          barPercentage: 1,
          categoryPercentage: 0.5 / 10 * barChartData2.datasets[0].data.length
      }],
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>

Leave a comment