Chart.js 2.0 doughnut tooltip percentages

后端 未结 3 1383
星月不相逢
星月不相逢 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:39

    I came across this question because I needed to show percentage on stacked bar charts. The percentage I needed was per stacked columns. I accomplished this by modifying Willian Surya's answer like this:

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

    This is the final result:

提交回复
热议问题