Networkx Spring Layout with Different Edge Values

后端 未结 2 1755
旧巷少年郎
旧巷少年郎 2021-01-03 09:24

I am new to Networkx and trying to figure out how to use the spring layout but applying different edge values (i.e., different distances between nodes) between nodes rather

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 10:14

    You can accomplish what you're after (almost).

    1) You can predefine some weights that will affect the node distances. (but you can't specify the distance directly)

    2) You can feed an initial position into the spring_layout algorithm, which will result in a consistent final output. (You can even specify certain nodes that aren't allowed to change position if you want that as well). Or you can assign a seed to the random number generator used by nx.spring_layout using the optional argument seed.

    import networkx as nx
    
    G = nx.Graph()
    G.add_edges_from([(1,2, {'myweight':20}), (2,3,{'myweight':0.1}), 
                      (1,4,{'myweight':1}), (2,4,{'myweight':50})])
    initialpos = {1:(0,0), 2:(0,3), 3:(0,-1), 4:(5,5)}
    pos = nx.spring_layout(G,weight='myweight', pos = initialpos)
    
    nx.draw_networkx(G,pos)
    
    import pylab as plt
    plt.savefig('test.png')
    

    enter image description here

    Documentation is available here. The source code can be found here.

    Look at nx.draw if you want rid of axes.

    Note that there are other ways to add weighted edges than just what I've done.

提交回复
热议问题