将NetworkX与matplotlib.ArtistAnimation一起使用

cjo*_*ley 4 python matplotlib networkx

我想要做的是创建一个动画,其中图形的节点随时间改变颜色.当我在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()
Run Code Online (Sandbox Code Playgroud)

所以我想我可以这样做:

#!/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()
Run Code Online (Sandbox Code Playgroud)

我坚持的是,在使用nx.draw()绘制图形之后,我可以得到一个适当类型的对象,放入传递给ArtistAnimation的数组中.在第一个示例中,plt.imshow()返回matplot.image.AxesImage类型的对象,但nx.draw()实际上不返回任何内容.有没有办法可以让我的手放在合适的图像对象上?

当然,欢迎使用完全不同的方法(似乎在matplotlib中总是有很多不同的方法可以做同样的事情),只要我在完成时就可以将动画保存为mp4.

谢谢!

--craig

tac*_*ell 8

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)
Run Code Online (Sandbox Code Playgroud)

nx.draw没有返回任何东西,因此为什么你的方法不起作用.最简单的方法是绘制nodesedges使用nx.draw_networkx_nodes以及nx.draw_networkx_edges返回PatchCollectionLineCollection对象.然后,您可以使用更新节点的颜色set_array.

使用相同的总体框架的工作,你也可以左右移动节点(通过set_offsetsPatchCollectionset_vertsset_segmentsLineCollection)

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