我正在处理增量图,所以每次我在上一张图的顶部插入一条新边时,我都想绘制当前图。
使用这段代码,我可以一次生成一个图形,但它们只会在迭代结束后显示。
import random
import time
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
#Generating some random edges
M = 10
N = 4
edges = []
for i in range(M):
s = random.randrange(N) + 1
t = random.randrange(N) + 1
edges.append((s,t))
G = nx.DiGraph()
G.add_nodes_from(range(1, 5))
plt.subplot(121)
plt.ion()
nx.draw(G, with_labels=True, font_weight='bold')
for edge in edges:
plt.figure()
G.add_edge(*edge)
nx.draw(G, with_labels=True, font_weight='bold')
time.sleep(1)
但我真正想要的是看到图表在每次迭代时都被重新绘制,或者至少能够使用 Matplotlib 的交互模式将它们堆叠起来,这样我就可以前进和后退。
我搜索了好几天,找到了一些使用条形图、饼图等图形的示例,但我指的图形是数据结构,而不是图表。
这里建议使用FuncAnimation
,它大大简化了在matplotlib
中创建动画/实时图形的整个过程
import random
import time
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook
#Generating some random edges
M = 10
N = 4
edges = []
for i in range(M):
s = random.randrange(N) + 1
t = random.randrange(N) + 1
edges.append((s,t))
G = nx.DiGraph()
G.add_nodes_from(range(1, 5))
fig = plt.figure()
ax = plt.subplot(121)
def init():
nx.draw(G, with_labels=True, font_weight='bold')
def update(edge):
G.add_edge(*edge)
nx.draw(G, with_labels=True, font_weight='bold')
ani = animation.FuncAnimation(fig, update, frames=edges, interval=1000., init_func=init, repeat=False)
我是一名优秀的程序员,十分优秀!