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

前端 未结 11 1941
面向向阳花
面向向阳花 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 20:54
    tooltips: {
        callbacks: {
            label: function (tooltipItem) {
                return (new Intl.NumberFormat('en-US', {
                    style: 'currency',
                    currency: 'USD',
                })).format(tooltipItem.value);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-07 20:56

    You need to make use of Label Callback. A common example to round data values, the following example rounds the data to two decimal places.

    var chart = new Chart(ctx, {
        type: 'line',
        data: data,
        options: {
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        var label = data.datasets[tooltipItem.datasetIndex].label || '';
    
                        if (label) {
                            label += ': ';
                        }
                        label += Math.round(tooltipItem.yLabel * 100) / 100;
                        return label;
                    }
                }
            }
        }
    });
    

    Now let me write the scenario where I used the label callback functionality.

    Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart. In my case it's 4, that's why length of datasets array is 4.

    In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.

    To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.

      callbacks: {
        label: function (tooltipItem, data) {
          console.log('data', data);
          console.log('tooltipItem', tooltipItem);
          let updatedToolTip: number;
          if (tooltipItem.datasetIndex == 0) {
            updatedToolTip = tooltipItem.yLabel;
          }
          if (tooltipItem.datasetIndex == 1) {
            updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
          }
          if (tooltipItem.datasetIndex == 2) {
            updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
          }
          if (tooltipItem.datasetIndex == 3) {
            updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
          }
          return updatedToolTip;
        }
      } 
    

    Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.

    0 讨论(0)
  • 2020-12-07 20:57

    In chart.js 2.1.6, I did something like this (in typescript):

      let that = this;
      options = {
        legend: {
          display: false,
          responsive: false
        },
        tooltips: {
          callbacks: {
            label: function(tooltipItem, data) {
              let account: Account = that.accounts[tooltipItem.index];
              return account.accountNumber+":"+account.balance+"€";
            }
          }
        }
      }
    
    0 讨论(0)
  • 2020-12-07 20:58

    This is what my final options section looks like for chart.js version 2.8.0.

            options: {
            legend: {
                display: false //Have this or else legend will display as undefined
            },
            scales: {
                //This will show money for y-axis labels with format of $xx.xx
                yAxes: [{
                  ticks: {
                    beginAtZero: true,
                    callback: function(value) {
                        return (new Intl.NumberFormat('en-US', {
                            style: 'currency',
                            currency: 'USD',
                        })).format(value);
                    }
                  }
                }]
            },
            //This will show money in tooltip with format of $xx.xx
            tooltips: {
                callbacks: {
                    label: function (tooltipItem) {
                        return (new Intl.NumberFormat('en-US', {
                            style: 'currency',
                            currency: 'USD',
                        })).format(tooltipItem.value);
                    }
                }
            }
        }
    

    I wanted to show money values for both the y-axis and the tooltip values that show up when you hover over them. This works to show $49.99 and values with zero cents (ex: $50.00)

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题