<!DOCTYPE html>
<
html
>
<
head
>
<
title
>Example 2</
title
>
<
script
src
=
</
script
>
<
style
>
h1 {
color: green;
}
</
style
>
</
head
>
<
body
>
<
h1
>GeeksforGeeks</
h1
>
<
h3
>
Approach 2: Using categoryPercentage Property
</
h3
>
<
label
for
=
"categoryPercentageInput"
>
Bar Width Percentage:
</
label
>
<
input
type
=
"number"
id
=
"categoryPercentageInput"
value
=
"70"
>
<
button
onclick
=
"chartUp()"
>Update Chart</
button
>
<
canvas
id
=
"barChart"
></
canvas
>
<
script
>
let categoryPercentageValue = 70;
const data = {
labels: ['JavaScript', 'Python', 'Java', 'C++', 'Ruby'],
datasets: [{
label: 'Monthly Users',
data: [5000, 8000, 6000, 7000, 9000],
backgroundColor: ['rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)', 'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)'],
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)'],
borderWidth: 1
}]
};
const config = {
type: 'bar',
data: data,
options: {
scales: {
x: {
beginAtZero: true
},
y: {
beginAtZero: true
}
},
categoryPercentage: categoryPercentageValue / 100
}
};
const ctx = document.getElementById('barChart').getContext('2d');
const myChart = new Chart(ctx, config);
function chartUp() {
categoryPercentageValue = parseInt(document
.getElementById('categoryPercentageInput').value, 10) || 70;
config.options.categoryPercentage = categoryPercentageValue / 100;
myChart.update();
}
</
script
>
</
body
>
</
html
>