【问题标题】:Nesting a CSV for D3 Tree Layout为 D3 树布局嵌套 CSV
【发布时间】:2016-04-11 00:46:49
【问题描述】:

我有一个这样结构的 CSV 文件

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

我想构造一个类似这个D3的树形图Pedigre Diagram

我已尝试使用此 example 展平文件并取得了一些成功,但我似乎无法让数组携带 百分比字段,以便它们将在节点上呈现。

我已经尝试过这些示例,但它们似乎不允许完全嵌套 https://gist.github.com/phoebebright/3176159#file-index-html

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

请看下面我的代码,目标是确保在节点上显示值和百分比。

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

这是我“丢失”所有用于标记的值和百分比数据的地方

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

希望在此处将 CSV 文件中的所有值附加到节点

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

【问题讨论】:

    标签: javascript arrays csv d3.js


    【解决方案1】:

    您可以将节点保存到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 });
    }
    

    然后像这样访问它们:

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

    【讨论】:

    • 谢谢。只见树木不见森林!
    猜你喜欢
    • 2012-12-02
    • 2013-10-03
    • 1970-01-01
    • 2023-03-20
    • 2013-03-02
    • 2012-09-17
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    相关资源
    最近更新 更多