d3.js : Applying styles to individual lines

前端 未结 2 1173
感情败类
感情败类 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: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); });
    

提交回复
热议问题