javascript

Assign a fixed height to chart in Chart.js

By default, Chart.js maintains the aspect ratio with the width and height of the chart. If you want to assign a fixed height to a chart you can set maintainAspectRatio property to false.

<canvas id="myChart" width="400" height="300"></canvas>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script>
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5', 'Label 6'],
            datasets: [{
                label: 'Title',
                data: [10, 20, 50, 30, 20]
            }]
        },
        options: {
            maintainAspectRatio: false // This will fix the height
        }
    });
</script>

A live demo for the above code snippet can be found below.

Was this helpful?