javascript

Assign fixed width to the columns of bar chart in Chart.js

If you want to assign a fixed width to the bars of the bar chart created using the Chart.js library. You can use barThickness property of datasets.

var ctx = document.getElementById("my_chart").getContext("2d");

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Label 1", "Label 2", "Label 3", "Label 4"],
        datasets: [{
            label: "Title on top",
            data: [50, 40, 60, 80],
            backgroundColor: "#1491e5",
            barThickness: 30 // Assign your width here
        }]
    },
    options: {
    	maintainAspectRatio: false
    }
});

We are using barThickness property of datasets in Chart.js to assign a fixed thickness to the bars of the bar chart. Here, we have created a bar chart that has four data points that mean there will be four bars in the bar chart. As we know Chart.js will assign own with to these bars according to the width of the chart. But if you want to assign your own width to these bars, you can use barThickness property.

Here, value 30 is assigned to barThickness property that means the width of each bar will be 30px.

Live Demo

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

<canvas id="my_chart" width="400" height="200" ></canvas>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script>
var ctx = document.getElementById("my_chart").getContext("2d");

new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Jan", "Feb", "Mar", "Apr"],
        datasets: [{
            label: "Months Revenue",
            data: [90, 80, 30, 50],
            backgroundColor: "#1491e5",
            barThickness: 30
        }]
    }
});
</script>
The HTML code is an example of a bar chart that will create a bar chart having fixed-width column bars.
Was this helpful?