Using NetworkX with matplotlib.ArtistAnimation

I want to create an animation in which the nodes of the graph change color over time. When I look for animation information in matplotlib, I usually see examples that look something like this:

#!/usr/bin/python import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation fig = plt.figure(figsize=(8,8)) images = [] for i in range(10): data = np.random.random(100).reshape(10,10) imgplot = plt.imshow(data) images.append([imgplot]) anim = ArtistAnimation(fig, images, interval=50, blit=True) anim.save('this-one-works.mp4') plt.show() 

So, I thought I could just do something like this:

 #!/usr/bin/python import numpy as np import networkx as nx import matplotlib import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation G = nx.Graph() G.add_edges_from([(0,1),(1,2),(2,0)]) fig = plt.figure(figsize=(8,8)) pos=nx.graphviz_layout(G) images = [] for i in range(10): nc = np.random.random(3) imgplot = nx.draw(G,pos,with_labels=False,node_color=nc) # this doesn't work images.append([imgplot]) anim = ArtistAnimation(fig, images, interval=50, blit=True) anim.save('not-this-one.mp4') plt.show() 

I'm stuck with how, after drawing a graph with nx.draw (), I can get an object of the appropriate type to be placed in the array passed to ArtistAnimation. In the first example, plt.imshow () returns an object of type matplot.image.AxesImage, but nx.draw () actually returns nothing. Is there a way that I can access a suitable image object?

Of course, very different approaches are welcome (there always seem to be many different ways to do the same in matplotlib), as long as I can save my animation as mp4 when done.

Thanks!

- Craig

+4
source share
1 answer
 import numpy as np import networkx as nx import matplotlib import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation G = nx.Graph() G.add_edges_from([(0,1),(1,2),(2,0)]) fig = plt.figure(figsize=(8,8)) pos=nx.graphviz_layout(G) nc = np.random.random(3) nodes = nx.draw_networkx_nodes(G,pos,node_color=nc) edges = nx.draw_networkx_edges(G,pos) def update(n): nc = np.random.random(3) nodes.set_array(nc) return nodes, anim = FuncAnimation(fig, update, interval=50, blit=True) 

nx.draw does not return anything, therefore why your method does not work. The easiest way to do this is to draw nodes and edges using nx.draw_networkx_nodes and nx.draw_networkx_edges , which return PatchCollection and LineCollection . Then you can update the color of the nodes using set_array .

Using the same overall frame work, you can also move nodes (via set_offsets for PatchCollection and set_verts or set_segments for LineCollection )

best animated lesson I've seen: http://jakevdp.imtqy.com/blog/2012/08/18/matplotlib-animation-tutorial/

+6
source

Source: https://habr.com/ru/post/1496998/


All Articles