Skip to content Skip to sidebar Skip to footer

Creating Fixed Set Of Nodes Using Networkx In Python

I have a problem concerning graph diagrams. I have 30 nodes(points). I want to construct an adjacency matrix in such a way that each ten set of nodes are like at a vertices of a tr

Solution 1:

I was able to get something going fairly quickly just by hacking away at this, all you need to do is put together tuples representing each edge, you can also set some arbitrary lengths on the edges to get a decent approximation of your desired layout:

import networkx
import string

all_nodes = string.ascii_letters[:30]
a_nodes = all_nodes[:10]
b_nodes = all_nodes[10:20]
c_nodes = all_nodes[20:]

all_edges = []
for node_set in [a_nodes, b_nodes, c_nodes]:
    # Link each node to the next
    for i, node in enumerate(node_set[:-1]):
        all_edges.append((node, node_set[i + 1], 2))
    # Finish off the circle
    all_edges.append((node_set[0], node_set[-1], 2))

joins = [(a_nodes[0], b_nodes[0], 8), (b_nodes[-1], c_nodes[0], 8), (c_nodes[-1], a_nodes[-1], 8)]

all_edges += joins
# One extra edge for C:
all_edges.append((c_nodes[0], c_nodes[5], 5))

G = networkx.Graph()
for edge in all_edges:
    G.add_edge(edge[0], edge[1], len=edge[2])

networkx.draw_graphviz(G, prog='neato')

Try something like networkx.to_numpy_matrix(G) if you then want to export as an adjacency matrix.

enter image description here

Post a Comment for "Creating Fixed Set Of Nodes Using Networkx In Python"