Chartjs2将数据0设置为类型甜甜圈

时间:2017-07-14 11:46:33

标签: angular chart.js

我有一些圆环图的数据,但在开始时我想显示默认的圆环图和数据为0和相同大小的零件。 我把beginAtZero

JS

scales: {
    yAxes: [{
        ticks: {
            beginAtZero: true,
        }
    }]
}

但是数据的值为0,图表被隐藏我看不到任何图表。但我需要默认大小相等的图表值部分为0。 用圆环图可以吗?

示例:(但我想使值1到0,其中5个相等)

enter image description here

谢谢

1 个答案:

答案 0 :(得分:1)

是的!有可能。

要做到这一点,你需要做的是,用...生成圆环图

[1, 1, 1, 1, 1]

作为 data 数组,开头。

然后,使用以下工具提示回调函数,在工具提示上显示值 0

options: {
   tooltips: {
      callbacks: {
         label: function(t, d) {
            var isSame = d.datasets[t.datasetIndex].data.every(function(e) {
               return e === 1;
            });
            if (isSame) return d.labels[t.index] + ': ' + 0;
            else return d.labels[t.index] + ': ' + d.datasets[t.datasetIndex].data[t.index];
         }
      }
   },
   ...
}

这只会在工具提示中显示0,如果data数组的所有值都是1

ᴅᴇᴍᴏ⧩

var chart = new Chart(ctx, {
   type: 'doughnut',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         data: [1, 1, 1, 1, 1],
         backgroundColor: [
            'rgba(0, 119, 204, 0.8)',
            'rgba(0, 119, 204, 0.7)',
            'rgba(0, 119, 204, 0.6)',
            'rgba(0, 119, 204, 0.4)',
            'rgba(0, 119, 204, 0.3)'
         ],
      }]
   },
   options: {
      responsive: false,
      legend: false,

      tooltips: {
         callbacks: {
            label: function(t, d) {
               var isSame = d.datasets[t.datasetIndex].data.every(function(e) {
                  return e === 1;
               });
               if (isSame) return d.labels[t.index] + ': ' + 0;
               else return d.labels[t.index] + ': ' + d.datasets[t.datasetIndex].data[t.index];
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" height="200"></canvas>

ꜰʏɪ:您不能创建所有数据为0的图表,以使5个相等的部分。

相关问题