Reputation: 3685
I'm very new to D3, I'm trying to draw an directed graph, but I want the nodes to be an rectangle instead of circle. Here is the code that I have tried:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Testing</title>
<style>
.node {
fill: #ccc;
stroke: #fff;
stroke-width: 2px;
}
.link {
stroke: #777;
stroke-width: 2px;
}
</style>
</head>
<body>
<script src='http://d3js.org/d3.v3.min.js'></script>
<script>
var width = 640,
height = 480;
var nodes = [
{ x: width/3, y: height/2 , width:50,height:50 },
{ x: 2*width/3, y: height/2 ,width:50,height:50 },
{ x: 3*width/4, y: height/2 ,width:50,height:50 },
{ x: 6*width/5, y: height/2 ,width:50,height:50 }
];
var links = [
{ source: 0, target: 1 }
];
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links);
force.linkDistance(width/2);
var link = svg.selectAll('.link')
.data(links)
.enter().append('line')
.attr('class', 'link');
var node = svg.selectAll('.node')
.data(nodes)
.enter().append('rect')
.attr('class', 'node');
force.on('end', function() {
node.attr('r', width/25)
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; });
link.attr('x1', function(d) { return d.source.x; })
.attr('y1', function(d) { return d.source.y; })
.attr('x2', function(d) { return d.target.x; })
.attr('y2', function(d) { return d.target.y; });
});
force.start();
</script>
</body>
</html>
but the above code only displays the line, not rectangle, however if I change:
.enter().append('rect')
to
.enter().append('circle')
things are working as expected. Where I'm making the mistake?
And also how can I make the arrow as directed one?
Thanks in advance.
Upvotes: 1
Views: 1403
Reputation: 4053
you have to define rectangle attributes instead of circle attributes using node.attr
, then it will be running correctly
for arrows use svg marker, see this example: http://bl.ocks.org/d3noob/5141278
Upvotes: 1
Reputation: 13811
Your doing it in-correctly, you should be doing this:
node.attr('x', function(d) { return d.x; })
.attr('y', function(d) { return d.y; })
.attr('width', function(d) { return d.width; })
.attr('height', function(d) { return d.height; })
instead of circle
properties.
Upvotes: 1
Reputation: 848
You need to the change the circle attributes for rectangle attributes like the following:
node.attr('x', function(d){ return d.x;})
.attr('y', function(d){ return d.y;})
.attr('width', width/25)
.attr('height', width/25);
Hope this helps.
Upvotes: 0