Javascript 根据数据中的附加列更改d3 Sankey图中的节点颜色

Javascript 根据数据中的附加列更改d3 Sankey图中的节点颜色,javascript,d3.js,colors,sankey-diagram,Javascript,D3.js,Colors,Sankey Diagram,我正在使用D3 Sankey插件创建一个Sankey图。我有标准列:source、target、value加上一个名为nodeColor的附加列。我希望目标节点的颜色由“nodeColorTarget”列中注明的颜色决定。我能够将节点的源代码全部更改为一种颜色。但是,我无法开发一个函数来使用附加列来指定颜色 样本数据: source,target,value,nodeColorTarget Dist A,Place1,1,red DistB,Place1,5,red DistB,Place2,2

我正在使用D3 Sankey插件创建一个Sankey图。我有标准列:source、target、value加上一个名为nodeColor的附加列。我希望目标节点的颜色由“nodeColorTarget”列中注明的颜色决定。我能够将节点的源代码全部更改为一种颜色。但是,我无法开发一个函数来使用附加列来指定颜色

样本数据:

source,target,value,nodeColorTarget
Dist A,Place1,1,red
DistB,Place1,5,red
DistB,Place2,2,grey
DistB,Place2,1,grey
DistB,Place3,2,blue
现行守则:

// add the rectangles for the nodes
  node.append("rect")
      .attr("height", function(d) { return d.dy; })
      .attr("width", sankey.nodeWidth())
      .style("fill", "red") 
      //.style("fill", function(d) { 
          //return d.color = color(d.name.replace(/ .*/, "")); })
      //.style("stroke", function(d) { 
         // return d3.rgb(d.color).darker(2); })
    //.append("title")
     // .text(function(d) { 
         // return d.name + "\n" + format(d.value); });

我的完整代码是。

您首先需要添加如下属性:

graph.nodes.push({ "name": d.source, "color": d.nodeColorTarget });
.style("fill", function(d) { return d.color;}) 
那么你可以这样称呼它:

graph.nodes.push({ "name": d.source, "color": d.nodeColorTarget });
.style("fill", function(d) { return d.color;}) 
请参见此示例:


PS:在您提供的示例中,随着数据结构的变化,我做了一些小的更改,我看到颜色发生了变化。然而,这个图表不再正确。它们不再是左侧的源和右侧的目标,而是分散在一起。例如,您可以在右侧看到DisB。此外,DistB和Place3之间没有流动箭头。右下角还有一堆空节点。有没有办法解决这个问题?解决了,我忘了删除副本,请看更新的提琴,谢谢。我调整了您的响应,以包含需要修改的特定代码片段。我更新了答案