gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:37 27 4
gpt4 key购买 nike

我正在尝试使用 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

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

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

TypeError: Image data can not convert to float

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

最佳答案

这是一个动态动画(如果您想以这种方式查看,可以在 iPython notebook 中使用)。本质上,您想要使用 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()

关于python - 将 LineCollection 转换为数组或动画 Networkx 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24385892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com