Chartjs-Django Chartjs outputs "No data" when data has value 0

1👍

The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to write the text "No Data" directly on the canvas using CanvasRenderingContext2D in case the sum of all data values is zero.

Please take a look at your amended code and see how it works.

new Chart('doughnutChart', {
  type: 'doughnut',
  plugins: [{
    afterDraw: function(chart) {
      let sum = chart.data.datasets[0].data.map(v => parseInt(v)).reduce((a, b) => a + b, 0);
      if (sum == 0) {
        let width = chart.chart.width,
          height = chart.chart.height + 35,
          ctx = chart.chart.ctx;
        ctx.save();
        let fontSize = (height / 200).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";
        let text = 'No Data',
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;
        ctx.fillText(text, textX, textY);
        ctx.restore();
      }
    }
  }],
  data: {
    labels: ['d1', 'd2'],
    datasets: [{
      data: ['0', '0'],
      backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C", "#949FB1", "#4D5360"],
      hoverBackgroundColor: ["#FF5A5E", "#5AD3D1", "#FFC870", "#A8B3C5", "#616774"]
    }]
  },
  options: {
    responsive: true
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="doughnutChart" height="80"></canvas>

Leave a comment