How to reformat tooltip in Chart.js?
Asked Answered
R

4

12

How to reformat tooltip in Chart.js? The chart has x-axis as time, y-axis as sales amount and tooltip to show data value for both x and y. So far tooltip can work by default but I want to change the value we see in tooltip. I can reformat the time in tooltip by redefine the tooltipFormat field in 'time'. But I don't find a similar thing for y-axis data. For example, show "$1600" instead of "Daily Ticket Sales:1600".
example tooltip format image

Could anyone tell me where should that change happen?

Could the 'custom' callback function solve problem here? Here is the code, thanks!

    var dates=data.linechart.dates;
    var times=[];
    for (var i=0; i<dates.length; i++) {
        times.push(moment(dates[i],'YYYY/MM/DD'));
    }
    // console.log(dates);
    // console.log(times);

    var salesData = {
    labels: times,

    datasets: [
        {
            label: "Daily Ticket Sales",
            fill: false,
            lineTension: 0,
            backgroundColor: "#fff",
            borderColor: "rgba(255,88,20,0.4)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(255,88,20,0.4)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(255,88,20,0.4)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 3,
            pointHitRadius: 10,
            data: data.linechart.sales,
        }
        ]
    };


    var ctx = document.getElementById("daily_sale").getContext("2d");
    var myLineChart = new Chart(ctx, {
        type: 'line',
        data: salesData,        
        options: {

            showLines: true,
            responsive: true,
            legend:{display:false},
            tooltips:{ 
                // backgroundColor:'rgba(0,255,0,0.8)',
                custom: function(tooltip) {

                    // tooltip will be false if tooltip is not visible or should be hidden
                    if (!tooltip) { 
                        return;
                    }
                    else{
                    console.log(tooltip);
                    }   
                }
            },
            scales: 
            {
                xAxes: [{
                    type: "time",
                    time: {
                        displayFormat:'MM/DD/YY',
                        tooltipFormat: 'MM/DD/YY',
                    //     unit: 'day',
                    }
                }],
                yAxes: [{
                    ticks:{ userCallback: function(value, index, values) {
                                                // $ sign and thousand seperators
                                                return  '$'+value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                                            },  
                    },
                }],
            },
        }
    });
Ryun answered 23/5, 2016 at 14:26 Comment(0)
L
12

You can customize the label in callback function.

tooltips: { 
          callbacks: {
                        label: function(tooltipItem, data) {
                            return "Daily Ticket Sales: $ " + tooltipItem.yLabel;
                        },
                    }
            }
Laband answered 24/5, 2016 at 2:36 Comment(0)
H
39
scales: {
    xAxes: [{
      type: 'time',
      time: {
          tooltipFormat:'MM/DD/YYYY', // <- HERE
          displayFormats: {
             'millisecond':'HH:mm:ss',
             'second': 'HH:mm:ss',
             'minute': 'HH:mm:ss',
             'hour': 'HH:mm:ss',
             'day': 'HH:mm:ss',
             'week': 'HH:mm:ss',
             'month': 'HH:mm:ss',
             'quarter': 'HH:mm:ss',
             'year': 'HH:mm:ss',
          }
        }
    }]
}
Heritor answered 7/11, 2019 at 11:13 Comment(1)
From Review: Hi, please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. ThanksCeporah
L
12

You can customize the label in callback function.

tooltips: { 
          callbacks: {
                        label: function(tooltipItem, data) {
                            return "Daily Ticket Sales: $ " + tooltipItem.yLabel;
                        },
                    }
            }
Laband answered 24/5, 2016 at 2:36 Comment(0)
C
4

A bit late, but perhaps the answer by @LeonF works great, didn't make it fully as I work with many datasets and great numbers, so if anyone needs it, here I left my code so the labels have the correct label and the formated value (I hope this helps someone):

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: _labels,
        datasets: [...]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    stacked: false,
                    callback: function (label, index, labels) {
                        return '$' + label / 1000000;
                    }
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Millones de pesos'
                }
            }]
        },
        tooltips: {
            callbacks: {
                label: function (tti, data) {
                    // Here is the trick: the second argument has the dataset label
                    return '{0}: {1}'.Format(data.datasets[tti.datasetIndex].label, formatMoney(tti.yLabel));
                }
            }
        },
        title: {
            display: true,
            text: 'Avance global'
        }
    }
});

I left also my functions for String.Format:

String.prototype.format = String.prototype.Format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined' ? args[number] : match;
    });
};

and for formatMoney:

function formatNumber(num) {
    if (num == 'NaN') return '-';
    if (num == 'Infinity') return '&#x221e;';
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);
}
function formatMoney(num) {
    return '$' + formatNumber(num);
}
Contrail answered 24/2, 2017 at 18:44 Comment(0)
C
0

to set the number formatting and decimals alone, without changing the label or tooltip layout in the callbacks, here's what i found with chartjs 4.4.0.

const options = {
    //...
    ticks: {
        format: {
            minimumFractionDigits: 4,
            maximumFractionDigits: 4,
        },
    },
    //...
};
Christi answered 31/10, 2023 at 0:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.