Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 tree: lines instead of diagonal projection

Tags:

tree

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?

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

like image 515
Joum Avatar asked Apr 25 '13 12:04

Joum


1 Answers

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

like image 85
Joum Avatar answered Nov 18 '22 16:11

Joum