Chartjs-How to hide Fields and Strike-through Legends when the data is empty or Zero in Pie/Polar/Doughnut Chart?

0๐Ÿ‘

โœ…

I am posting this answer hoping that, it will be helpful for someone later. You can also post a better solution if found.

After some deep diving into the library the files, I realised that is there are no direct answers to my question. But we can achieve that by emptying the label text in case of 0 data values.

For that, we must edit the chart options as follows,

public pieChartOptions: ChartOptions = {
    responsive: true,
    legend: {
      position: 'top',
    },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
          const label = ctx.chart.data.labels[ctx.dataIndex];
          if (ctx.dataset.data[ctx.dataIndex] > 0)
            return label + " : " + ctx.dataset.data[ctx.dataIndex];
          else
            return "" // retun empty if the data for label is empty
        },
      }
    },
    showLines: true,
    spanGaps: true,
    cutoutPercentage: 1,
    rotation: 15, // rotate the chart
  };

Here in the function returns empty value in case the data for the corresponding label is 0. Also I rotate the chart 15deg to make the labels horizontal align in most cases.

Reference โ€“ Chart.js documentation

Hence I achieved a better view to the user and the overlapping issues are resolved. Thanks.

Leave a comment