I do it all the time by using individual plots created from matplotlib.
An example procedure is:
- 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')
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.
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()