I am creating a bar chart using ng2 charts library. in the template I have added the following code
<div class="chart-wrapper">
<canvas baseChart
[datasets]="getBarChartData()"
[labels]="barChartLabels"
[options]="barChartOptions"
[plugins]="barChartPlugins"
[legend]="barChartLegend"
[chartType]="barChartType">
</canvas>
</div>
In component.ts file I have added the following lines of code, Here I am using a function depending on range I am changing the color of the bar dynamically, but the bar size is not shown properly if I use this line of code it works properly.
barChartData: ChartDataSets[] = [{
data: [80, 12, 200, 137, 164, 4, 10, 35],
label: 'A Bar Chart',
backgroundColor: ['#99ccff', '#808080']
}];
export class BarchartComponent {
constructor(private data: ChartService) {}
barChartOptions: ChartOptions = {
responsive: true
};
barChartLabels: Label[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
barChartType: ChartType = 'bar';
barChartLegend = true;
barChartPlugins = [];
getBarChartData() {
const dataSets = [80, 12, 200, 137, 164, 4, 10, 35];
const low = 2;
const high = 5;
const colors = [];
for (let i = 0; i < dataSets.length; i++) {
if (i >= (low - 1) && i <= (high- 1)) {
colors.push('#99ccff')
} else {
colors.push('#808080')
}
}
const barChartData: ChartDataSets[] = [{
data: dataSets,
label: 'A Bar Chart',
backgroundColor: colors
}];
return barChartData;
}
}
The problem is the bar graph values are not completely displayed. can someone help me how to set the data for bar with the above example.
The problem is related to Angular change detection that runs constantly and has to evaluate the
datasets
property of thecanvas
again and again. This way the chart is constantly updated and Chart.js can no longer draw it correctly.Avoid using the function
getBarChartData()
directly in theHTML
but create abarChartData
property in the component class instead.This
barChartData
property could be furnished in thengOnInit
method as follows:Please take a look at the following StackBlitz and see how it works.