Lucas Aimaretto
Lucas Aimaretto

Reputation: 1489

Fixed/loose distance between nodes with networkx

I want to represent a computer network. Devices have several ports that connect to another device's port. For example, here you see that port 1/1/1 of device a connects to port 1/1/1 of device b. So far, so good ...

enter image description here

Now I want to stick together (real close) ports to nodes, so that the distance between a node and its port, be zero. But the distance between ports-to-ports, should be loose. Bear in mind that ports and nodes in my network are represented both as nodes in the networkx abstraction ...

So far I have achieved this by controlling the weight of edge, when linking together a node and its port, by assigning a high value.

G.add_edge(node,node_port[0], w=2000)

I can read that value later on with pos = nx.spring_layout(G, weight='w'). But no matter how big w is, I cannot achive a zero distance between nodes and ports.

Any ideas? Thanks!

Upvotes: 1

Views: 676

Answers (1)

Johannes Wachs
Johannes Wachs

Reputation: 1310

When you run:

pos = nx.spring_layout(G, weight='w')

you get a dictionary in which keys are nodes and values are 2D coordinates. You can use this to create a new dictionary in which you manually overwrite the port positions with that of their device, if I understand you correctly.

Specifically:

  1. initialize a new dictionary pos2.
  2. loop over the nodes: if the node is a device, look up its coordinates in pos and add it to pos2. If the node is a port, look up its corresponding device's coordinates in pos and add the port node to pos2 with those coordinates.

Then call nx.draw, passing pos2 as the position of your nodes. Hope that is clear and that I'm interpreting you correctly.

Upvotes: 1

Related Questions