D3.js : Applying Styles To Individual Lines
Solution 1:
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) { returncolor(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) { returncolor(i); });
Solution 2:
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';
});
Post a Comment for "D3.js : Applying Styles To Individual Lines"