简体   繁体   中英

Line chart zoom for multiseries d3js v5 chart

I am trying to achieve zooming for d3js line chart. It is working fine for single series line, but not working for multiseries. here is the svg zooming function

function zoom(svg) {

        var extent = [
            [margin.left, margin.top], 
            [width - margin.right, height - margin.top]
        ];

        var zooming = d3.zoom()
            .scaleExtent([1, 3])
            .translateExtent(extent)
            .extent(extent)
            .on("zoom", zoomed);

        svg.call(zooming);

        function zoomed() {

            x.range([margin.left, width - margin.right]
                .map(d => d3.event.transform.applyX(d)));

            // for single series
            svg.select(".path")
                .attr("d", line);

            svg.select(".x-axis")
                .call(d3.axisBottom(x)
                    .tickSizeOuter(0));
        }
    }

attached working fiddle also, in the demo you can clearly see on mouse scroll, only one line series gets zoomed, other one fixed as it is. Don't know how to fix this. Need help from D3 ninjas.

Usually we would use both the datas and the line generator functions in an array: [{line: line, data: data1}, {line: line100, data: data2}] , bound to each SVG line with selectAll() .

But because the data is the same for both lines, we can take a little shortcut and use only the line generators, using the same data each time:

svg.selectAll(".path")
    .data([line, line100])
    .join("path")
    .attr("d", lineGenerator => lineGenerator(data));

This selects all existing path elements, bind a line generator to each of them, and then use the line generators we bound to generate the new paths, using the data join .

JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM