D3 树:线而不是对角线投影 [英] D3 tree: lines instead of diagonal projection
问题描述
我正在使用 d3.js 通过这个例子创建一棵树.
I am using d3.js to create a tree using this example.
这可以完美地处理我拥有的数据并产生所需的结果,除了一个细节:我不想要节点之间的那些摆动连接线,我想要一条干净简单的线.谁能告诉我如何制作它?
This handles the data I have perfectly and produces the desired outcome except for one detail: I don't want those wiggly connector lines between the nodes, I want a clean and simple line. Can anyone show me how to produce that?
我一直在查看 d3.js 的 API 文档,但没有成功.据我所知,svg.line
函数应该产生一条直线,给定一组两对坐标 (x,y).我想我需要知道的是:给定这些数据,给定 links 数组中每对节点的 (cx,cy),如何创建线:
I've been looking at the API documentation for d3.js, but with no success. From what I understood, the svg.line
function should produce a straight line given a set of two pairs of coordinates (x,y). What I think I need to know is: given this data, how to create a line given the (cx,cy) of each pair of nodes in the links array:
<代码>
var margin = {top: 40, right: 40, bottom: 40, left: 40};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
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.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("graph.csv", function(links) {
var nodesByName = {};
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];
});
var nodes = tree.nodes(links[0].source);
svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 10)
.attr("cx", function(d) { return d.y; })
.attr("cy", function(d) { return d.x; });
function nodeByName(name) {
return nodesByName[name] || (nodesByName[name] = {name: name});
}
});
推荐答案
其实我是从其他例子中想到的:
Actually I figured out from other example:
<代码>
svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link")
.attr("x1", function(d) { return d.source.y; })
.attr("y1", function(d) { return d.source.x; })
.attr("x2", function(d) { return d.target.y; })
.attr("y2", function(d) { return d.target.x; });
这篇关于D3 树:线而不是对角线投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!