I'm trying to build a chart.js scatter chart where upon the user hovering over the scatter point, the tool tip reveals the label that is specific to that point.
So each data point would have it's x and y values, and also it's label.
So far I've got
var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
labels: ["Label 1","Label 2","Label 3"],
data: [{
x: -10,
y: 0,
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || 'Other';
var label = data.labels[tooltipItem.index];
return datasetLabel + ': ' + label;
}
}
}
}
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</head>
<canvas id="myChart" style = "height:1000px"></canvas>
When I hover over each point, I'd like to see either 'label 1', 'label 2' or 'label 3' appear.
Thanks very much
As of Chart.js version 3, callbacks are handled a little differently. Here is a working example with 3.2.0. Relevant docs: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback
ctx = document.getElementById("myChart").getContext("2d");
let data = {
datasets: [{
label: "Legend",
labels: ["Label 1", "Label 2", "Label 3"],
data: [{
x: -10,
y: 0,
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}],
backgroundColor: "rgb(255, 99, 132)"
}]
}
let options = {
plugins: {
tooltip: {
callbacks: {
label: function(ctx) {
// console.log(ctx);
let label = ctx.dataset.labels[ctx.dataIndex];
label += " (" + ctx.parsed.x + ", " + ctx.parsed.y + ")";
return label;
}
}
}
}
}
scatterChart = new Chart(ctx, {
type: "scatter",
data: data,
options: options
});
<canvas id="myChart" height="500"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>
You can achieve this using the following tooltips label callback function ...
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
return label + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
}
}
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
var ctx = document.getElementById('myChart').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
labels: ["Label 1", "Label 2", "Label 3"],
datasets: [{
label: 'Legend',
data: [{
x: -10,
y: 0,
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
return label + ': (' + tooltipItem.xLabel + ', ' + tooltipItem.yLabel + ')';
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" style="height:1000px"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With