Chartjs-Chart js: when all the values passed to data are zeros, nothing is showing

4👍

Show chart when all data values are zero

This can be achieved in a more elegant way using the following chart plugin :

Chart.plugins.register({
   beforeInit: function(chart) {
      var data = chart.data.datasets[0].data;
      var isAllZero = data.reduce((a, b) => a + b) > 0 ? false : true;
      if (!isAllZero) return;
      // when all data values are zero...
      chart.data.datasets[0].data = data.map((e, i) => i > 0 ? 0 : 1); //add one segment
      chart.data.datasets[0].backgroundColor = '#d2dee2'; //change bg color
      chart.data.datasets[0].borderWidth = 0; //no border
      chart.options.tooltips = false; //disable tooltips
      chart.options.legend.onClick = null; //disable legend click
   }
});

* add this at the beginning of your script

note: make sure to use the latest version of ChartJS, which is 2.6.0 atm.

see – working example

1👍

You can add some CSS that gives a background to the canvas when chart is not drawn onto it:

canvas {
  background: radial-gradient(circle at center, rgba(0,0,0,0) 0, rgba(0,0,0,0) 55%, rgba(0,0,0,0.2) 56%, rgba(0,0,0,0.2) 60%, rgba(0,0,0,0.2) 64%, rgba(0,0,0,0) 65%,rgba(0,0,0,0) 100%);
}

Here’s the fiddle: http://jsfiddle.net/Nisarg0/9mby62w4/7/

I would ideally apply the radial-gradient when I know for a fact that the values are zero – so the CSS selector would be something like canvas.no-data, and I would add the class .no-data to the canvas only when the values are zero.

Leave a comment