Yadeses
Yadeses

Reputation: 195

Networkx animation, graph not changing

I have the following code: https://pastebin.com/L4KfLhMc

The most important part from this:

def animate(i):
    ax.clear()
    plt.axis('off')
    edges = G.edges()
    edge1, edge2 = random.sample(edges, 2)
    while set(edge1) & set(edge2):
        edge1, edge2 = random.sample(edges, 2)

    new_edge1 = (edge1[0], edge2[1])

    new_edge2 = (edge1[1], edge2[0])

    if not(new_edge1 in edges or new_edge2 in edges):

        G.remove_edge(*edge1)
        G.remove_edge(*edge2)
        G.add_edge(new_edge1[0], new_edge2[0])
        G.add_edge(new_edge1[1], new_edge2[1])

    #print(G.edges())
    edges = nx.draw_networkx_edges(G, pos, ax=ax)
    nodes = nx.draw_networkx_nodes(G, pos, node_color="#87CEEB", node_size=50, ax=ax)
    return edges, nodes

The starting graph is a Watts-Strogatz Graph where none of the connections are reconnected.

In this code I try to use the matplotlib FuncAnimation to make a graph that changes over time. This is happening in the animate function. So I have checked the following: the edges are redrawn every time since ax.clear() cleans the plot. Then G also is changed overtime. But whenever I draw the Graph of G it looks the same as the starting graph even though edges have been changed.

Upvotes: 0

Views: 210

Answers (1)

Reti43
Reti43

Reputation: 9796

The animation doesn't change because you add and remove the same nodes. Pay close attention:

new_edge1 = (edge1[0], edge2[1])
new_edge2 = (edge1[1], edge2[0])

if not(new_edge1 in edges or new_edge2 in edges):
    G.remove_edge(*edge1)
    G.remove_edge(*edge2)
    G.add_edge(new_edge1[0], new_edge2[0])  # equal to (edge1[0], edge1[1])
    G.add_edge(new_edge1[1], new_edge2[1])  # equal to (edge2[1], edge2[0])

I guess you meant to do

G.add_edge(*new_edge1)
G.add_edge(*new_edge2)

with which the animation changes.

Upvotes: 1

Related Questions