It can be very useful to create animations of plots in order to visualize how values change over time. Below is a way to create video file using matplotlib.
NOTES :
Agg
as a backend, so you can run it on a system wiht no GUI.This method uses the writer.saving
context manager, which handles cleaning up and properly closing the video filestream in the event that an error occurs in the loop.
import numpy as np import matplotlib # matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.animation as animation # Settings video_file = "myvid.mp4" clear_frames = True # Should it clear the figure between each frame? fps = 15 # Output video writer FFMpegWriter = animation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=fps, metadata=metadata) fig = plt.figure() x = np.arange(0,10,0.1) with writer.saving(fig, video_file, 100): for i in np.arange(1, 10, 0.1): y = np.sin(x+i) if clear_frames: fig.clear() ax, = plt.plot(x, y, 'r-', linestyle="solid", linewidth=1) writer.grab_frame()
Running the above code we get:
Setting the clear frames to False we get:
import numpy as np import matplotlib # matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.animation as animation # Settings video_file = "myvid.mp4" clear_frames = True # Should it clear the figure between each frame? fps = 15 # Output video writer FFMpegWriter = animation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=fps, metadata=metadata) fig = plt.figure() writer.setup(fig, outfile=video_file, dpi=None) x = np.arange(0,10,0.1) for i in np.arange(1, 10, 0.1): y = np.sin(x+i) if clear_frames: fig.clear() ax, = plt.plot(x, y, 'r-', linestyle="solid", linewidth=1) writer.grab_frame() writer.finish() # writer.cleanup()
Note you can comment without any login by: