Mr.Roboto Mr.Roboto - 2 months ago 7
CSS Question

Changing Edge color with D3

I am reading a D3 tutorial and am following the code in this link:

http://www.d3noob.org/2013/03/d3js-force-directed-graph-example-basic.html

I understand the content so far, but am trying to learn more styling by changing different colors. I am trying to change the edge color between the nodes, but this is not working. I know I need to do

path.style("stroke", red)


for instance. But this changes every edge color as expected.

However, I want to change the color of the edge based on the value in the links array. So, if the links.value is < 1 I want green else I want an orange link.
I am somewhat stuck I know I need to use

.style("stroke", function(d) {if d.value < 1 {return 'green'} else {return 'orange'} });


I just can't figure out where to put this in the sample code. I'm just trying to learn by example from some basic D3. Thanks!

Answer

You set the style in the "enter" selection of the edges:

var path = svg.append("svg:g")
    .selectAll("path")
    .data(force.links())
    .enter()
    .append("svg:path")
    .attr("class", function(d) { return "link " + d.type; })
    .attr("class", "link")
    .style("stroke", function(d){ 
        if(d.value < 1) {return 'green'} else {return 'orange'} 
    }) 
    .attr("marker-end", "url(#end)");

Here is the plunker: https://plnkr.co/edit/tOBZdHXVrvcAmh9aHlsl?p=preview