问题描述
我想知道是否有一种方法可以为涉及图形的算法创建漂亮的可视化(在 Python 中).
I am wondering if there is a way to create a beautiful visualisation (in Python) of something like algorithm which involves graphs.
如果有一种方法可以在 Python 中做到这一点,这将有助于将算法代码的每个执行的逻辑步骤转换为简洁的实时插图,那就太好了.
It would be really nice if there is a way to do that in Python which would help converting each executed logical step of the algorithm's code into a neat live illustration.
在维基百科上阅读 TSP 时,我发现了这一点:
While reading about TSP on Wikipedia I found this:
推荐答案
我一直通过使用从matplotlib创建的各个图来做到这一点.
I do it all the time by using individual plots created from matplotlib.
一个示例过程是:
- 创建多个绘图并将它们保存为图像文件
- 遍历每个保存的图像文件并使用
opencv
读取它们 - 使用
opencv
将所有图像文件编译成单个视频文件.
- create multiple plots and save them as image files
- loop over each saved image file and read them using
opencv
- use
opencv
to compile all image files into a single video file.
这是一些简化的示例代码
Here is some simplified example code
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).Youtube 上的这个视频正是使用这种方法制作的.
In the create_video
function, I added options to reverse the frame order and set frames per second (fps).This video on Youtube was created using exactly this method.
要应用于示例代码,请尝试将所有绘图函数放入 for
循环中.这将产生您在边缘上迭代的每个tome的图.然后每次生成绘图时,您都可以将该绘图保存到文件中.像这样:
To apply to your sample code, try putting all your plotting functions inside your for
loop. This should produce plots each tome you iterate over an edge. Then each time a plot is generated, you can save that plot to file. Something like this:
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()
这篇关于算法的动画可视化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!