python - 算法的动画可视化

标签 python matplotlib networkx

我想知道是否有一种方法可以(用Python)创建一个漂亮的可视化效果,比如涉及图形的算法。

如果有一种方法可以在 Python 中实现这一点,帮助将算法代码的每个执行逻辑步骤转换为简洁的实时插图,那就太好了。

在维基百科上阅读有关 TSP 的内容时,我发现了这一点:

enter image description here

最佳答案

我一直使用 matplotlib 创建的单独绘图来完成此操作。

示例过程是:

  1. 创建多个绘图并将它们另存为图像文件
  2. 循环每个保存的图像文件并使用opencv读取它们
  3. 使用opencv将所有图像文件编译为单个视频文件。

这是一些简化的示例代码

import cv2
import os
import matplotlib.pyplot as plt

# create a single plot
plt.plot([1,2,3], [3, 7, 11])
# save plot as an image
plt.savefig(plot_directory\plot_name.jpg, format='jpg', dpi=250)
plt.show()


def create_video(image_folder, video_name, fps=8, reverse=False):
    """Create video out of images saved in a folder."""
    images = [img for img in os.listdir(image_folder) if img.endswith('.jpg')]
    if reverse: images = images[::-1]
    frame = cv2.imread(os.path.join(image_folder, images[0]))
    height, width, layers = frame.shape
    video = cv2.VideoWriter(video_name, -1, fps, (width,height))
    for image in images:
        video.write(cv2.imread(os.path.join(image_folder, image)))
    cv2.destroyAllWindows()
    video.release()

# use opencv to read all images in a directory and compile them into a video
create_video('plot_directory', 'my_video_name.avi')

create_video 函数中,我添加了用于反转帧顺序并设置每秒帧数 (fps) 的选项。 This video on Youtube正是使用这种方法创建的。

要应用于示例代码,请尝试将所有绘图函数放入 for 循环中。这应该会生成您在边缘上迭代的每个书籍的图。然后,每次生成绘图时,您都可以将该绘图保存到文件中。像这样的事情:

import random
from itertools import combinations
from math import sqrt
import itertools
from _collections import OrderedDict
import networkx as nx
import numpy as np
from matplotlib import pyplot as plt

random.seed(42)
n_points = 10


def dist(p1, p2):
    return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)


points = [(random.random(), random.random()) for _ in range(n_points)]
named_points = {i: j for i, j in zip(itertools.count(), points)}

weighted_edges = dict()
tree_id = [None] * n_points
min_tree = []

for v1, v2 in combinations(named_points.values(), 2):
    d = dist(v1, v2)
    weighted_edges.update({d: ((list(named_points.keys())[list(named_points.values()).index(v1)]),
                               (list(named_points.keys())[list(named_points.values()).index(v2)]))
                           }
                          )

for i in range(n_points):
    tree_id[i] = i

sorted_edges = OrderedDict(sorted(weighted_edges.items(), key=lambda t: t[0]))
list_edges = sorted_edges.values()


for edge in list_edges:
    if tree_id[edge[0]] != tree_id[edge[1]]:
        min_tree.append(edge)

        old_id = tree_id[edge[0]]
        new_id = tree_id[edge[1]]

        for j in range(n_points):
            if tree_id[j] == old_id:
                tree_id[j] = new_id

        print(min_tree)


        G = nx.Graph()
        G.add_nodes_from(range(n_points))
        G.add_edges_from(list_edges)

        green_edges = min_tree



        G = nx.Graph()
        G.add_nodes_from(range(n_points))
        G.add_edges_from(list_edges)
        edge_colors = ['black' if not edge in green_edges else 'red' for edge in G.edges()]
        pos = nx.spiral_layout(G)

        G2 = nx.Graph()
        G2.add_nodes_from(range(n_points))
        G2.add_edges_from(min_tree)
        pos2 = nx.spiral_layout(G2)


        plt.figure(1)
        nx.draw(G, pos, node_size=700, edge_color=edge_colors, edge_cmap=plt.cm.Reds, with_labels = True)

        plt.figure(2)
        nx.draw(G2, pos2, node_size=700, edge_color='green', edge_cmap=plt.cm.Reds, with_labels = True)

        plt.show()

关于python - 算法的动画可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60958425/

相关文章:

python - 查找networkx中每对节点之间的边

python - Pandas 将数据帧的行转换为对角线数据帧

python - Python线程自调用线程意外行为

python - 属性错误 : HelloWorld Instance has no attribute main

python - 如何用pylab画一颗心

python - 哪些版本的 NumPy 与 Python 3.3 兼容?

python - 仅在点图中的 x 轴上显示整数

python - 如何向现有图表添加属性

python - 网络x : How to create graph edges from a csv file?

python - 在 python 中运行时将数据从 GUI 传递到线程