Search code examples
htmltooltipchart.js

Customised tooltip in chart.js


In below code i need the tool tip to be like this Probability: 40 Audience: 5000 i.e in the tool tip i need xAxes labelstring with the xAxes value and yAxes labelstring with yAxes value.How to achieve this pls help

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
    datasets: [{
        label: 'Audience',
        data: [{x:12,y:9000}, {x:30, y:6000}, {x:40, y:5000},{x:52,y:4000},{x:70,y:3000},{x:92,y:2000}],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',

        borderColor: 'rgba(255, 159, 64, 1)',
        borderWidth: 1
    }]
},
options: {
 tooltips:
{
callbacks: 
{
label: function(tooltipItem, data) {return  data.datasets[tooltipItem.datasetIndex].label+':'+ tooltipItem.yLabel;
}
}
},
    scales: {
    xAxes: [{
    type: 'linear',position: 'bottom',
        scaleLabel:{labelString:"Probability",display:true},
            ticks: {
                 beginAtZero:true,
                max:100
            }
        }],
        yAxes: [{
        scaleLabel:{labelString:"Audience",display:true},
            ticks: {
                min: 1000
            }
        }]
    }
}
});  

Solution

  • Just replace your "callbacks" block with this one:

            callbacks: 
            {
                title: function() {
                    return '';
                },
                beforeLabel: function(tooltipItem, data) {
                    return 'Probability: ' + tooltipItem.xLabel + '%';
                },
                label: function(tooltipItem, data) {
                    return data.datasets[tooltipItem.datasetIndex].label+': '+ tooltipItem.yLabel;
                }
    
            }