[Chartjs]-Need to increase the length of Y axis in a horizontal bar chart

1👍

You could dynamically define the height of the canvas depending on the number of bars your chart contains.

const canvas = document.getElementById('myChart');
const headerHeight = 75;
canvas.height = barCount * 25 + headerHeight;

Please take a look at your amended code and see how it works.

const barCount = 500;

var labels = [];
for (var i = 1; i <= barCount; i++) {
  labels.push('Category ' + i);
}

var data1 = [];
for (var i = 1; i <= barCount; i++) {
  data1.push(i * 10);
}

var data2 = [];
for (var i = 1; i <= barCount; i++) {
  data2.push(i * 3);
}

const data = {
  'labels': labels,
  datasets: [{
    label: 'Bar 1',
    data: data1,
    backgroundColor: 'rgba(100, 149, 237, 0.25)',
    barPercentage: 0.8
  }, {
    label: 'Bar 2',
    data: data2,
    backgroundColor: 'rgb(100, 149, 237,0.8)',
    barPercentage: 0.6
  }]
};

const canvas = document.getElementById('myChart');
const headerHeight = 75;
canvas.height = barCount * 25 + headerHeight;

const config = {
  type: 'bar',
  data: data,
  options: {
    maintainAspectRatio: false,
    indexAxis: 'y',
    scales: {
      x: {
        beginAtZero: true,
        position: 'top'
      },
      y: {
        beginAtZero: true,
        stacked: true
      }
    },
    plugins: {
      legend: {
        display: true
      },
      layout: {
        padding: {
          left: 20,
          right: 20
        }
      }
    }
  }
};

new Chart(canvas, config);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>

Leave a comment