7π
β
Here an example working with chart.js 2.8.0
<canvas id="pieChartExample01" width="25" height="25"></canvas>
<div id="no-data">Nothing to display</div>
...
options: {
title: {
display: false,
text: 'Overall Activity'
},
animation: {
onComplete: function(animation) {
var firstSet = animation.chart.config.data.datasets[0].data,
dataSum = firstSet.reduce((accumulator, currentValue) => accumulator + currentValue);
if (typeof firstSet !== "object" || dataSum === 0) {
document.getElementById('no-data').style.display = 'block';
document.getElementById('pieChartExample01').style.display = 'none'
}
}
}
}
19π
Use this plugin I slightly modified which checks if each dataset item is zero:
<script>
Chart.plugins.register({
afterDraw: function(chart) {
if (chart.data.datasets[0].data.every(item => item === 0)) {
let ctx = chart.chart.ctx;
let width = chart.chart.width;
let height = chart.chart.height;
chart.clear();
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('No data to display', width / 2, height / 2);
ctx.restore();
}
}
});
</script>
With this, if all dataset items are 0, it will display No data to display
in place of the chart.
3π
For React
(react-chartjs-2)
Use this plugin
const plugins = [
{
afterDraw: function (chart) {
console.log(chart);
if (chart.data.datasets[0].data.length < 1) {
let ctx = chart.ctx;
let width = chart.width;
let height = chart.height;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "30px Arial";
ctx.fillText("No data to display", width / 2, height / 2);
ctx.restore();
}
},
},
];
Use this plugin
<Line height={120} data={props.data} options={options} plugins={plugins} />
<Pie height={320} width={500} data={props.data} options={options} plugins={plugins} />
2π
For those using version 3.x of the library, hereβs how I did it
const plugin = {
id: 'emptyChart',
afterDraw(chart, args, options) {
const { datasets } = chart.data;
let hasData = false;
for (let dataset of datasets) {
//set this condition according to your needs
if (dataset.data.length > 0 && dataset.data.some(item => item !== 0)) {
hasData = true;
break;
}
}
if (!hasData) {
//type of ctx is CanvasRenderingContext2D
//https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
//modify it to your liking
const { chartArea: { left, top, right, bottom }, ctx } = chart;
const centerX = (left + right) / 2;
const centerY = (top + bottom) / 2;
chart.clear();
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('No data to display', centerX, centerY);
ctx.restore();
}
}
};
And just use the above like so:
const chart1 = new Chart(ctx, {
plugins: [plugin]
});
-5π
You need to set some data in data: [0, 0, 0, 0]
Itβs imposible to display pie graph without any data i try to change only data and all itβs good.
...
data: [2, 3, 4, 5]
...
Source:stackexchange.com