Reputation: 153
after working on animating my networkx network i finally succeeded to do it with matplotlib but my network changes its layout (placement of nodes and edges) and so that makes my network not understanable. it is more of a general question (how do i stop my network from changing in animations?). My animation call looks like this:
def update(it = None):
global gG
global gnodes
global fig
tick(gG,gnodes)
fig.clf()
nx.draw(gG,with_labels=True,node_color = setColorMap(gG,gnodes))
def draw():
global fig
ani = animation.FuncAnimation(fig,update,repeat=True,interval= 1)
plt.show()
gG is the graph, gNode is a dictionary of the nodes and fig is the figure Interval isn't supposed to be one, I am aware of this
Upvotes: 1
Views: 1218
Reputation: 23907
The problem is that by default networkx uses an algorithm for placing nodes that starts by placing the nodes at random and then shifting them around as if they were masses on the end of springs. This tends to get a decent arrangement, but since the starting point is random, each time it changes.
This is easily fixed using the pos
argument. pos
is a dictionary which stores an x and y coordinate for each node. You can set these by hand, or more easily, you can have networkx create them.
pos = nx.spring_layout(G) #other layouts are available.
nx.draw(G, pos=pos)
This is useful not just for animations, but when you want to have a subset of nodes plotted in one color and another subset plotted in another.
Here is some sample code for an animation I did: https://epidemicsonnetworks.readthedocs.io/en/latest/_modules/EoN/simulation_investigation.html#Simulation_Investigation.animate
and some examples of output using that code:
https://epidemicsonnetworks.readthedocs.io/en/latest/examples/Simulation_Investigation.html
Upvotes: 3