7

I am following this tutorial: > http://bl.ocks.org/mbostock/4062045 for visualising a Force Directed Graph in D3 Javascript. The link above has the code and JSON file as well. I have two questions. How are the nodes linked? Here is the code for the links and nodes and their positions:

force.on("tick", function() {
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; });

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

My second question: Could anyone please help me draw a sample of two nodes (circles) and one link between these two nodes so I can understand how this graph works. Your assistance would be very much appreciated.

1 Answer 1

7

Whether two nodes are linked or not is determined by the data. In particular, it contains lines such as

{"source":1,"target":0,"value":1}

which tell it which nodes (by index) to link. The indices refer to the list of nodes also given in the data. This data is given to D3 in this block:

var link = svg.selectAll(".link")
    .data(graph.links)
  .enter().append("line")
    .attr("class", "link")
    .style("stroke-width", function(d) { return Math.sqrt(d.value); });

So for each element in graph.links, a line will be added. At this point, the line doesn't have a start or end point, so it is not drawn -- only the element is added. Then, while the simulation is running, the start and end points of the lines are set based on the current state of the simulation. This is the code that you have in your question.

The following code would draw two circles and a link between them.

var svg = d3.select("body").append("svg").attr("width", 100).attr("height", 100);
svg.append("circle").attr("cx", 10).attr("cy", 10);
svg.append("circle").attr("cx", 90).attr("cy", 90);
svg.append("line").attr("x1", 10).attr("y1", 10).attr("x2", 90).attr("y2", 90);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this explanation. Do you think I can create the circles and then I link them together after creating that link? Is that possible?
You can create the line that links them any time you want.
Keep in mind that there's a distinction between the data nodes and links and the SVG nodes and links.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.