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

czfnxgou  于 2022-11-07  发布在  Chart.js
关注(0)|答案(2)|浏览(185)

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

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>

这就是ng2 chart的外观
我希望,只有当值为而不是0时,才会显示这些值。如果我设置

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

但如果我用中心的话,我也想工作。
先谢谢你
干杯
大卫

rt4zxlrg

rt4zxlrg1#

我找到了解决办法:

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

svujldwt2#

你可以使用formatter函数,如果值大于0则返回它,否则返回一个空字符串:
第一个

相关问题