I've implemented zoom and pan functionality on chart and I'm experiencing an issue. While Zooming and panning, the x and y scales adjust correctly, and the lines expand and shrink as expected. However, it appears that data is being mapped to the 'lines'. In other words, the new scale values are not being applied to the lines, causing inconsistencies. When I hover the mouse over the line, the tooltip displays some data, but the problem arises when I hover outside the line, and the tooltip still shows data. Through debugging, I realized that the data is not being correctly mapped to the line. I'm relatively new to d3.js, and I'd appreciate your assistance in resolving the issue.
In the provided sample code below, the zoom and pan functionalities do not seem to work as expected. I'm sharing this code to illustrate the attributes I've used. However, in my actual project zooming and panning is work correctly.
Expected Result I expect the data to be properly mapped to the lines with new scale values and hovering outside the line should not display tooltip data.
Actual Result The Data is not correctly mapped to the lines with the new scale values and hovering outside the line displays tooltip data
const svgWidth = 488;
const svgHeight = 300;
const margin = {
top: 18,
left: 60,
right: 35,
bottom: 25,
};
const width = svgWidth - margin.left - margin.right;
const height = svgHeight - margin.bottom - margin.top;
const svg = d3.select("body").append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight)
.append("g")
.attr("transform", \`translate(${margin.left}, ${margin.top})\`);
const xScale = d3.scaleLinear()
.domain(\[0, 200\])
.range(\[0, width\]);
const yScale = d3.scaleLinear()
.domain(\[0, 100\])
.range(\[height, 0\]);
const xAxis = d3.axisBottom(xScale).ticks(10).tickSize(-height);
const yAxis = d3.axisLeft(yScale).ticks(5).tickSize(-width);
const zoomAndPan = d3.zoom()
.scaleExtent(\[0.2, 5\])
.translateExtent(\[\[-7808, -7090\], \[7000, 7800\])
.on("zoom", (e) =\> {
svg.selectAll("g.line").attr("transform", e.transform);
svg.select(".x.axis").call(xAxis.scale(e.transform.rescaleX(xScale)));
svg.select(".y.axis").call(yAxis.scale(e.transform.rescaleY(yScale)));
});
svg.call(zoomAndPan);
svg.append("g")
.attr("class", "x axis")
.attr("transform", \`translate(0, ${height})\`)
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
const lineSVG = d3.line()
.x((d) =\> xScale(d.x))
.y((d) =\> yScale(d.y));
const data = \[
{ 'x': 1, 'y': 6 },
{ 'x': 2, 'y': 5 },
{ 'x': 3, 'y': 18 },
// Add more data points here
\];
const lines = svg.append("g").attr("class", "lines");
lines.selectAll(".line-group")
.data(\[data\])
.enter()
.append("g")
.attr("class", "line-group")
.append("path")
.attr("class", "line")
.attr("d", (d) =\> lineSVG(d))
.style("stroke", "red")
.style("opacity", 1.0);