Chart.js 2.0 doughnut tooltip percentages

后端 未结 3 1339
星月不相逢
星月不相逢 2021-01-30 03:57

I have worked with chart.js 1.0 and had my doughnut chart tooltips displaying percentages based on data divided by dataset, but I\'m unable to replicate this with chart 2.0.

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 04:30

    For those who want to display dynamic percentages based on what currently displayed on the chart (not based on total data), you can try this code:

     tooltips: {
        callbacks: {
          label: function(tooltipItem, data) {
            var dataset = data.datasets[tooltipItem.datasetIndex];
            var meta = dataset._meta[Object.keys(dataset._meta)[0]];
            var total = meta.total;
            var currentValue = dataset.data[tooltipItem.index];
            var percentage = parseFloat((currentValue/total*100).toFixed(1));
            return currentValue + ' (' + percentage + '%)';
          },
          title: function(tooltipItem, data) {
            return data.labels[tooltipItem[0].index];
          }
        }
      },
    

提交回复
热议问题