我想做的是创建一个动画,其中图形的节点会随着时间而改变颜色。当我在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
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
不返回任何内容,因此您的方法不起作用。最简单的方法是使用返回PatchCollection
和LineCollection
对象的nx.draw_networkx_nodes
和nx.draw_networkx_edges
绘制nodes
和edges
。然后可以使用set_array
更新节点的颜色。
使用相同的通用框架,您也可以移动节点(通过set_offsets
用于PatchCollection
,通过set_verts
或set_segments
用于LineCollection
)
我看过的最好的动画教程:http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/