2

I have a CSV file structured thus

source, target, name, value1 , percentange
  A1      A1      T1    200        3%
  A1      A2      T2    340        4%
  A1      A3      T3    400        2%  

I would like to construct a tree diagram similar to this D3 Pedigre Diagram

I have tried to flatten the file using this example and had some success, but I can't seem to get the array to carry the value and percentage fields so they will render on the node.

I have tried these examples, but they don't seem to allow the full nesting https://gist.github.com/phoebebright/3176159#file-index-html

D3: use nest function to turn flat data with parent key into a hierarchy

Please see my code below, the goal is to ensure value and percentage are displayed at the node.

d3.csv("graph2.csv", function(error, links) {
  if (error) throw error;

  var nodesByName = {};

  // Create nodes for each unique source and target.
  links.forEach(function(link) {
    var parent = (link.source = nodeByName(link.source)),
      child = (link.target = nodeByName(link.target));
    if (parent.children) parent.children.push(child);
    else parent.children = [child];
  });
});

This is where I 'Lose' all the value and percentage data for labelling

// Extract the root node and compute the layout.
var nodes = tree.nodes(links[0].source);

// Create the link lines.
var link = svg
  .selectAll(".link")
  .data(links)
  .enter()
  .append("path")
  .attr("class", "link")
  .attr("d", diagonal);

// Create the node circles.
var node = svg
  .selectAll(".node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("class", "node")
  .attr("transform", function(d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

node
  .append("circle")
  .attr("class", "node")
  .attr("r", 4.5);

Would like to have ALL the values from the CSV file here to append to the node

node
  .append("text")
  .attr("class", "source")
  .attr("x", 8)
  .attr("y", -6)
  .text(function(d) {
    return d.name;
  });

function nodeByName(name) {
  return nodesByName[name] || (nodesByName[name] = { name: name });
}
ROOT
  • 11,363
  • 5
  • 30
  • 45
conr404
  • 305
  • 2
  • 4
  • 19

1 Answers1

2

You can save the node to nodesByName:

var nodesByName = {};

// Create nodes for each unique source and target.
links.forEach(function(link) {
  var parent = (link.source = nodeByName(link.source, link)),
    child = (link.target = nodeByName(link.target, link));
  if (parent.children) parent.children.push(child);
  else parent.children = [child];
});

function nodeByName(name, node) {
  return nodesByName[name] || (nodesByName[name] = { name: name, node: node });
}

Then access them like this:

node
  .append("text")
  .attr("class", "source")
  .attr("x", 8)
  .attr("y", -6)
  .text(function(d) {
    var node = nodesByName[d.name].node;
    return d.name + " " + node.value1 + " " + node.percentage;
  });
ROOT
  • 11,363
  • 5
  • 30
  • 45
Fabricator
  • 12,722
  • 2
  • 27
  • 40