0

I am trying to simulate a network growth by having edges connecting to different nodes. The following code, when run, displays the entire sequence of edges and nodes simultaneously. But how do i show one edge getting added to another after a delay of n units of time (in the same graph). I understand i have to use 'animation' package but am not sure how

import networkx as nx
import matplotlib.pyplot as plt

def f1(g):

    nodes = set([a for a, b in g] + [b for a, b in g])

    G=nx.Graph()

    for node in nodes:
       G.add_node(node)

    for edge in g:
       G.add_edge(edge[0], edge[1])

    pos = nx.shell_layout(G)

    nx.draw(G, pos)

    plt.show()

g = [(10, 11),(11, 12),(12, 13), (13, 15),(15,10)]
f1(g)

I hope the intendation is correct. When the code is run, a graph does show up, but how to have each edge appearing one after the other, instead of appearing simultaneously.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Krishn Nand
  • 135
  • 1
  • 1
  • 9
  • 1
    The code you posted does not run -- could you please formulate your question as [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Thomas Kühn Jan 04 '18 at 06:30
  • I almost missed your edit -- next time it is best to answer to the comment. If you start your comment with and `@`followed by a username, that user will receive a note in his mail box. – Thomas Kühn Jan 17 '18 at 20:47

1 Answers1

2

Basically there is already an answer to this question here, but I decided to write another answer that is tailored to your specific problem. Instead of using nx.draw(), I use nx.draw_networkx_edges and draw_networkx_nodes, which return a LineCollections and a PathCollection, respectively. These can then be altered in several ways, for instance you can change the color of each line segment in a LineCollection. In the beginning I set the colors of all edges to white and then I use a matplotlib.animation.FuncAnimation to change these segment colors to black one by one at given time intervals. Once all edges are black, the animation starts over. Hope this helps.

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

g = [(10, 11),(11, 12),(12, 13), (13, 15),(15,10)]

fig = plt.figure()

G = nx.Graph()
G.add_edges_from(g)
G.add_nodes_from(G)

pos = nx.shell_layout(G)
edges = nx.draw_networkx_edges(G, pos, edge_color = 'w')
nodes = nx.draw_networkx_nodes(G, pos, node_color = 'g')

white = (1,1,1,1)
black = (0,0,0,1)

colors = [white for edge in edges.get_segments()]

def update(n):
    global colors

    try:
        idx = colors.index(white)
        colors[idx] = black
    except ValueError:
        colors = [white for edge in edges.get_segments()]

    edges.set_color(colors)
    return edges, nodes

anim = FuncAnimation(fig, update, interval=150, blit = True) 

plt.show()

The result looks like this:

result of the above code

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63