Chartjs v2 - format tooltip for multiple data sets (bar and line)
You could achieve that using the following tooltips callback function ...
callbacks: {
label: function (t, d) {
if (t.datasetIndex === 0) {
return '$' + t.yLabel.toFixed(2)
} else if (t.datasetIndex === 1) {
return Math.round(+t.yLabel.toString().replace(/(\d{2})(.*)/, '$1.$2')) + 'M';
}
}
}
ᴅᴇᴍᴏ
var ctx = document.getElementById("canvas").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May"],
datasets: [{
type: 'line',
label: "Sales",
data: [144.36534, 146.42534, 145.23534, 147.19534, 145],
fill: false,
borderColor: '#EC932F',
backgroundColor: '#EC932F',
tension: 0,
yAxisID: 'y-axis-2'
}, {
type: 'bar',
label: "Visitor",
data: [22345343, 23345343, 24345343, 25345343, 230245343],
backgroundColor: '#71B37C',
yAxisID: 'y-axis-1'
}]
},
options: {
responsive: false,
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function (t, d) {
if (t.datasetIndex === 0) {
return '$' + t.yLabel.toFixed(2);
} else if (t.datasetIndex === 1) {
if (t.yLabel.toString().length === 9) {
return Math.round(+t.yLabel.toString().replace(/(\d{3})(.*)/, '$1.$2')) + 'M';
} else return Math.round(+t.yLabel.toString().replace(/(\d{2})(.*)/, '$1.$2')) + 'M';
}
}
}
},
scales: {
yAxes: [{
id: "y-axis-1",
position: "left"
}, {
id: "y-axis-2",
position: "right"
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas" width="400" height="190"></canvas>