Construct and label a uniform graph in NetworkX using dictionaries?

378 views Asked by At

How can you use node position and edge information to label a graph in NetworkX?

I like the structured nature of the hypercube_graph() instead of the randomness of the spring_layout(). I'm aware that NetworkX only plots in 2D, but the hypercube_graph() projects an N dimensional object in 2D and I would like to use this layout with my own labels. enter image description here

For a 3 dimensional figure, the nx.Graph() is uniform (not random) but not for a 4 dimensional figure. I am using 3D as a simple version of higher dimensional cubes.

Currently, I have a dictionary of nodes to edges:

D_node_edge = {'pr': ['pqr'], 
               'pq': ['pqr'], 
               'p': ['pq', 'pr'], 
               'qr': ['pqr'], 
               'q': ['pq', 'qr'], 
               '0': ['p', 'q', 'r'], 
               'pqr': [], 
               'r': ['pr', 'qr']}

and a dictionary of nodes to positions within a graph:

D_node_pos = {'pr': (1, 0, 1), 
              'qr': (0, 1, 1), 
              'p': (1, 0, 0), 
              'pq': (1, 1, 0), 
              'q': (0, 1, 0), 
              '0': (0, 0, 0), 
              'pqr': (1, 1, 1), 
              'r': (0, 0, 1)}

I want to use a DiGraph():

axis_labels = ['p','q','r']
dimension = len(axis_labels) #3 in this case

H = nx.DiGraph()

with the layout of a hypercube_graph

HC = nx.hypercube_graph(dimension) #dimension = 3

>>>nx.spring_layout(HC, dim = dimension)

{(1, 1, 0): array([ 0.69543835,  0.37689489,  0.48037435]), 
 (0, 1, 1): array([ 0.27055875,  0.        ,  0.36329725]), 
 (1, 0, 0): array([ 0.41149329,  0.76917215,  0.60675544]), 
 (0, 0, 1): array([ 0.        ,  0.43156976,  0.51814906]), 
 (1, 0, 1): array([ 0.33865646,  0.53760327,  0.16742205]), 
 (0, 0, 0): array([ 0.04858308,  0.73062358,  1.        ]), 
 (0, 1, 0): array([ 0.34010671,  0.27698965,  0.81225166]), 
 (1, 1, 1): array([ 0.65369567,  0.13626658,  0.        ])}

Is there any way to assign the layout positions of the hypercube_graph() to my nodes using the dictionaries I've created?

It doesn't work when I try to draw it:

nx.draw(H, pos = D_node_pos, with_labels = True, node_shape = 'o', arrows = True)

I understand that the "pos" dictionary needs to be keys= node and values= positions (e.g. 'p': array([ 0.41149329, 0.76917215, 0.60675544])) but it still didn't work :(

...
      File "/Users/Mu/anaconda/lib/python2.7/site-packages/matplotlib/path.py", line 148, in __init__
        assert vertices.shape[1] == 2
    AssertionError
0

There are 0 answers