Created
November 23, 2020 09:55
-
-
Save sgraaf/cff19b000e0670b4427bfe35105a79e1 to your computer and use it in GitHub Desktop.
Create an animated gif using matplotlib (& PIL)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import matplotlib.pyplot as plt | |
import numpy as np | |
from matplotlib.animation import FuncAnimation, PillowWriter | |
# initialize the figure | |
fig, ax = plt.subplots() | |
fig.set_tight_layout(True) | |
ax.set_xlim(0, 2 * np.pi) | |
ax.set_ylim(-1, 1) | |
# initialize empty objects | |
x, y_sin, y_cos = [], [], [] | |
line_1, = plt.plot([], [], 'ro') | |
line_2, = plt.plot([], [], 'm*') | |
def update_func(frame: float): | |
x.append(frame) | |
y_sin.append(np.sin(frame)) | |
y_cos.append(np.cos(frame)) | |
line_1.set_data(x, y_sin) | |
line_2.set_data(x, y_cos) | |
# initialize the `FuncAnimation` object | |
anim = FuncAnimation( | |
fig=fig, | |
func=update_func, | |
frames=np.linspace(0, 2 * np.pi, 64), | |
# init_func=init_func | |
) | |
# initialize the `Writer` object using 25 frames per second | |
writer = PillowWriter(fps=25) | |
# save the animation as a gif | |
anim.save('demo_sin.gif', writer=writer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment