NetworkX:首先完整地绘制相同的图形,然后删除一些节点

时间:2016-10-07 13:46:33

标签: python matplotlib networkx

假设我有一个包含10个节点的图表,我想在以下时间绘制它:

  1. 完好无损
  2. 删除了几个节点
  3. 如何确保第二张图与第一张图的位置完全相同?

    我尝试生成两个使用不同布局绘制的图形:

    import networkx as nx
    import matplotlib.pyplot as plt
    %pylab inline
    
    #Intact
    G=nx.barabasi_albert_graph(10,3)
    fig1=nx.draw_networkx(G)
    
    #Two nodes are removed
    e=[4,6]
    G.remove_nodes_from(e)
    plt.figure()
    fig2=nx.draw_networkx(G)
    

2 个答案:

答案 0 :(得分:4)

networkx的绘图命令接受参数pos

因此,在创建fig1之前,请定义pos这两行应为

pos = nx.spring_layout(G) #other layout commands are available.
fig1 = nx.draw_networkx(G, pos = pos)

稍后你会做

fig2 = nx.draw_networkx(G, pos=pos).

答案 1 :(得分:1)

以下适用于我:

import networkx as nx
import matplotlib.pyplot as plt
from random import random


figure = plt.figure()
#Intact
G=nx.barabasi_albert_graph(10,3)

node_pose = {}
for i in G.nodes_iter():
    node_pose[i] = (random(),random())

plt.subplot(121)
fig1 = nx.draw_networkx(G,pos=node_pose, fixed=node_pose.keys())

#Two nodes are removed
e=[4,6]
G.remove_nodes_from(e)
plt.subplot(122)
fig2 = nx.draw_networkx(G,pos=node_pose, fixed=node_pose.keys())


plt.show()

enter image description here