<!DOCTYPE html>
<
html
>
<
body
>
<
canvas
id
=
"myChart"
></
canvas
>
<
script
src
=
</
script
>
<
script
>
// Define percentage scale class
class PercentageScale extends Chart.Scale {
// Constructor
constructor(cfg) {
super(cfg);
this._startValue = 0;
this._endValue = 100;
}
// Determine the data limits (mandatory)
determineDataLimits() {
this.min = this._startValue;
this.max = this._endValue;
}
// Build ticks (mandatory)
buildTicks() {
this.ticks = []; // Initialize tick array
for (let i = this.min; i <= this.max; i += 10) {
this.ticks.push({ value: i });
}
}
generateTickLabels(ticks) {
ticks.
forEach(tick => tick.label = `${tick.value}%`);
}
// Calculate pixel for value (mandatory)
getPixelForValue(value) {
const pixel =
(value - this.min) /
(this.max - this.min) *
this.width;
return this.isHorizontal() ? pixel : this.bottom - pixel;
}
// Calculate value for pixel (mandatory)
getValueForPixel(pixel) {
const value =
this.min + (pixel / this.width) * (this.max - this.min);
return this.isHorizontal() ? value : this.bottom - value;
}
}
// Set id for the custom scale
// The id should match the type in the chart config
PercentageScale.id = 'PercentageScale';
// Default settings
PercentageScale.defaults = {};
// Register the custom scale
Chart.register(PercentageScale);
// Create chart instance
new Chart('myChart', {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'Dataset 1',
data: [1125, 2500, 750],
backgroundColor: ['rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'], // Optional colors
}]
},
options: {
scales: {
y: {
type: 'PercentageScale'
}
}
}
});
</
script
>
</
body
>
</
html
>