Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

D3.js Pointer Coordinates relative to the axis Domain

Using d3.js and the d3.pointer class, I am recieving the SVG coordinates for pointermove events. I’m struggling to relate these coordinates to meaningful numbers on the linear axes when the axes do not start from 0 (or may go negative).

`

function pointermoved(d) {
    const [x, y] = d3.pointer(d);
    document.getElementById("X-COORDINATES").innerHTML = x;
    document.getElementById("Y-COORDINATES").innerHTML = y;
}

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do a relate these to the drawn axes domains?

>Solution :

To relate the SVG coordinates to meaningful numbers on the linear axes, you can use the invert method from the d3.scaleLinear class. This method takes an x or y coordinate and returns the corresponding value on the domain of the linear scale.

For example, if you have a linear scale with a domain of [0, 100] and a range of [0, 200], you can use the invert method to convert an x coordinate of 50 to the corresponding value on the domain, which would be 50. Here is an example of how you can use the invert method to do this:

const xScale = d3.scaleLinear()
    .domain([0, 100])
    .range([0, 200]);

const xCoordinate = 50;
const xValue = xScale.invert(xCoordinate); // 50

You can use this same approach to convert y coordinates to values on the domain of the y-axis.

In your code, you can use the invert method to convert the x and y coordinates from the d3.pointer event to the corresponding values on the x and y domains of your linear scales. Here is an example of how you could do this:

function pointermoved(d) {
    const [x, y] = d3.pointer(d);

    // Convert x and y coordinates to values on the x and y domains
    const xValue = xScale.invert(x);
    const yValue = yScale.invert(y);

    // Update the page with the converted values
    document.getElementById("X-COORDINATES").innerHTML = xValue;
    document.getElementById("Y-COORDINATES").innerHTML = yValue;
}

This answer is generated using AI.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading