0

I have written the following code to animate the colours of the graph nodes in jupyter notebook.

%matplotlib notebook

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation

def update(i,G,pos,t,ax):
    ax.clear()
    cmap = matplotlib.cm.get_cmap('Blues')
    color_map = []
    for node in G:
        color_map.append(cmap(t[i]))

    nx.draw(G,pos,node_color=color_map,ax=ax)

t = np.linspace(0,1,10)
G = nx.petersen_graph()
pos = nx.spring_layout(G) # positions for all nodes   

fig, ax = plt.subplots(figsize=(8,6))

ani = matplotlib.animation.FuncAnimation(fig,update,repeat=True,interval=100,frames=len(t),repeat_delay=10,fargs=(G, pos, t, ax))
plt.show()

Although this works in my case, I would like to be able to execute the whole program inside a function like so

%matplotlib notebook

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation

def update(i,G,pos,t,ax):
    ax.clear()
    cmap = matplotlib.cm.get_cmap('Blues')
    color_map = []
    for node in G:
        color_map.append(cmap(t[i]))

    nx.draw(G,pos,node_color=color_map,ax=ax)

def anim():
    t = np.linspace(0,1,10)
    G = nx.petersen_graph()
    pos = nx.spring_layout(G) # positions for all nodes   

    fig, ax = plt.subplots(figsize=(8,6))

    ani = matplotlib.animation.FuncAnimation(fig,update,repeat=True,interval=100,frames=len(t),repeat_delay=10,fargs=(G, pos, t, ax))
    plt.show()

anim()

This one, however, does not work because the unlike in the first script, tha animation does not display in jupyter notebook. Could someone tell me why? Note that I want to display the animation in the console of jupyter notebook and not saved as a gif for example.

Adam Gosztolai
  • 242
  • 1
  • 3
  • 14
  • 1
    You have turned interactive mode on, which means `plt.show()` is non-blocking. Hence the `anim()` function returns and the `ani` variable inside is garbage collected. Add a `return ani` at the end of the function and store it outside, `ani = anim()` – ImportanceOfBeingErnest Sep 23 '19 at 12:50
  • Excellent, thank you. Could you add it as a solution? – Adam Gosztolai Sep 23 '19 at 12:52

0 Answers0