如何隐藏/不使用 0/null/undefined 值绘制条形图?

How to hide / not draw bars with 0 / null / undefined values?

如何隐藏错误的值? (0、空或未定义)

我试过

new Chart(this.barCanvas.nativeElement, {

    ...

     data: {
            datasets: [{
                     data: [
                             value < 1 ? null : value,
                             value2 < 1 ? null : value2,
                             valueX < 1 ? null : valueX,
                     ],
            }],
    },
    options: {
            skipNull: true,
    }

    ...

}

但是没用。

我在 SOF 上发现了一些类似的 post,但没有答案或有效的解决方案

受 LeeLenalee 回答和 zhulien 评论的启发,我创建了一个变量 chartData,我在传递它之前对其进行过滤。

但是传递变量 chartData 会在 data 上产生类型错误(复制过去 chartData 的对象并直接传递它不会产生类型错误,但是视图图表未加载)

indexToRemove是一个索引数组,基于0

的数据
var chartData = {
      labels: ['Batterie faible', 'Maintenance', 'HS', 'Place libre', 'Place occupée'].filter((v, i) => indexToRemove.includes(i)),
      datasets: [{
        label: '',
        data: data.filter((v, i) => indexToRemove.includes(i)),
        backgroundColor: [
          '#F6741A',
          '#dc2625',
          '#B91C1B',
          '#22c55e',
          '#FACC14'
        ].filter((v, i) => indexToRemove.includes(i)),
        borderRadius: 4,
        borderSkipped: false,
      }]
    }

    new Chart(this.barCanvas.nativeElement, {
      type: 'bar',
      data: chartData, // <- Type error (But replacing by the object correct the type error but still does not work as said above)
    ...
    }

您可以先过滤数据,然后再使用对象表示法:

let initialData = [{
    "x": "label1",
    "y": 9
  },
  {
    "x": "label2",
    "y": 0
  },
  {
    "x": "label3",
    "y": 5
  },
  {
    "x": "label4",
    "y": 10
  },
  {
    "x": "label6",
    "y": null
  },
  {
    "x": "label7",
    "y": 3
  },
  {
    "x": "label8",
    "y": undefined
  }
];
let data = initialData.filter(e => e.y);

const options = {
  type: 'bar',
  data: {
    datasets: [{
      label: '# of Votes',
      data: data,
      backgroundColor: 'pink',
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>