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

4 投票
1 回答
851 浏览
提问于 2025-04-18 10:53

我正在尝试使用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: 'LineCollection' object is not iterable

所以,我发现“artists”列表应该是一个图像列表,这些图像要么是numpy数组,要么是png图像,或者是一些我不太熟悉的东西叫做PIL,而我不知道怎么把一个集合转换成这些格式,而不需要把图像保存为png或其他格式。

实际上,我想做的是:一个动态动画,当我尝试用im = plt.imshow(f(x, y))来显示我拥有的某个绘图时,出现了这个错误:

TypeError: Image data can not convert to float

我希望我说得够清楚,这是我第一次使用动画和绘图工具。有没有人能给我一个解决方案?

1 个回答

2

这里有一个动态动画(如果你想在iPython笔记本中查看,可以这样做)。基本上,你需要使用 draw_networkx 这个函数,并给它提供每一帧要绘制的内容。为了避免每次调用这个函数时位置都发生变化,你需要重复使用相同的位置(下面的 pos)。

%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()

撰写回答