'ngx-charts-bar-horizontal data label formatting
I'm using ngx-charts more exactly bar-horizontal. What I'm trying to do is to format data label and add % at the end. I have tried to use [xAxisTickFormatting] but it doesn't work because, from what I noticed, my values are not on ngx-charts-x-axis but on ngx-charts-series-horizontal.
ngx-charts used as bellow:
<ngx-charts-bar-horizontal
*ngIf='givesEnergyChartData && givesEnergyDataColorScheme'
[scheme]="givesEnergyDataColorScheme"
[results]="givesEnergyChartData"
[gradient]="gradient"
[xAxis]="showXAxis"
[yAxis]="showYAxis"
[legend]="showLegend"
[view]="viewGiveEnergy"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[showDataLabel]="showDataLabel">
</ngx-charts-bar-horizontal>
Also I have tried to format on data array (I know it was stupid, but I have tried:) )
this.givesEnergyChartData = this.statistic.givesEnergyData.map(
s => {
return { name: s.name, value: s.count }
});
by adding for value: s.count + '%'.
So, what should I do to format the data labels and add '%' after values?
Solution 1:[1]
Try this.
<ngx-charts-bar-horizontal
*ngIf='givesEnergyChartData && givesEnergyDataColorScheme'
[scheme]="givesEnergyDataColorScheme"
[results]="givesEnergyChartData"
[gradient]="gradient"
[xAxis]="showXAxis"
[yAxis]="showYAxis"
[legend]="showLegend"
[view]="viewGiveEnergy"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[dataLabelFormatting] = "formatDataLabel"
[showDataLabel]="showDataLabel">
</ngx-charts-bar-horizontal>
and
formatDataLabel(value )
{
return value + '%';
}
Solution 2:[2]
You need this param [yAxisTickFormatting] and function like this in .ts file:
chart.component.ts
percentTickFormatting(val: any) {
return val.toLocaleString() + '%';
}
chart.component.html
<ngx-charts-bar-vertical
[view]="view"
[results]="chartData"
[xAxis]="true"
[yAxis]="true"
[legend]="true"
[showXAxisLabel]="true"
[showYAxisLabel]="true"
[yAxisTickFormatting]="percentTickFormatting"
>
</ngx-charts-bar-vertical>
Solution 3:[3]
I found a solution using querySelector and innerHTML like that:
document.querySelectorAll(text.textDataLabel).innerHTML += '%';
Solution 4:[4]
I add this code to CSS file for change the text style:
::ng-deep .ngx-charts .tick text {
text-anchor: start;
font-size: 20px !important;
color: red !important;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sree |
Solution 2 | nektobit |
Solution 3 | Sergiu Molnar |
Solution 4 | Dor Levi |