How to draw a simple Force-oriented chart in D3 Javascript

I follow this guide:> http://bl.ocks.org/mbostock/4062045 , which is mainly intended to render Force_Directed diagrams in D3 Javascript. The link above has the code and the JSON file. I have two questions about this. I managed to understand the code. However, how can a program communicate between nodes in this way, and on what basis are these nodes connected to each other? Here is the code for link and node 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 dx; }) .attr("cy", function(d) { return dy; }); }); 

My second question is: can someone help me make a very simple and small sample of two nodes (circles) and one link between these two nodes so that I can understand how this graph works and how this graph will be based on a very simple JSON file. Your help will be greatly appreciated.

+7
json javascript force-layout
source share
1 answer

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

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

which report which nodes (by index) to associate. Indexes refer to the list of nodes also indicated in the data. This data is given by 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 stage, the line does not 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 you have in your question.

The following code will 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); 
+7
source share

All Articles