networkx add_node with specific position

后端 未结 2 1738
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 00:56

I am still a beginner with networkx I want to add multiple types of nodes in different position, I used the following code

pos = {0: (40, 20), 1: (20, 30),          


        
相关标签:
2条回答
  • 2020-12-13 01:04

    I'm not completely sure what you want to accomplish, but I think you want to add nodes to the graph, draw them in the wanted positions and still be able to access them in the graph object.

    Since you don't add the nodes to the graph, that would be a start:

    X.add_nodes_from(pos.keys())
    

    Then you don't have to specify the node list when drawing the graph, and thus you don't have to change the code in two different places when adding new nodes.

    If you want the position of the node as a node attribute, you could do that as well:

    for n, p in pos.iteritems():
        X.nodes[n]['pos'] = p
    

    Just note that these positions won't be used as the position when drawing the graph, it has to be set explicitly. You could then draw and display the graph with:

    nx.draw(X, pos)
    plt.show()
    

    assuming that you did the import from matplotlib import pyplot as plt.

    0 讨论(0)
  • 2020-12-13 01:21

    You can use the following approach to set individual node positions and then extract the "pos" dictionary to use when drawing.

    In [1]: import networkx as nx
    
    In [2]: G=nx.Graph()
    
    In [3]: G.add_node(1,pos=(1,1))
    
    In [4]: G.add_node(2,pos=(2,2))
    
    In [5]: G.add_edge(1,2)
    
    In [6]: pos=nx.get_node_attributes(G,'pos')
    
    In [7]: pos
    Out[7]: {1: (1, 1), 2: (2, 2)}
    
    In [8]: nx.draw(G,pos)
    

    UPDATE

    Add drawing

    0 讨论(0)
提交回复
热议问题