I have a question regarding ng2 charts. This is my component.ts file.
public barChartOptions: ChartConfiguration['options'] = {
responsive: true,
// We use these empty structures as placeholders for dynamic theming.
scales: {
x: {},
y: {
min: 10
}
},
plugins: {
legend: {
display: true,
},
datalabels: {
anchor: 'center',
align: 'center'
}
}
};
public barChartType: ChartType = 'bar';
public barChartPlugins = [
DataLabelsPlugin
];
public barChartData: ChartData<'bar'> = {
labels: [ '2006', '2007', '2008', '2009', '2010', '2011', '2012' ],
datasets: [
{ data: [ 65, 59, 80, 81, 56, 55, 40 ], label: 'Series A' , stack: 'a',},
{ data: [ 28, 48, 40, 19, 86, 27, 90 ], label: 'Series B' , stack: 'a',},
{ data: [ 28, 48, 0, 19, 86, 27, 90 ], label: 'Series C', stack: 'a', },
{ data: [ 28, 0, 90, 79, 66, 7, 9 ], label: 'Series D', stack: 'a', },
]
};
public randomize(): void {
// Only Change 3 values
this.barChartData.datasets[0].data = [
Math.round(Math.random() * 100),
59,
80,
Math.round(Math.random() * 100),
56,
Math.round(Math.random() * 100),
40 ];
}
This is my component.html file
<div>
<div>
<div style="display: block">
<canvas baseChart
[data]="barChartData"
[options]="barChartOptions"
[plugins]="barChartPlugins"
[type]="barChartType">
</canvas>
</div>
<button mat-button mat-raised-button color="primary" (click)="randomize()">Update</button>
</div>
</div>
This is how it looks like ng2 chart
I want, that the values only get displayed, if they are not 0 It works, if I set
datalabels: {
anchor: 'end',
align: 'end'
}
But I want to work as well, if I use center.
Thanks in advance
Cheers
David
CodePudding user response:
I found a solution:
datalabels: {
anchor: 'center',
align: 'center',
display: function(context) {
return context.dataset.data[context.dataIndex]! >= 6; // or >= 1 or ...
}
}
CodePudding user response:
You can use the formatter
function for this, if the value is bigger then 0 return it, else return an empty string:
Chart.register(ChartDataLabels)
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 0, 5, 2, 3],
backgroundColor: 'pink'
}]
},
options: {
plugins: {
datalabels: {
color: 'red',
formatter: (val) => (val > 0 ? val : '')
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>