4

I am creating a Sankey Diagram using the D3 Sankey plugin. I have the standard columns: source, target, value plus one additional column called nodeColor. I would like the color of the target node to be dictated by the color noted in the "nodeColorTarget" column. I was able to change the source code for the nodes to be all one color. However, I was unable to develop a function to use the additional column to dictate the color.

Sample Data:

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

Existing Code:

// 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); });

My full code is here.

Danny
  • 554
  • 1
  • 6
  • 17

1 Answers1

4

You first need to add the attribute like that :

graph.nodes.push({ "name": d.source, "color": d.nodeColorTarget });

Then you can call it like that :

.style("fill", function(d) { return d.color;}) 

See this example : http://plnkr.co/edit/4xPx05PxnWxoQBhIj2lo?p=preview

PS : I did some minor changes as the structure of the data changed

Tim B
  • 1,983
  • 1
  • 20
  • 21
  • in the example you provided I see the colors having changed. However the diagram is no longer correct. Instead of having the sources on the left and the targets on the right they are now interspersed. For example you see DisB on the right side. In addition, there are no flow arrows between DistB and Place3. There are also a bunch of empty nodes on the bottom right. Any idea on how to fix this? – Danny Jun 21 '16 at 19:28
  • 1
    Fixed it, I forgot to remove the duplicates, see the updated fiddle http://plnkr.co/edit/4xPx05PxnWxoQBhIj2lo?p=preview – Tim B Jun 21 '16 at 20:12
  • Thanks that works. I adjusted your response to include the specific snippets of code that needed to be modified. – Danny Jun 22 '16 at 15:15