使用FuncAnimation将离散数量的图形转换为动画

问题描述

我正在尝试为我的算法课程启动一项新计划。

我想设计一个python代码,将顶点,边和算法名称作为输入,并在图形上将算法作为输出运行。

我已经使用networkx创建了一个图形,并且已经编写了一些算法。

该脚本按以下步骤工作:

  1. 它创建了networkx图的列表。
  2. 将图形输出为数字。

我希望将步骤2从照片更改为动画,以吸引更多关注。

问题是我发现的所有示例/教程都依赖于这样的事实,即数据是连续的(例如,绘制图形),而我的数据是离散数量的networkx图形。

def print_graph2(Graphs): #Graphs - a list of networkx graphs.
    for index,graph in enumerate(Graphs):
        plt.figure(index + 1)
        pos = nx.bipartite_layout(graph,[node for ind,node in enumerate(graph.nodes) if ind < len(graph.nodes) / 2])
        nx.draw(graph,pos)
        vertex_weight = {u: f'{u}:{w["weight"]}' for u,w in graph.nodes.data()}
        nx.draw_networkx_labels(graph,pos,labels=vertex_weight)
    plt.show()

解决方法

每次FuncAnimation调用func函数时,您需要创建一个生成器以遍历图形列表。例如:

import random

import matplotlib.pyplot as plt
import networkx as nx
import matplotlib.animation as animation
import matplotlib

# create a list of 50 random cycle graphs with nodes ranging from 10 to 100 (the list of your graphs)
graphs = [nx.cycle_graph(random.randint(10,100)) for g in range(50)]

# make a generator 
def get_a_nice_graph():
    for g in graphs:
        yield g

nice_graph = get_a_nice_graph()

# make the function to pass to FuncAnimation method
def draw_next_graph(n):
    G = next(nice_graph)  # here your call the next graph in the list
    plt.cla()
    plt.title('frame {}'.format(n))  # each graph is a new frame
    pos = nx.spring_layout(G,iterations=200)
    nx.draw(G,pos,node_color=range(len(G.nodes)),node_size=100)

ani = animation.FuncAnimation(plt.gcf(),draw_next_graph,50)
ani.save('animation.gif',writer='imagemagick')

然后您将获得以下动画: enter image description here

编辑:我忘记了在调用next()方法之前调用并分配生成器。现在已更正。