[Chartjs]-Show "No Data" message for Pie chart with no data

12👍

Have you checked this open issue?

And the relative solution proposed by etimberg user:

Chart.plugins.register({
    afterDraw: function(chart) {
    if (chart.data.datasets.length === 0) {
        // No data is present
      var ctx = chart.chart.ctx;
      var width = chart.chart.width;
      var height = chart.chart.height
      chart.clear();

      ctx.save();
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = "16px normal 'Helvetica Nueue'";
      ctx.fillText('No data to display', width / 2, height / 2);
      ctx.restore();
    }
  }
});

See: https://jsfiddle.net/x04ptfuu/

1👍

Could be handle by CSS display property.

foo.html

<div id="showId" class="showData">
  <canvas id="myChart"></canvas>
</div>
<div id="noId" class="noData">
  <span>No Data Available</span>
<div>

foo.css

.showData {
   display: block;
}

.noData {
   display: none;
}

foo.js

// ...code
if(chartData) {
  document.getElementById("showId").classList.add("showData");
  document.getElementById("noId").classList.remove("noData");
} else {
  document.getElementById("showId").classList.remove("showData");
  document.getElementById("noId").classList.add("noData");
}

Leave a comment