I'm trying to fetch x- and y- coordinates from a chart.js scatter plot through a mouse click event in a react application. Following this tutorial: https://react-chartjs-2.js.org/docs/working-with-events I implemented a call-back for the mouse click:
function scatter_point_selector(event)
{
var element = getElementAtEvent(scatter_ref.current, event);
var element_ix = getElementAtEvent(scatter_ref.current, event)[0].index;
var dataset = getDatasetAtEvent(scatter_ref.current, event);
console.log('element = ', element);
from which I see the data structure with the x
and y
coordinates in the browser console:
The problem is that the x- and y-coordinates of the data points are at x=-100, -95, ..., 50 and at y=0, 180. These are not the same as the x- and y- listed in the element.
How can I fetch the x- and y-coordinates of the data points when clicking on them?
You can use scatter_ref.current.scales.x.getValueForPixel(xValue)
and scatter_ref.current.scales.y.getValueForPixel(yValue)
to get the values you see on the axis