我想做的是创建一个动画,其中图形的节点随时间改变颜色。当我在 matplotlib 中搜索有关动画的信息时,我通常会看到类似这样的示例:
#!/usr/bin/python
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
fig = plt.figure(figsize=(8,8))
images = []
for i in range(10):
data = np.random.random(100).reshape(10,10)
imgplot = plt.imshow(data)
images.append([imgplot])
anim = ArtistAnimation(fig, images, interval=50, blit=True)
anim.save('this-one-works.mp4')
plt.show()
所以我想我可以做这样的事情:
#!/usr/bin/python
import numpy as np
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
G = nx.Graph()
G.add_edges_from([(0,1),(1,2),(2,0)])
fig = plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(G)
images = []
for i in range(10):
nc = np.random.random(3)
imgplot = nx.draw(G,pos,with_labels=False,node_color=nc) # this doesn't work
images.append([imgplot])
anim = ArtistAnimation(fig, images, interval=50, blit=True)
anim.save('not-this-one.mp4')
plt.show()
我坚持的是,在使用 nx.draw() 绘制图形后,我如何获得适当类型的对象以放入传递给 ArtistAnimation 的数组中。在第一个示例中,plt.imshow() 返回一个 matplot.image.AxesImage 类型的对象,但 nx.draw() 实际上不返回任何内容。有没有办法让我得到合适的图像对象?
当然,欢迎使用完全不同的方法(似乎在 matplotlib 中总是有许多不同的方法来做同样的事情),只要我可以在完成后将我的动画保存为 mp4。
谢谢!
--克雷格
最佳答案
import numpy as np
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
G = nx.Graph()
G.add_edges_from([(0,1),(1,2),(2,0)])
fig = plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(G)
nc = np.random.random(3)
nodes = nx.draw_networkx_nodes(G,pos,node_color=nc)
edges = nx.draw_networkx_edges(G,pos)
def update(n):
nc = np.random.random(3)
nodes.set_array(nc)
return nodes,
anim = FuncAnimation(fig, update, interval=50, blit=True)
nx.draw
不返回任何内容,因此您的方法不起作用。最简单的方法是使用 nx.draw_networkx_nodes
和 nx.draw_networkx_edges
绘制 nodes
和 edges
返回 PatchCollection
和 LineCollection
对象。然后,您可以使用 set_array
更新节点的颜色。
使用相同的通用框架,您还可以移动节点(通过 set_offsets
用于 PatchCollection
和 set_verts
或 set_segments
用于 LineCollection
)
我见过的最好的动画教程:http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
关于python - 将 NetworkX 与 matplotlib.ArtistAnimation 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18229563/