如果数据集为空,则Chart.js饼图将显示“无数据”

时间:2018-10-10 08:57:45

标签: javascript chart.js

如果饼图中没有数据,我试图显示“无数据可显示”。如果图表是折线,则效果很好,但是如果是饼图,则不起作用。我已经包括了该插件,但是仍然可以得到想要的输出。让我知道我在哪里做错

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

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
	type: 'line',
  data: {
  	labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: []
  }
});

var ctx2 = document.getElementById('chart2').getContext('2d');
var myChart2 = new Chart(ctx2, {
	type:'pie',
  data:{
  	labels:['Jan', 'Feb', 'Mar', 'Apr'],
    datasets:[{
    	data:[],
      backgroundColor: ['red','blue','green','yellow']
    }]
  }
});

var ctx3 = document.getElementById('chart3').getContext('2d');
var myChart3 = new Chart(ctx3, {
	type: 'pie',
  data: {
  	labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: []
  }
});
<canvas id="chart"></canvas>
<canvas id="chart2"></canvas>
<canvas id="chart3"></canvas>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>

2 个答案:

答案 0 :(得分:0)

尝试一下:

var ctx2 = document.getElementById('chart2').getContext('2d');
var myChart2 = new Chart(ctx2, {
    type:'pie',
    data:{
      labels:['Jan', 'Feb', 'Mar', 'Apr'],
      datasets:[]
    }
});

答案 1 :(得分:0)

我在有角度的应用程序中所做的就是复制我的甜甜圈图。

通过css类position: absolute; z-index: 1;给占位符一个.placeholder-chart

.real-chart {
    position: relative;
    z-index: 2;
}

.placeholder-chart {
    position: absolute;
    z-index: 1;
}

然后我将图表数据初始化为100%,并根据需要初始化背景颜色:

options: {
    "aspectRatio": 1.75,
    "legend": {
        "display": false,
    },
    "title": {
        "display": false,
    },
    "rotation": - Math.PI,
    "circumference": Math.PI
}

realData: {
    // My real data, which result 0 in this case
}

placeholderData: {
    "labels": "",
    "datasets": [
        {
           "label": [""],
           "data": [100],
           "backgroundColor": "#F2EEE8"
        }
    ]
}

我的模板:

<chart
    class="placeholder-chart"                                
    [type]="'doughnut'"
    [data]="placeholderData"
    [options]="options"></chart>
<chart
    class="real-chart"
    [type]="'doughnut'"
    [data]="realData"
    [options]="options"></chart>

在图片1中,我只有一条黄色的细零线

enter image description here

在图片2中,我有2个图表-占位符1比实际占位符

enter image description here

在图片3中,然后是重叠的两个图表

enter image description here