Balloon
Balloon

Reputation: 7

D3 force layout: individually positioning first and last node

I would like to create a static force-directed layout as the one in this example: http://bl.ocks.org/mbostock/1667139, but with the first and last node anchored on each side of the window (contrary to the example, my graph is not circular). This way I could clearly see where the graph starts and ends and also hopefully be able to give it a more linear conformation. So far I have attempted to assign different classes to these two nodes and then give those classes fixed coordinates, like:

svg.select(".first")
  .attr("cx", function(d) { return 10; })
  .attr("cy", function(d) { return height/2; })

svg.select(".last")
  .attr("cx", function(d) { return width-10; })
  .attr("cy", function(d) { return height/2; })

But it doesn't seem to be working, the two nodes are just sitting in the upper right corner of the window. Any ideas?

Upvotes: 0

Views: 678

Answers (1)

JSBob
JSBob

Reputation: 1046

Placing the following code between the for loop and force.stop() seemed to work fine for me.

var nodes = force.nodes();
nodes[0].x = 10;
nodes[0].y = height/2;

nodes[nodes.length-1].x = width-10;
nodes[nodes.length-1].y = height/2;

Here's a Fiddle showing this. You might also want to look into the fixed property, which could help with the behaviour you're looking for.

Upvotes: 1

Related Questions