Chartjs-How to use excess vertical space in stacked bar chart?

1๐Ÿ‘

โœ…

You could sum your arrays, find the max value in the resulting array and set the options.scales.y.max property with this value :

let data1 = [20,40,60,40,20];
let data2 = [100,200,300,200,100];

let sum = data1.map(function (num, idx) {
  return num + data2[idx];
});

let max = Math.max(...sum);

var options = 
{
    maintainAspectRatio: false,
    responsive: true,
    plugins: {
        legend: { display: false },
    },
    scales: {
      x: {
        display: false,
        stacked: true 
      }, 
      y: { 
        display: true,
        stacked: true,
        max: max
      }
    }
  };

var mychart = new Chart(document.getElementById('mycanvas2').getContext('2d'), {
  type: 'bar',
  data: {
    labels: ['a','b','c','d','e'],
    datasets: [{
      backgroundColor: '#ff00ff',
      data: data1
    },{
      backgroundColor: '#00ff00',
      data: data2
    }]
  },
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<div  style="width:400px; height: 200px">
  <canvas id="mycanvas2"></canvas>
</div>

0๐Ÿ‘

According to this issue with chart.js you can configure the y-axis bounds to fit the data:

options: {
    scales: {
        x: {
            display: false,
            stacked: true 
        }, 
        y: { 
            display: true,
            stacked: true,
            bounds: 'data' <----------
        }
    }
}

Leave a comment