Search code examples
pythonanimationgraphnetworkx

What tool to draw an animated network graph


I would like to obtain an animation of the probability distribution of a random walk on a complex graph. I currently use Python and NetworkX for the manipulation of the graph and the evaluation of the dynamics of the walk.

My goal is to have an animation (say, a GIF file) where each node of the graph has a size proportional to its degree (or other topological properties) and the color proportional to a scalar attribute (the probability distribution). The size and the position of the node remain fixed in time, but the color changes.

Currently, I'm able to draw the graph with the desired properties at a certain time instant using Gephi, but I would like to know how to do the animation, or how to automate the process of generating an image for each time instant.

Can somebody point out some reference where something similar has been done? I can also use different visualization tools other than Gephi. Actually, I would ideally have all my workflow in Python without resorting to external programs.


Solution

  • Fairly straightforward with FuncAnimation in matplotlib:

    import numpy as np
    import matplotlib.pyplot as plt; plt.close('all')
    import networkx as nx
    from matplotlib.animation import FuncAnimation
    
    def animate_nodes(G, node_colors, pos=None, *args, **kwargs):
    
        # define graph layout if None given
        if pos is None:
            pos = nx.spring_layout(G)
    
        # draw graph
        nodes = nx.draw_networkx_nodes(G, pos, *args, **kwargs)
        edges = nx.draw_networkx_edges(G, pos, *args, **kwargs)
        plt.axis('off')
    
        def update(ii):
            # nodes are just markers returned by plt.scatter;
            # node color can hence be changed in the same way like marker colors
            nodes.set_array(node_colors[ii])
            return nodes,
    
        fig = plt.gcf()
        animation = FuncAnimation(fig, update, interval=50, frames=len(node_colors), blit=True)
        return animation
    
    total_nodes = 10
    graph = nx.complete_graph(total_nodes)
    time_steps = 20
    node_colors = np.random.randint(0, 100, size=(time_steps, total_nodes))
    
    animation = animate_nodes(graph, node_colors)
    animation.save('test.gif', writer='imagemagick', savefig_kwargs={'facecolor':'white'}, fps=0.5)
    

    enter image description here