【问题标题】:How can I save a networkx animation?如何保存networkx动画?
【发布时间】:2021-06-05 17:29:03
【问题描述】:

我制作了这个函数,它根据循环中生成的给定随机节点标签提供网络动画,但我希望能够录制这个动画,但我仍然不知道该怎么做。 代码如下:

import networkx as nx 
import matplotlib.pyplot as plt
import numpy as np
import random
import time
from matplotlib.animation import FuncAnimation

global ax, fig, G
fig, ax = plt.subplots(figsize=(10,7))
G = nx.DiGraph()

def showNet(n):
    global ax, fig, G

    plt.style.use('fivethirtyeight')
    
    fig.clf()    

    l1, l2, l3, l4, l5, l6, l7 = n[0], n[1], n[2], n[3], n[4], n[5], n[6] 

    edgelist= [(l1,l2),(l2,l3), (l3,l4), (l3,l5), (l4, l1), (l5, l6), (l5, l7)]

    pos = {l1: (10, 60), l2: (10, 40), l3:(80, 40), l4:(140, 60), l5:(200, 20), l6:(250, 40), l7:(250,10)}
    
    nx.draw_networkx_nodes(G, pos=pos, nodelist=list(pos.keys()), node_size=2000, alpha=0.8) 
    nx.draw_networkx_edges(G, pos=pos, edgelist= edgelist , edge_color="gray", arrows=True, arrowsize=10, arrowstyle='wedge') 

    nx.draw_networkx_labels(G, pos=pos, labels=dict(zip(pos.keys(),pos.keys())),  font_color="black") 

    plt.grid(False)

    plt.ion() 
    fig.show() 
    plt.pause(0.0000001)

for i in range(30):
    n = random.sample(range(1, 10), 7)
    showNet(n)

【问题讨论】:

    标签: python matplotlib animation networkx


    【解决方案1】:

    你可以plt.savefig(f'{n}.png')他们,然后用专门的工具创建一个gif(你可以在网上很容易找到)

    【讨论】:

    • 感谢您的反馈!有什么办法可以让我不必保存数字(这就是我应该说的)
    • 我猜你可以使用 io.BytesIO 将 savefig 的内容重定向到一个变量,然后到一个列表中......但是因为我没有考虑到 Python 的 gif 创建器模块(在互联网上查看)我不明白为什么这会有所帮助......
    猜你喜欢
    • 2017-10-11
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2012-10-24
    • 2018-11-13
    • 1970-01-01
    • 2013-08-03
    相关资源
    最近更新 更多