Skip to content Skip to sidebar Skip to footer

Networkx In Python: Connect Only Values Not Keys

I face a similar problem to the SO question here, with almost the same data as described: graph = { '1': ['2', '3', '4'], '2': ['5','11','12','13','14','15'], '3' : ['6

Solution 1:

What you're asking is possible, I think you're just confused about how NetworkX graphs work. When you add a node to the graph, you pass in an ID to represent that node. Internally NetworkX uses this value to track individual nodes. When connect two nodes together, you pass two ids (representing nodes) to connect.

In your explanation of your problem you are wanting NetworkX to accept the same ID twice, but 'forget' that ID already represents a node. That's not possible.

You have two options:

  1. Plot the indiviudal graphs individually (this allows you to re-used IDs at will)
  2. Create unique IDs for each subgraph, but change the labels on the nodes.

The following is an example of the second approach. Here the key in the graph dictionary is used to create a unique ID set for each subgraph, e.g. 1_2, 1_3, 1_4, etc. We store the unique IDs with the label, and apply these when creating the plot. That way it looks like multiple nodes have the same ID, even though they do not.

import networkx
from itertools import combinations

graph = {
    '1': ['2', '3', '4'],
    '2': ['5','11','12','13','14','15'],
    '3' : ['6','7','66','77'],
    '5': ['6', '8','66','77'],
    '4': ['7','66','77'],
    '7': ['9', '10']
}

g = networkx.Graph()
labels = {}

for k, vs in graph.items():
    vs.append(k)
    for a, b in combinations(vs, 2):
        # We're creating multiple 'subnetworks', so prefix the ids
        node_a = '%s_%s' % (k, a)
        node_b = '%s_%s' % (k, b)

        g.add_edge(node_a,node_b)

        # Store labels
        labels[node_a] = a
        labels[node_b] = b

# Draw the graph, replacing the labels to hide the unique IDs            
networkx.draw_spring(g, labels=labels)

This produces the following image, as you can see multiple nodes have the same label, even though behind the scenes they have distinct IDs.

enter image description here

Post a Comment for "Networkx In Python: Connect Only Values Not Keys"