【问题标题】:Converting LineCollection to array OR animating Networkx graph将 LineCollection 转换为数组或动画 Networkx 图
【发布时间】:2014-08-14 16:07:37
【问题描述】:

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

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

【问题讨论】:

    标签: python animation numpy matplotlib networkx


    【解决方案1】:

    这是一个动态动画(如果您想以这种方式查看,可以在 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()
    

    【讨论】:

    • 我用 Ipython 尝试了你的代码,它给出了这样的输出 '' 没有显示。您的代码不会清除显示,而只会清除轴,我不明白为什么我们每次都应该重新编写轴。我想要做的是清除图像并重新绘制它。我自己用'plt.ion()'和'plt.show()'和'clf()'尝试过,python显示由于某种原因崩溃,这无助于我保存动画,有什么想法吗?而且我也是用'nx.draw_network(graph, pos)'这个位置,和它有区别吗?
    • 我只是使用了this answer 的一个想法,用pause() 代替了计时器,用pylab.draw() 代替了plt.show,我不知道为什么,但它奏效了!所以你可以忽略以前的问题。但是还是不能解决视频问题。
    • 抱歉,我不确定您所说的视频问题是什么意思?如果你取消注释最后第二行here,你应该得到视频
    • matplotlib 网站中的那个例子使用一个函数来创建每个图像,它输出一个数组。 matplotlib.animation.ArtistAnimation 需要一个 numpy 数组或 png 图像来创建动画。在我的情况下,networkx 输出我无法使用的集合,所以我必须将它们保存为 png。但我不想这样做,因为会有很多图像。我最初的问题是如何在不保存每个新图像的情况下将集合转换为数组或等价于 png 的东西;这样我就可以用它来制作视频了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多