[Chartjs]-Force ChartJS to show Doughnut chart with null values

0đź‘Ť

I found a quick work-around, not sure how “good” or “valid” way it is but it’s working for me. If the values are null/zero I replaced them with -1 to retain the looks of the chart and then use the custom tooltip function to override the output.

{
  ...
  data: [earned == 0 ? -1 : earned, pending == 0 ? -1 : pending]
  ...
},
options: {
  tooltip: {
    callbacks: {
       label: function (tooltipItem, data) {
              const value = data['datasets'][0]['data'][tooltipItem['index']];
              return '$' + (value == -1 ? 0 : value);
       }
    }
  }
}

Obviously I have 2 slices and when both are 0 the chart is displayed with 2 equal halves both showing $0 income (both earned and pending).

*Do note that this will still take 1 into account when others aren’t null so you need to take care of that on your end. I added a method to verify if ALL values are null and that’s the only case I display it like this.

-1đź‘Ť

A pie chart with all values equal to zero is ill-defined. Because the angle (and the area) of each slice is proportionate to the ratio of the slice’s respective value over the sum of all values. If all values are equal to zero, then their sum is zero. Division by zero should be rightfully avoided by the library (hopefully by design), resulting in the no-pie-chart case you encounter. It should be the programmer’s responsibility to detect the all-zeros case before populating the chart, if such a case has a possibility of occurring. Then the programmer could either display a “No data yet. What are you doing up so early? Go to sleep.” message, if all values are zero. Or, maybe, if they terribly need to keep the looks consistent (having a chart there all the time), they could show a special all-black no-data pie chart with the following dummy data:

var pieNoData = [
  {
    value: 1,
    color: "#000000"
  }
];

There is no shame in disclosing that no data exists yet, though.

Leave a comment