Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

d3.js - D3 js multiple line graph toggle dots on/off

This D3 js example shows all the code to produce a multi-line graph that can be toggled. Each line in the graph includes dots for existing data points.

While the lines can be toggled on/off, the dots stay stagnant. I would like for the toggle to work for both turning on/off the line & the dots that are associated with the same line.

I suspect that the svg.append("text") is the part that requires code update to also enable the dots to be turned on/off along with the line.

Here is the existing code snipet that turns on/off the line graph, but it doesn't turn on/off the dots.

svg.append("text")
        .attr("x", (legendSpace/2)+i*legendSpace)  // space legend
        .attr("y", height + (margin.bottom/2)+ 5)
        .attr("class", "legend")    // style the legend
        .style("font-size","15px")  // Change the font size
        .style("font-weight", "bold") // Change the font to bold
        .style("text-anchor", "middle") // center the legend
        .style("fill", function() { // Add the colours dynamically
            return d.color = color(d.key); })
        .on("click", function(){
            // Determine if current line is visible 
            var active   = d.active ? false : true,
            newOpacity = active ? 0 : 1; 
            // Hide or show the elements based on the ID
            d3.select("#tag"+d.key.replace(/s+/g, ''))
                .transition().duration(100) 
                .style("opacity", newOpacity); 
            // Update whether or not the elements are active
            d.active = active;
            })  
        .text(d.key); 

Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IDs are unique. You cannot set the same ID for several different DOM elements.

Solution: set classes instead.

For the lines:

.attr("class", 'tag'+d.key.replace(/s+/g, ''))

And for the circles:

.attr("class", d=>'tag'+d.symbol.replace(/s+/g, ''))

Then, get the class on the click event (use selectAll, not select):

d3.selectAll(".tag"+d.key.replace(/s+/g, ''))

here is the updated fiddle: http://jsfiddle.net/gx4zc8tq/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...