仅当标签值> 0 时才显示数据标签



我有一个关于ng2图表的问题。这是我的组件。文件。

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 ];
}

这是我的component.html文件

<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>

它看起来是这样的喜欢的《忍者外传2》图

我想让值只在不是0时才显示它的工作原理,如果我设置

datalabels: {
anchor: 'end',
align: 'end'
}

但是我也想工作,如果我使用居中

Thanks in advance

欢呼大卫

您可以使用formatter函数进行此操作,如果值大于0则返回它,否则返回空字符串:

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>

我找到了一个解决方案:

datalabels: {
anchor: 'center',
align: 'center',
display: function(context) {
return context.dataset.data[context.dataIndex]! >= 6; // or >= 1 or ...
}
}

最新更新