树形图:获取“ [对象对象]”而不是子代,孙代等

时间:2018-06-26 01:08:02

标签: d3.js family-tree

这是经典的Bostock“树形图”,带有一些按钮可以展开和折叠(下一篇文章的主题)。目前,它会从html中嵌入的JSON数据中生成“ [object Object]”,而不是预期的子代,孙代等名称。

我到处都在寻找解决方案,但是没有运气。我已经看到了对“ JSON.stringify”的引用,但是在我的示例中尚不清楚如何实现它。

试图从中创建一个jsfiddle,但是错过了一两个步骤。见下文:

https://jsfiddle.net/VinceLackner/f9Lpudry/22/

我在stackoverflow上发表的第三篇文章,所以试图掌握如何最好地表达我的问题。

d3.selectAll(("input[name='CollapseOthersYN']")).on("change", function() {
  CollapseOthersYN = this.value;
});



var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 1160 - margin.right - margin.left,
  height = 800 - margin.top - margin.bottom;

var i = 0,
  duration = 750,
  root;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");



var flare = {
  "parent": "Family",
  "children": [{
    "parent": "Anne",
    "children": [{
        "parent": "Daughter1",
        "children": [{
            "parent": "Child 1"
          },
          {
            "parent": "Child 2",
            "children": [{
                "parent": "Grandchild 2.1"
              },
              {
                "parent": "Grandchild 2.2"
              },
              {
                "parent": "Grandchild 2.3"
              }
            ]
          },
          {
            "parent": "Child 3"
          },
          {
            "parent": "Child 4"
          }
        ]
      },
      {
        "parent": "Daughter2",
        "children": [{
          "parent": "Child 1",
          "children": [{
            "parent": "Grandchild 1.1",
            "children": [{
              "parent": "GreatGrandchild 1.1.1",
              "children": [{
                  "parent": "Great GreatGrandchild 1.1.1.1"
                },
                {
                  "parent": "Great GreatGrandchild 1.1.1.2"
                },
                {
                  "parent": "Great GreatGrandchild 1.1.1.3"
                }
              ]
            }]
          }]
        }]
      }
    ]
  }],
  "x0": 300,
  "y0": 0
}

console.table(flare);


root = flare;

root.x0 = height / 2;
root.y0 = 0;

function collapse(d) {
  if (d.children) {
    d._children = d.children;
    d._children.forEach(collapse);
    d.children = null;
  }
}

root.children.forEach(collapse);

update(root);


d3.select(self.frameElement).style("height", "800px");

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 180;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on("click", click);

  nodeEnter.append("circle")
    .attr("r", 1e-6)
    .style("fill", function(d) {
      return d._children ? "lightsteelblue" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", function(d) {
      return d.children || d._children ? -10 : 10;
    })
    .attr("dy", ".35em")
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    .text(function(d) {
      return d.parent;
    })
    .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    //      .ease("bounce")
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  nodeUpdate.select("circle")
    .attr("r", 4.5)
    .style("fill", function(d) {
      return d._children ? "lightsteelblue" : "#fff";
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  nodeExit.select("circle")
    .attr("r", 1e-6);

  nodeExit.select("text")
    .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}


// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }

  // 2018-06-20 (VFL)
  // If the node has a parent, then collapse its child nodes
  // except for this clicked node.

  if (d.parent != "null") {
    d.parent.children.forEach(function(element) {
      if (d !== element) {
        collapse(element);
      }
    });
  }

  update(d);
}


function collapse(d) {
  if (d.children) {
    d._children = d.children;
    d._children.forEach(collapse);
    d.children = null;
  }
}

function collapseAll() {
  root.children.forEach(collapse);
  update(root);
}

function expand(d) {
  if (d._children) {
    d.children = d._children;
    d.children.forEach(expand);
    d._children = null;
  }
}

function expandAll() {
  root.children.forEach(collapse);
  root.children.forEach(expand);
  update(root);
}
.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}
<script src="https://d3js.org/d3.v3.js"></script>

<button onclick="expandAll(true)" style="background-color:lightblue">Expand all</button>
<p>
  <button onclick="collapseAll(true)" style="background-color:lightgreen">Collapse all</button>
  <p>

    <form id="form">
      Collapse Others?
      <p></p>
      <input type="radio" name="CollapseOthersYN" value="Yes">Yes<br>
      <input type="radio" name="CollapseOthersYN" value="No">No<br>
    </form>


已解决

显然,“ d.parent”是D3库中的关键字。在JSON数据(父母,孩子)中使用“父母”作为键会干扰D3自己对“ d.parent”的使用。

两项更改:

1)我在JSON数据中将“父”更改为“名称”。

2)在下面的代码中,我将“ d.parent”更改为“ d.name”。

nodeEnter.append("text")
  .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
  .attr("dy", ".35em")
  .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
  .text(function(d) { return **d.name**; })
  .style("fill-opacity", 1e-6);

0 个答案:

没有答案