1

I made this function that gives a network animation based on a given random node labels generated in a loop, but I want to be able to record this animation, still can't figure out how I can do it. Here is the code:

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)
mac179
  • 1,540
  • 1
  • 14
  • 24

1 Answers1

0

You can plt.savefig(f'{n}.png') them and after create a gif with a specialized tool (you can find that on internet easily)

Icarwiz
  • 184
  • 6
  • Thank you for the feedback ! is there any way I Can make it without having to save the figures (that's what I should have Said actually) – mac179 Mar 07 '21 at 18:07
  • 1
    I guess you could use io.BytesIO to redirect the content of savefig to a variable, and then into a list... But as I don't have a gif creator module for Python in mind (check out on internet) I don't see why that would help... – Icarwiz Mar 07 '21 at 18:20
  • 1
    Take a look here: https://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python – Sparky05 Mar 08 '21 at 09:06