简体   繁体   中英

Is it possible to animate a graph in networkX while removing nodes?

I have a graph consisting of about 200 nodes out of which I am removing nodes on each iteration. It is possible to visualize the graph with the nodes removed, but the location of the nodes does not change while doing so. Ideally, I'd like to take away nodes and see if the remaining nodes move closer together and if clusters form as more and more nodes are removed.

I'm using networkX for this. I have tried to recompute the graph on every iteration but there seems to be some randomness in how the graph is created. I am therefore getting a very different graph on each iteration.

Is there a way to achieve what I want?

You can use draw_networkx for this:

import networkx as nx
import matplotlib.pyplot as plt

nodes = [i for i in range(10)]
edges = [(i, i+1) for i in range(5)]
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)

positions = {}

for node in nodes:
    positions[node] = (node, node)

nx.draw_networkx(G, pos=positions)

I generate a graph of 10 nodes with some edges, and then define a dict where the keys are the nodes (1 to 10 here) and the values are the coordinates in (x,y) format. In this example I arranged the nodes along a line.
Then, at the next iteration, just remove the nodes you do not need and pass the same dict. It will skip over the missing nodes and just plot the ones still present in the graph:

G.remove_nodes_from([5,6])
nx.draw_networkx(G, pos=positions)

You should see the nodes 5 and 6 missing. .draw_networkx relies on matplotlib , so you can do many of the things allowed by that library. More info here .

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM