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

jjjwad0x  于 2023-11-18  发布在  Chart.js
关注(0)|答案(4)|浏览(232)

如何在Chart.js中重新格式化工具提示?图表的x轴为时间,y轴为销售额,工具提示显示x和y的数据值。到目前为止,工具提示可以默认工作,但我想更改工具提示中的值。我可以通过重新定义“time”中的tooltipFormat字段来重新格式化工具提示中的时间。但我没有发现y轴数据的类似情况。例如,显示“$1600”而不是“每日售票额:1600”。
example tooltip format image
有谁能告诉我,这种变化应该发生在哪里?
自定义回调函数能解决这个问题吗?代码如下,谢谢!

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, ",");
                                            },  
                    },
                }],
            },
        }
    });

字符串

yws3nbqq

yws3nbqq1#

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',
          }
        }
    }]
}

字符串

k10s72fa

k10s72fa2#

您可以在回调函数中自定义标签。

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

字符串

ckx4rj1h

ckx4rj1h3#

有点晚了,但也许@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'
        }
    }
});

字符串
我也离开了我的函数为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;
    });
};


对于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);
}

e0uiprwp

e0uiprwp4#

要单独设置数字格式和小数,而不改变回调中的标签或工具提示布局,下面是我在chartjs 4.4.0中发现的。

const options = {
    //...
    ticks: {
        format: {
            minimumFractionDigits: 4,
            maximumFractionDigits: 4,
        },
    },
    //...
};

字符串

相关问题