2

I am currently working on a GUI with AngularJS, which contains a graph given with it's nodes and connections in a javascript objects like this:

Nodes = [{'name': 'name1', x: 0, y: 0, id: 1}, {'name': 'name2', x: 0, y: 0, id: 2}, {'name': 'name3', x: 0, y: 0, id: 3}];
Connections = [{'from': 1, 'to': 2}, {'from': 1, 'to': 3}];

What I need to do, is give the x and y values for every node. At the moment I am using a simple offset to avoid overlapping and render node-by-node, but I would like to calculate x and y values for each node to have a proper layout.

Is there an algorithm, that I give my nodes and connections to and returns with a layout (x, y values for every node), which is better looking than my simple solution?

I have tried D3, but I am already using a third party library for the graph and it's hard to integrate it, so a optimal solution would be to simply give the coordinates for the current library's data structure (Nodes and Connections).

1 Answer 1

1

From D3.js Force directed layout you can find such an algorithm. If you leave out the drawing code, you end up with the following:

var width = 100;
var height = 100;
var Nodes = [{'name': 'name1', x: 0, y: 0, id: 1}, {'name': 'name2', x: 0, y: 0, id: 2}, {'name': 'name3', x: 0, y: 0, id: 3}];
var Connections = [{'source': 1, 'target': 2}, {'source': 1, 'target': 3}];

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) { return d.id; }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

simulation
    .nodes(Nodes);

simulation.force("link")
    .links(Connections);

console.log(Nodes, Connections);

If you now open your console and inspect the Nodes variable, you will see the x and y positions are updated.

Sign up to request clarification or add additional context in comments.

Comments

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.