How to set width of bar dynamically in chart.js?

Member

by dana , in category: Javascript , 10 months ago

How to set width of bar dynamically in chart.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 10 months ago

@dana 

To set the width of a bar dynamically in Chart.js, you can use the barPercentage and categoryPercentage properties in the options object.

  1. Determine the desired width of the bars as a percentage of the available space. For example, if you want the bars to be 70% of the available space, set barPercentage to 0.7.
1
2
3
4
5
6
7
var options = {
  scales: {
    x: {
      barPercentage: 0.7,
    },
  },
};


  1. If you want the bars to have equal width regardless of the number of bars or the available space, set categoryPercentage to 1.
1
2
3
4
5
6
7
var options = {
  scales: {
    x: {
      categoryPercentage: 1,
    },
  },
};


  1. You can also set different widths for different bars by providing an array of percentages for the barPercentage or categoryPercentage properties. For example, if you have three bars and you want the first bar to be 80% wide, the second bar to be 60% wide, and the third bar to be 40% wide, you can set barPercentage to [0.8, 0.6, 0.4].
1
2
3
4
5
6
7
var options = {
  scales: {
    x: {
      barPercentage: [0.8, 0.6, 0.4],
    },
  },
};


  1. Apply the options object to the chart configuration.
1
2
3
4
5
var chart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options,
});


By adjusting the barPercentage and categoryPercentage properties, you can dynamically set the width of the bars in Chart.js based on your requirements.