Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change nodes to be rectangles instead of circles in a d3 force layout?

How can I change the nodes to be rectangles instead of circles in the following d3 forced directed graph?

like image 974
Anthati Nagaraju Avatar asked Jul 25 '13 09:07

Anthati Nagaraju


1 Answers

You have to append a rect SVG element instead of a circle.

So, in the script, where it shows this:

var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag);

You should change it to maybe this:

var node = svg.selectAll(".node")
      .data(graph.nodes)
    .enter().append("rect")
      .attr("class", "node")
      .attr("width", 40)
      .attr("height", 20)
      .style("fill", function(d) { return color(d.group); })
      .call(force.drag);

And, where it shows:

node.attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });

Change it to:

node.attr("x", function(d) { return d.x; })
    .attr("y", function(d) { return d.y; });
like image 56
Joum Avatar answered Sep 22 '22 02:09

Joum