python – 将LineCollection转换为数组或动画化Networkx图

我试图使用networkx.draw函数的输出,这是一个集合(LineCollection),用于需要数组的matplotlib.animation.我不想把我的身材保存为png,因为会有很多.我也不想展示它,但这并不重要.

一个简单的代码可以是:

import networkx as nx
graph= nx.complete_graph(5) #a simple graph with five nodes
Drawing=nx.draw(graph)

这会输出一个python集合:

<matplotlib.collections.LineCollection at 0xd47d9d0>

我想创建一个这种图纸的列表:

artists=[]
artists.append(Drawing)

并进一步在动画中使用这些绘图:

import matplotlib
fig= plt.figure()  #initial figure, which can be empty
anim=matplotlib.animation.ArtistAnimation(fig, artists,interval=50, repeat_delaty=1000)

但是我得到一个TypeError如下:

TypeError: 'LineCollection' object is not iterable

所以,我认为“艺术家”列表应该是一个图像列表,应该是numpy数组或png图像或称为PIL(我不熟悉)的东西,我不知道如何将集合转换为其中一个没有将图像保存为png或任何其他格式的图像.

实际上这就是我想要做的:a dynamic animation,当我尝试使用im = plt.imshow(f(x,y))和我的一张图纸时,它给出了这个错误:

TypeError: Image data can not convert to float

我希望我足够清楚,这是我第一次使用动画和绘图工具.有没有人有办法解决吗?

最佳答案 这是一个动态动画(如果你想这样看,它可以在iPython笔记本中使用).基本上,您希望使用draw_networkx并为其提供要为每个帧绘制的项目.为防止每次调用该函数时位置发生变化,您需要重复使用相同的位置(下方位置).

%pylab inline  #ignore out of ipython notebook
from IPython.display import clear_output #ignore out of ipython notebook

import networkx as nx
graph= nx.complete_graph(5) #a simple graph with five nodes

f, ax = plt.subplots()

pos=nx.spring_layout(graph)

for i in range(5):
    nx.draw_networkx(graph, {j:pos[j] for j in range(i+1)}, ax=ax, nodelist=graph.nodes()[0:i+1], 
                     edgelist=graph.edges()[0:i], with_labels=False)
    ax.axis([-2,2,-2,2]) #can set this by finding max/mins

    time.sleep(0.05)
    clear_output(True) #for iPython notebook
    display(f)
    ax.cla() # turn this off if you'd like to "build up" plots

plt.close()
点赞