D3树:线代替对角投影 [英] D3 tree: lines instead of diagonal projection

查看:244
本文介绍了D3树:线代替对角投影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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)。我想我需要知道的是:给定这个数据,如何在链接数组中的每对节点的(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆