简体   繁体   English

如何在 Chart.js 中重新格式化工具提示?

[英]How to reformat tooltip in Chart.js?

How to reformat tooltip in Chart.js?如何在 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.该图表的 x 轴为时间,y 轴为销售额,工具提示显示 x 和 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'.我可以通过重新定义“时间”中的 tooltipFormat 字段来重新格式化工具提示中的时间。 But I don't find a similar thing for y-axis data.但是我没有发现 y 轴数据有类似的东西。 For example, show "$1600" instead of "Daily Ticket Sales:1600".例如,显示“$1600”而不是“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, ",");
                                            },  
                    },
                }],
            },
        }
    });
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',
          }
        }
    }]
}

You can customize the label in callback function.您可以在回调函数中自定义标签。

tooltips: { 
          callbacks: {
                        label: function(tooltipItem, data) {
                            return "Daily Ticket Sales: $ " + tooltipItem.yLabel;
                        },
                    }
            }

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):有点晚了,但也许@LeonF 的答案效果很好,但在我处理许多数据集和大量数字时并没有完全解决,所以如果有人需要它,我在这里留下了我的代码,以便标签具有正确的标签和格式化值(我希望这对某人有帮助):

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.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 :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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM