Chartjs-Chartjs2 set data 0 to type doughnut

1👍

Yes! It is possible.

To accomplish this, what you have to do is, generate the doughnut chart with…

[1, 1, 1, 1, 1]

as the data array, at the beginning.

Then, use the following tooltips callback function, to show the value 0 on tooltip.

options: {
   tooltips: {
      callbacks: {
         label: function(t, d) {
            var isSame = d.datasets[t.datasetIndex].data.every(function(e) {
               return e === 1;
            });
            if (isSame) return d.labels[t.index] + ': ' + 0;
            else return d.labels[t.index] + ': ' + d.datasets[t.datasetIndex].data[t.index];
         }
      }
   },
   ...
}

this will only show 0 on tooltip, if all the values of data array is 1

ᴅᴇᴍᴏ ⧩

var chart = new Chart(ctx, {
   type: 'doughnut',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         data: [1, 1, 1, 1, 1],
         backgroundColor: [
            'rgba(0, 119, 204, 0.8)',
            'rgba(0, 119, 204, 0.7)',
            'rgba(0, 119, 204, 0.6)',
            'rgba(0, 119, 204, 0.4)',
            'rgba(0, 119, 204, 0.3)'
         ],
      }]
   },
   options: {
      responsive: false,
      legend: false,

      tooltips: {
         callbacks: {
            label: function(t, d) {
               var isSame = d.datasets[t.datasetIndex].data.every(function(e) {
                  return e === 1;
               });
               if (isSame) return d.labels[t.index] + ': ' + 0;
               else return d.labels[t.index] + ': ' + d.datasets[t.datasetIndex].data[t.index];
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" height="200"></canvas>

ꜰʏɪ : you cannot create chart with all data as 0, to make 5 equal parts.

Leave a comment