2 thoughts on “Show Message When Chart Has No Data

  1. If you want to add your chart title to the example below, you can do it whis way:

    A plugin is the best way to solve this. See https://jsfiddle.net/x04ptfuu/

    And then just add one line

    ctx.fillText(chart.options.title.text, width / 2, 18); // <====   ADDS TITLE
    

    in this example

    Chart.plugins.register({
    	afterDraw: function(chart) {
    		console.log('After draw: ', chart);
    		console.log('Title: ', chart.options.title.text);
    		console.log(chart.data.datasets[0].data.length,  chart.canvas.id, chart.data.datasets[0].data);
    		if (chart.data.datasets[0].data.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'";
    			// chart.options.title.text <=== gets title from chart 
    			// width / 2 <=== centers title on canvas 
    			// 18 <=== aligns text 18 pixels from top, just like Chart.js 
    			ctx.fillText('My Chart Title', width / 2, 18); // <====   ADDS TITLE
    			ctx.fillText('No data to display for selected time period', width / 2, height / 2);
    			ctx.restore();
    		}
    	}
    });
    

Comments are closed.