Topic: Format the Y-axis display values of Bar Chart and Stacked Bar Chart
1001albertpadilla asked 5 years ago
How do you format the Y-axis display values of Bar Chart and Stacked Bar Chart? Right now I got the following values in vertical Y-axis:
30000000 25000000 20000000
I want to display them to something like: 300 M 250 M 200 M
Is there a way to do this? Thanks!
Bartosz Termena staff answered 5 years ago
Dear @1001albertpadilla
To do this, you need to override the ticks.callback
method in the axis configuration. In the following example, every number between 10000 and 1 trillion would be written as NK. For example: 321K
, 981K
, 1M
, 102M
TS:
public chartOptions: any = {
responsive: true,
scales: {
xAxes: [
{
stacked: true,
},
],
yAxes: [
{
ticks: {
// Include a dollar sign in the ticks
callback: function(value: any) {
// 2 decimal places => 100, 3 => 1000, etc
let decPlaces = 2;
decPlaces = Math.pow(10, decPlaces);
// Enumerate number abbreviations
const abbrev = ['K', 'M', 'B', 'T'];
// Go through the array backwards, so we do the largest first
for (let i = abbrev.length - 1; i >= 0; i--) {
// Convert array index to "1000", "1000000", etc
const size = Math.pow(10, (i + 1) * 3);
// If the number is bigger or equal do the abbreviation
if (size <= value) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
value = Math.round((value * decPlaces) / size) / decPlaces;
// Handle special case where we round up to the next abbreviation
if (value === 1000 && i < abbrev.length - 1) {
value = 1;
i++;
}
// Add the letter for the abbreviation
value += abbrev[i];
// We are done... stop
break;
}
}
return value;
},
},
stacked: true,
},
],
}
}
Hope it helps!
Best Regards, Bartosz.
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Resolved
- User: Free
- Premium support: No
- Technology: MDB Angular
- MDB Version: 7.5.3
- Device: Laptop
- Browser: Chrome
- OS: Win 10
- Provided sample code: No
- Provided link: No