Reputation: 449
I want to make a chart which has percentage values on y-axis
but I'm not able to find any options in document. Please suggest some answers
Upvotes: 29
Views: 79788
Reputation: 2195
I used these options to add percentage to yAxes
:
const options = {
showLines: true,
scales: {
yAxes: [
{
ticks: {
min: 0,
max: 100,
stepSize: 20,
callback: function (value) {
return (value / this.max * 100).toFixed(0) + '%'; // convert it to percentage
},
},
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
gridLines: {
drawOnArea: false,
},
},
],
},
};
Upvotes: 3
Reputation: 19014
With Chart.js 3 you can do this:
const options = {
scales: {
y: {
ticks: {
format: {
style: 'percent'
}
}
}
}
};
Upvotes: 19
Reputation: 2121
Of using the toLocaleString
function
scales: {
yAxes: [
{
ticks: {
callback: function (value) {
return value.toLocaleString('de-DE', {style:'percent'});
},
}
},
],
},
Upvotes: 2
Reputation: 8459
You could do something like this:
If you know the absolute value that represents 100% in your dataset, you can pass this to your options object:
scales: {
yAxes: [
{
ticks: {
min: 0,
max: this.max,// Your absolute max value
callback: function (value) {
return (value / this.max * 100).toFixed(0) + '%'; // convert it to percentage
},
},
scaleLabel: {
display: true,
labelString: 'Percentage',
},
},
],
},
Upvotes: 27
Reputation: 3482
If you have a static total...say a max value of 800, you can just show custom ticks like this:
ticks: {
//.. Other settings
stepSize: 200, /* total/4 shows 0, 25%, 50%, 75%, 100% */
callback: function(value, index, values) {
return ((value / 800) * 100) + '%';
}
}
Upvotes: 6
Reputation: 3026
Don't think there is a out of the box version of that yet. You might have to do it a bit manually by calculating the percentages before setting the chart up and e.g. follow this example to create the graph: https://stackoverflow.com/a/40438511/6638478
Upvotes: 5