Ben Mayo Ben Mayo - 3 months ago 22
Javascript Question

Chart js scatter - display label on hover

I've cobbled together a chart js scatter graph - which works pretty much ok.

In the bottom part of this js, I have a function that gets the label of the point clicked so that I can do stuff with it - this is working fine.

What I can't do is get this label to display when the user hovers over the point - I just get the x and y values of the data point.



I want the relevant label to appear when the user hovers over. Ideally, I'd like the x and y values not to.

How do I do that?

Thanks,

<script>var data = {
datasets: [{
backgroundColor: "#566573",
{{scatterData|safe}}
}],
{{labelsData|safe}}
};

$(document).ready(
function () {
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'bubble',
data: data,
options : {
legend: {
display: false
},
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Page Value'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Unique Page Views'
}
}] }
}
});
canvas.onclick = function (evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
loadScatterPoint(label);
};
}
);
</script>

Answer Source

There is no need to use click event handler for your chart.

To display a label on tooltip, you would have to define the label property for you dataset, like so ...

var data = {
   datasets: [{
      label: 'Ben Mayo',  //<-- define this
      backgroundColor: "#566573",
      { { scatterData | safe } }
   }],
   { { labelsData | safe } }
};

note: labels array are not applicable for bubble chart.