简体   繁体   中英

networkx: drawing graphs consistently

I am working on plotting 3D cubes, 4D hypercubes, and 5D hypercubes using networkx.

How do I control how the draw() function works? I would like them all to come out at the exact same angle, size, and labeling.

cnt = 0
for uniqHC in nx_hcl:
    plt.figure()
    nx.draw(uniqHC)
    plt.savefig("uniqHC_" + str(cnt))
    plt.close()
    #nx.relabel_nodes(uniqHC, flatten)
    cnt += 1

As you can see, the first one is not bad, the second one is not what I want. It's too hard to understand and compare what is going on. And this is just 3D

在此处输入图片说明

在此处输入图片说明

The software can plot hypercubes, and they look great. I would like my graphs to be plotted in the same style. Below shows a picture of what I want for the 3D case. My labeling of just '000', '001' is fine. I have tried being clever and starting with their hypercube and removing directed edges and adding my direction, but it distorts the shape of the graph randomly, and it looks as before!

HC = nx.hypercube_graph(3)
DHC = nx.convert.convert_to_directed(HC)
nx.draw(HC)

在此处输入图片说明

You might not be able to get the results you want (consistent orientation and spacing) using the spring-layout method in networkx. That is the default and what is happening when you call draw().

If you know where you want the nodes to be positioned to can specify that exactly like so

In [1]: import networkx as nx

In [2]: G = nx.hypercube_graph(2)

In [3]: pos = nx.spring_layout(G)

In [4]: pos
Out[4]: 
{(0, 0): array([ 0.67137792,  0.44182572]),
 (0, 1): array([ 0.42261686,  1.        ]),
 (1, 0): array([ 0.24869904,  0.        ]),
 (1, 1): array([ 0.        ,  0.55858863])}

In [5]: pos[(0,0)]=(0,0)

In [6]: pos[(0,1)]=(0,1)

In [7]: pos[(1,0)]=(1,0)

In [8]: pos[(1,1)]=(1,1)

In [9]: nx.draw(G,pos)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM