JavaScript Chart.js - Custom data formatting to display on tooltip

前端 未结 11 2055
面向向阳花
面向向阳花 2020-12-07 20:13

I have looked at various documentation and similar questions on here, but cannot seem to find the particular solution. Apologies if I have missed anything obvious or have re

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 21:05

    In Chart.Js 2.8.0, the configuration for custom tooltips can be found here: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback (Thanks to @prokaktus)

    If you want to e.g. show some values with a prefix or postfix (In the example, the script adds a unit of kWh to the values in the chart), you could do this like:

    options: {
      rotation: 1 * Math.PI,
      circumference: 1 * Math.PI,
      tooltips: {
        callbacks: {
          label: function(tooltipItem, data) {
            console.log(data);
            console.log(tooltipItem);
    
            var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] || '';
    
            if (label) {
              label += ' kWh';
            }
    
            return label;
          }
        }
      }
    }
    

    An example fiddle is here, too: https://jsfiddle.net/y3petw58/1/

提交回复
热议问题