简体   繁体   中英

Styling in D3 with a loop?

I wonder if it possible to use styling actions on the same element many times? I got this Array called A which stores 3 colours and I want to go through a loop that fills my element link.

var A = ["blue", "red", "green"]

    for ( var i = 0; i < A.length; i++){


                link.style("stroke", function(d) 
                {

                   return A[i];



                 }
                 ) 
                };

To style each link a different style based on the index of that element/datum in the selection. As with many things in d3, this does not require a loop. You can access the index of each datum with code like:

selection.attr("property",function(d,i) {
  return array[i];
})

For sake of ease, I've used some circles and fill rather than links and stroke, but the method is identical. The snippet below will color links sequentially based on the colors array.

 var svg = d3.select("body") .append("svg") .attr("width",500) .attr("height",300); var data = [[50,50],[100,50],[200,50],[300,100]]; var colors = ["steelblue","orange","pink","red"] // create some circles: var circles = svg.selectAll("circle") .data(data) .enter() .append("circle") .attr("transform",function(d) { return "translate("+d+")"; }) .attr("r",10) // to style sequentially, you can use the datum's index: circles.attr("fill",function(d,i) { return colors[i]; }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

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