2
votes

I have below Piechart using chartjs. I need to show a "No Data" message on it when there is nothing to show.

But I am unable to find such a way in chartjs tutorials. Can someone please help?

Pie Chart HTML

<div id="canvas-holder-CT" style="width:46%;float:right;position: absolute; left: 0px; top: 700px;">
    <canvas id="chart-area-CT" width="350" height="450" style="display: block; margin-left:2em">
    </canvas>
    <center> <b><details>
      <summary>Distribution by Call Types</summary>
    </details> </b></center>
</div>

Pie chart script

var configCT = {
    type : 'pie',
    data : {
        datasets : [{
                data : valuesCT,
                backgroundColor : coloringCT,
                label : 'Distribution by Call Types'
            }
        ],
        labels : labelsCT
    },
    options : {
        segmentShowStroke : false,
        legend : false,
        animateScale : true,
        responsive : true,
        showAllTooltips : false,
        tooltips : {
            custom : function (tooltip) {
                if (!tooltip)
                    return;
                tooltip.displayColors = false;
            }
        }
    }
};

var ctxCT = document.getElementById("chart-area-CT").getContext("2d");
if (myPieCT != null) {
    myPieCT.destroy();
}
myPieCT = new Chart(ctxCT, configCT);
2

2 Answers

12
votes

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
votes

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");
}