【问题标题】:Draw different graphs at the same position/co-ordinates in python using networkX and matplotlib使用networkX和matplotlib在python中的相同位置/坐标绘制不同的图形
【发布时间】:2018-07-27 21:17:03
【问题描述】:

图表 1:

邻接表:

2: [2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14]

3: [2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14]

5: [2, 3, 4, 5, 6, 7, 8, 9]

剧情:

`import networkx as nx 
 G = nx.Graph() 
 G1 = nx.Graph() 
 import matplotlib.pyplot as plt 
 for i, j in adj_list.items():
     for k in j:
           G.add_edge(i, k)  
pos = nx.spring_layout(G) 
nx.draw(G, with_labels=True, node_size = 1000, font_size=20)
plt.draw() 
plt.figure() # To plot the next graph in a new figure
plt.show() `

Graph 1

在图2中,我正在消除一些边并重新绘制图形,但是节点的位置正在改变,如何存储下一个图形的节点位置?

【问题讨论】:

    标签: python-3.x matplotlib networkx


    【解决方案1】:

    您需要在绘制图表时重新使用您的 pos 变量。 nx.spring_layout 返回一个字典,其中节点 id 是键,值是要绘制的节点的 x,y 坐标。只需重用相同的pos 变量并将其作为属性传递给nx.draw 函数,就像这样

    import networkx as nx 
    import matplotlib.pyplot as plt
    G = nx.Graph() 
    G1 = nx.Graph()
    adj_list = {2: [2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14],    
    3: [2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14],    
    5: [2, 3, 4, 5, 6, 7, 8, 9]}
    import matplotlib.pyplot as plt 
    for i, j in adj_list.items():
        for k in j:
            G.add_edge(i, k)  
    pos = nx.spring_layout(G)   #<<<<<<<<<< Initialize this only once
    nx.draw(G,pos=pos, with_labels=True, node_size = 1000, font_size=20)  #<<<<<<<<< pass the pos variable
    plt.draw() 
    plt.figure() # To plot the next graph in a new figure
    plt.show()
    

    现在我将创建一个新图并只添加一半的边

    cnt = 0
    G = nx.Graph()
    for i, j in adj_list.items():
        for k in j:
            cnt+=1
            if cnt%2 == 0:
                continue
            G.add_edge(i, k)  
    
    nx.draw(G,pos=pos, with_labels=True, node_size = 1000, font_size=20)  #<-- same pos variable is used
    plt.draw() 
    plt.figure() # To plot the next graph in a new figure
    plt.show()
    

    如您所见,只添加了一半的边,节点位置仍然保持不变。

    【讨论】:

    • 谢谢你 Mohammed Kashif :)
    猜你喜欢
    • 2015-12-05
    • 2018-02-18
    • 1970-01-01
    • 2020-03-01
    • 2020-03-13
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多