Networkx Spring Layout with Different Edge Values

后端 未结 2 1756
旧巷少年郎
旧巷少年郎 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.

    0 讨论(0)
  • 2021-01-03 10:22

    According to the documentation spring_layout takes a weight-keyword which is the name of the edge attribute to use as weight when applying the layout. An example:

    import networkx as nx
    import random
    G = nx.path_graph(5)
    
    # Add some random weights (as dictonary with edges as key and weight as value).
    nx.set_edge_attributes(G, 'my_weight', dict(zip(G.edges(), [random.random()*10 for edge in G.edges()])))
    
    # Apply layout using weights.
    pos = nx.spring_layout(G, weight='my_weight')
    nx.draw(G, pos)
    
    0 讨论(0)
提交回复
热议问题