使用NetworkX和matplotlib.ArtistAnimation

5

我想做的是创建一个动画,在动画中,图形的节点会随着时间改变颜色。当我在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格式。
谢谢!
--Craig

它是否给你任何错误?它的工作方式有何不同?您检查过 nx.draw 的返回值吗? - tacaswell
1个回答

15
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_nodesnx.draw_networkx_edges来绘制nodesedges,它们会返回PatchCollectionLineCollection对象。然后可以使用set_array更新节点的颜色。

使用相同的框架,您还可以移动节点(通过set_offsets对于PatchCollectionset_vertsset_segments对于LineCollection)。

我看过的最佳动画教程:http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/


1
太好了!FuncAnimation似乎比ArtistAnimation更能控制我正在做的事情;这正是我所需要的。谢谢。 - cjolley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接