Chartjs-How to keep bars same size even when adding new datasets

0👍

use property barThickness: 'flex' so that chartjs will automatically adjust the thickness whenever data is added or removed from the chart.

var ctx = document.getElementById('myChart').getContext('2d');

var data = {
  labels: ['label1', 'label2', 'label3', 'label4'],

  datasets: [

    {
      label: 'mydataset1',
      barThickness: 'flex',
      data: [1, 2, 3, 4],
      backgroundColor: 'red',
    },


    {
      label: 'mydataset2',
      barThickness: 'flex',
      data: [1, 2, 3, 4],
      backgroundColor: 'blue',
    },
    {
      label: 'mydataset3',
      barThickness: 'flex',
      data: [1, 2, 3, 4],
      backgroundColor: 'green',
    }


  ]



}


var options = {

  responsive: true,
  maintainAspectRatio: true,

  scales: {
    xAxes: [{

      ticks: {

        max: 12,
        min: 0,
      }

    }],

    yAxde: [{


    }],

  }
};


var chart = new Chart(ctx, {

  type: 'horizontalBar',

  data: data,

  options: options,

});
.chartWrapper {
  position: relative;
}

.chartWrapper>canvas {
  position: absolute;
  left: 0;
  top: 0;
  pointer-events: none;
}

.chartAreaWrapper {
  height: 85vh;
  background-color: rgba(0, 0, 0, 0);
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
  <title>Page Title</title>
</head>

<body>

  <div class="chartWrapper">
    <div class="chartAreaWrapper">
      <canvas id="myChart" height="100px"></canvas>
    </div>

  </div>

</body>

</html>

Leave a comment