How to fix the location of nodes in networkx?

Viewed 78

How can I fix the location of nodes in networkx? Each frame the cells move because the edges added were different. I'd like to keep all the cells in the same location.

(If you run the code snippet below on https://colab.research.google.com/ the resulting mp4 file shows how the nodes are moving around. This makes its hard to track the changes over each frame.)

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import seaborn.apionly as sns
import matplotlib.animation
import random

G = nx.grid_2d_graph(9, 9, )
pos = {f"{x},{y}":(x,y) for x,y in G.nodes()}
ndxs = [f"{x},{y}" for x,y in G.nodes()]
G=nx.DiGraph(directed=True)
G.add_nodes_from(ndxs)
edges = [
    [(f"{random.randint(0, 8)},{random.randint(0, 8)}", f"{random.randint(0, 8)},{random.randint(0, 8)}") for _ in range(10)]
    for _ in range(20)
]

# Build plot
fig, ax = plt.subplots(figsize=(8,8))

def update(i):
    ax.clear()
    edgelist = edges[i]

    nx.draw(G, pos, node_color="lightgrey", ax=ax)
    nx.draw_networkx_edges(
        G, pos=pos, edgelist=edgelist, 
        arrowstyle="->", connectionstyle=f"arc3,rad=0.5", ax=ax)

    ax.set_title(f"frame {i}")
    ax.set_xticks([])
    ax.set_yticks([])

ani = matplotlib.animation.FuncAnimation(fig, update, frames=20, interval=250, repeat=True)
ani.save("tmp.mp4")
plt.show()
0 Answers
Related