2

Is it possible to edit tooltip of Piechart, from the React-chartjs-2 lib to allow it to show percentage instead of default value preview?

<Pie
   data={this.props.data}
   legend={this.props.legend}
/>

Documentation on the link above it way non clear about customizing tooltips.

PieChart

I would like to enable tooltip to represent percentage too, instead of 'cancelled: 303' to show something like 'cancelled: 303 (40%)'.

Lululu
  • 675
  • 3
  • 9
  • 21

3 Answers3

9
const data = {
  labels: [
    'MFA',
    'NON-MFA'
  ],
  datasets: [{
    data: [5667, 223829],
    backgroundColor: [
    '#FF6384',
    '#36A2EB'
    ],
    hoverBackgroundColor: [
    '#FF6384',
    '#36A2EB'
    ]
  }]
};

const option = {
  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];
      }
    }
  }
}

Then in the render part, put:

<Pie data={data} options={option} />
DemiJiang
  • 93
  • 1
  • 6
0

Using ._meta no longer worked for me to get the total. Instead, I used DemiJiang's answer and got the total via:

let total = 0;
for (let i = 0; i < data.datasets.length; i++) {
  total += data.datasets[i].data[tooltipItem.index];
}

So my whole label callback in TypeScript looked like:

static numberWithPercentageLabel(tooltipItem: any, data: any) {
  const dataset = data.datasets[tooltipItem.datasetIndex];
  const currentValue = dataset.data[tooltipItem.index];
  let total = 0;
  for (let i = 0; i < data.datasets.length; i++) {
    total += data.datasets[i].data[tooltipItem.index];
  }
  const percentage = (currentValue / total * 100).toFixed(0);
  return `${currentValue} (${percentage}%)`;
}
Sarah Vessels
  • 30,930
  • 33
  • 155
  • 222
0
tooltips: {
    callbacks: {
        label: (tooltipItem, data) => {
            const dataset = data.datasets[tooltipItem.datasetIndex];
            const meta = dataset._meta[Object.keys(dataset._meta)[0]];
            const total = meta.total;
            const currentValue = tooltipItem?.value;
            const percentage = parseFloat((currentValue/total*100).toFixed(1));
            return currentValue + ' (' + percentage + '%)';
        },
        title: tooltipItem =>
            `${tooltipItem[0]?.label}`
    }
},
Diego Díaz
  • 389
  • 4
  • 4