如何使用d3.js获取垂直方向的树

时间:2013-10-18 07:47:03

标签: javascript svg d3.js

以下网址将获得水平方向的树。 但是我的要求是使用d3获得垂直方向的树。 请为此要求建议正确的有效解决方案。

d3js Tree square enter image description here

2 个答案:

答案 0 :(得分:7)

我知道自从你提出问题以来已经有一段时间了,但万一我想提请你注意我做的一个图表:

enter image description here

codepen上的代码。如果您对代码有任何疑问,请告诉我们。

答案 1 :(得分:3)

将第35行,第56行和肘部功能更改为

    <!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
  font-family: "Helvetica Neue", Helvetica, sans-serif;
}

.name {
  font-weight: bold;
}

.about {
  fill: #777;
  font-size: smaller;
}

.link {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

</style>
<body>
<script src="http://d3js.org/d3.v2.min.js?2.9.4"></script>
<script>

var margin = {top: 0, right: 0, bottom: 320, left: 0},
    width = 960- margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var tree = d3.layout.tree()
    .separation(function(a, b) { return a.parent === b.parent ? 1 : .5; })
    .children(function(d) { return d.parents; })
    .size([width, height]);

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

d3.json("tree.json", function(json) {
  var nodes = tree.nodes(json);

  var link = svg.selectAll(".link")
      .data(tree.links(nodes))
      .enter().append("path")
      .attr("class", "link")
      .attr("d", elbow);

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

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

  node.append("text")
      .attr("x", 8)
      .attr("y", 8)
      .attr("dy", ".71em")
      .attr("class", "about lifespan")
      .text(function(d) { return d.born + "–" + d.died; });

  node.append("text")
      .attr("x", 8)
      .attr("y", 8)
      .attr("dy", "1.86em")
      .attr("class", "about location")
      .text(function(d) { return d.location; });
});

function elbow(d, i) {

  console.log(d)
  return "M" + d.source.x + "," + d.source.y
       + "V" + d.target.y + "H" + d.target.x 
       + (d.target.children ? "" : ("v" + margin.bottom))
}

</script>
</body>

这是我的结果enter image description here

相关问题