Python 将NetworkX与matplotlib.ArtistAnimation一起使用

Python 将NetworkX与matplotlib.ArtistAnimation一起使用,python,matplotlib,networkx,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

我想做的是创建一个动画,其中图形的节点随时间改变颜色。当我在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()
所以我想我可以这样做:

#!/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

谢谢

--克雷格

nx.draw
不返回任何内容,因此您的方法不起作用。最简单的方法是使用
nx绘制
节点
。绘制网络x节点
nx。绘制网络x边
,它们返回
PatchCollection
LineCollection
对象。然后可以使用
set\u array
更新节点的颜色

使用相同的通用框架,您还可以移动节点(通过
PatchCollection
set\u offset
set\u verts
LineCollection
set\u segments


我看过的最好的动画教程:

它会给你任何错误吗?在什么方面不起作用?你检查了
nx.draw的返回值了吗?太好了!实际上,功能动画似乎比艺术动画更能控制我在做什么;这正是我需要的。谢谢