d3.js : Applying styles to individual lines

前端 未结 2 1169
感情败类
感情败类 2021-01-29 03:58

Was trying out the draggable network and wanted to be able to use different colours for different links. When I commented out the lines

/*var link = svg.append         


        
相关标签:
2条回答
  • 2021-01-29 04:20

    To make your links visible

    Do this

    var link = svg.append("g")
                 .selectAll("line");
    

    Instead of

    var link = svg.append("g");
    

    Now you can see all your links in orange color.

    To apply styles to individual lines

    Add class names using conditions like this.

    link.data(graph.links).enter()
         .append("line")
         .attr("class",function(d){     
              return (d.source.x>400 && d.source.y<300)?'link-b':'link-r';
         });
    
    0 讨论(0)
  • 2021-01-29 04:22

    You don't need any if-else conditions, or extensive modifications of the existing code. The way things like line color are set in D3 is through the .style() command:

    link.style("stroke", ...);
    

    The argument doesn't have to be a fixed value, but can be a function. This function is then evaluated for each element in the selection (the lines in this case), allowing you to give them different colours. If, for example, you wanted to give different colours based on the x position of the source, you would do the following.

    var color = d3.scale.category20();
    link.style("stroke", function(d) { return color(d.source.x); });
    

    You can use anything that's part of the data bound to the element (d) to determine what color you want, or indeed anything else. To e.g. set a different color for each line based on the index, you would do this.

    link.style("stroke", function(d, i) { return color(i); });
    
    0 讨论(0)
提交回复
热议问题