2016-12-14 50 views
0

我是javascript和d3的新手,我一直在使用一些共享代码,并且一直在尝试修改它。D3根据数据改变链接的颜色

这是我目前有:

https://gist.github.com/erich-kuehn/2770a7c7c1cd633f6b47ebb21b640f68

其基于关闭的:

http://bl.ocks.org/erikhazzard/6201948

我试图改变链接的基础上一个新的领域颜色我添加了称为status的csv。它似乎运行良好,如果我通过代码,它似乎使一些链接红色和一些绿色,但当它完成后,他们都结束了绿色。思考?对不起,我真的很新。

//update 
    for(var i=0, len=links.length; i<len; i++){ 
    if (links[i].status[0][0] === 'red') { 
    pathArcs.attr({ 
      //d is the points attribute for this path, we'll draw 
      // an arc between the points using the arc function 
      d: path 
     }) 
     .style({ 
      stroke: 'red', 
      'stroke-width': '2px' 
     }) 
     // Uncomment this line to remove the transition 
     .call(lineTransition); 

    //exit 
    pathArcs.exit().remove(); 
     }else{ 
    pathArcs.attr({ 
      //d is the points attribute for this path, we'll draw 
      // an arc between the points using the arc function 
      d: path 
     }) 
     .style({ 
      stroke: 'green', 
      'stroke-width': '2px' 
     }) 
     // Uncomment this line to remove the transition 
     .call(lineTransition); 

    //exit 
    pathArcs.exit().remove(); 
} 
    } 
}); 

回答

0

pathArcs是数据绑定到他们的元素的选择。当您调用选择的方法(attr,style,text等)时,它将迭代选择中的所有元素。如果你提供一个静态值,每个元素将被赋予该值。如果你提供了一个函数,那么每个元素都会调用该函数传递两个参数,第一个是绑定到元素的数据,第二个是元素的索引。这个函数的返回值是你想要的分配为attrstyletext

在代码中,每当你做出这些pathArcs方法调用,你在选择每一个元素设定值。你所有的绿色元素都结束了,因为for循环中的最后一个元素使它们变成绿色。

您可能已经注意到,您的if/else语句的唯一区别是您设置stroke颜色的位置。这意味着你只需要为样式的stroke值提供一个函数。

pathArcs 
    .attr({ 
    d: path 
    }) 
    .style({ 
    'stroke': function(d) { 
     // I don't know if you can just set this based on the 
     // value of d.status[0][0] without knowing the possible 
     // values of it. Ternary may be unnecessary. 
     return d.status[0][0] === 'red' ? 'red' : 'green'; 
    }), 
    'stroke-width': '2px' 
    }) 
    // Uncomment this line to remove the transition 
    .call(lineTransition);