Using NetworkX with matplotlib.ArtistAnimation

后端 未结 1 549
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 17:26

What I want to do is create an animation in which the nodes of a graph change color with time. When I search for information on animation in matplotlib, I usually see exampl

相关标签:
1条回答
  • 2020-12-01 17:59
    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, hence why your method didn't work. The easiest way to do this is to draw the nodes and edges using nx.draw_networkx_nodes and nx.draw_networkx_edges which return PatchCollection and LineCollection objects. You can then update the color of the nodes using set_array.

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

    best animation tutorial I have seen: http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

    0 讨论(0)
提交回复
热议问题