[Chartjs]-Chart.js aspect ratio / forced height

29👍

Try to set these options:

options: {
  responsive: true,
  maintainAspectRatio: false
}

If you set maintainAspectRatio to true, the height will be automatically calculated.

7👍

Actually in Chart.js 3.2.1 to update the aspect ratio to add more height to your scheme you can use the aspectRatio option:

options: {          
   aspectRatio: 1, 
}

And so according to the documentation:

Canvas aspect ratio (i.e. width / height, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style.

You can set it such as:

  • 1 for it to be square
  • 0.5 to be twice as high as wide
  • 2 to be twice as wide as high

2👍

Use maintainAspectRatio and responsive

  options: {
     responsive: true,
     maintainAspectRatio: false,
  }
let chart = new Chart('myChart', {

type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.2/dist/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

1👍

enter image description here

const config = {
  type: 'bar',
  data,
  options: {
      responsive: true,
      maintainAspectRatio: false
  }
};
var yourChart= new Chart(
    document.getElementById('chartCanvas'),
    config
  );
});
yourChart.canvas.parentNode.style.height = '480px'; 
yourChart.canvas.parentNode.style.width = '280px'; 
 

Leave a comment