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
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.
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';
});
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); });