Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-chartjs-2: Pie Chart tooltip percentage

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%)'.

like image 346
Lululu Avatar asked Mar 12 '26 09:03

Lululu


1 Answers

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} />
like image 193
DemiJiang Avatar answered Mar 13 '26 23:03

DemiJiang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!