Home > Enterprise >  D3.js Pointer Coordinates relative to the axis Domain
D3.js Pointer Coordinates relative to the axis Domain

Time:12-06

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;
}

`

How do a relate these to the drawn axes domains?

CodePudding user response:

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.

  • Related