Reputation: 549
I have created a chart using ngx-chart. The x-axis should populate year. My array of year currently has values: 2020, 2021,2022,2023. However when it is displayed in the chart, it automatically adds 2020.5, 2021.5, ...
The value has to be number in order to sort the year in ascending order. Is there a way to prevent the decimal from being autogenerated?
Typescript:
setChartValue(items: any[]): void {
let chartValues = [];
items.forEach((item) => {
chartValues.push({
'name': moment(item.purchaseDate, "DD/MM/YYYY").year(),
'value': item.purchasePrice
});
})
this.multi = [
{
'name': 'Purchase Summary',
'series': chartValues
}
];
}
Html:
<ngx-charts-line-chart [view]="view"
[scheme]="colorScheme"
[results]="multi"
[gradient]="gradient"
[xAxis]="showXAxis"
[yAxis]="showYAxis"
[legend]="showLegend"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[xAxisLabel]="xAxisLabel"
[yAxisLabel]="yAxisLabel"
[autoScale]="autoScale"
[timeline]="timeline">
</ngx-charts-line-chart>
Upvotes: 5
Views: 1731
Reputation: 3041
Ok, I have an answer, not sure if it's possible to configure ngx-chart to prevent decimals to fill the gaps, but I found an "elegant" solution by using this formula.
As you see I have the same problem here but with Months, I have just 4 months, but the xAxis is repeating them 5 times to fill the graph and cover the width.
Solution: Add this to your HTML attributes for the ngx-chart
[xAxisTickFormatting]="xAxisFormat"
then your method in the TS file should look like this:
xAxisFormat(val : any) {
if (val % 1 > 0) return "";
return val ;
}
Result working, not showing repeated values anymore:
The reasson why this works, the following line will return EMPTY to the graph, if the val
has a decimal value, if the number is an integer, it will be returned properly, and this will look like the value was not repeated.
if (val % 1 > 0) return "";
Hope it helps.
Upvotes: 5
Reputation: 61
I have a similar situation on the y axis that might help. In the html for the chart I added [yAxisTickFormatting]="yAxisTickFormattingFn"
In the class definition I added: public yAxisTickFormattingFn = this.yAxisTickFormatting.bind(this);
yAxisTickFormatting(value) {
return value;
}
I don't know why this would change anything, but it removed the '.0' for the y axis values.
Upvotes: 5