Created
July 3, 2024 11:19
-
-
Save izikeros/61c18539c80ba8fdd83a1048cde3409f to your computer and use it in GitHub Desktop.
[Animated GIFs from Matplotlib Plots] #visualization
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
import io | |
import matplotlib.pyplot as plt | |
import numpy as np | |
from matplotlib.animation import FuncAnimation | |
from PIL import Image | |
def create_plot(i): | |
plt.clf() | |
x = np.linspace(0, 10, 1000) | |
y = np.sin((i + 1) * x) | |
plt.plot(x, y) | |
plt.title(f"Sine Wave (Frequency: {i+1})") | |
plt.xlim(0, 10) | |
plt.ylim(-1.5, 1.5) | |
# Create the animation | |
fig = plt.figure(figsize=(10, 6)) | |
# Save frames as images | |
frames = [] | |
for i in range(10): | |
create_plot(i) | |
buf = io.BytesIO() | |
plt.savefig(buf, format="png") | |
buf.seek(0) | |
frames.append(Image.open(buf)) | |
# Create and save the animated GIF | |
frames[0].save( | |
"sine_wave_animation.gif", | |
save_all=True, | |
append_images=frames[1:], | |
duration=200, | |
loop=0, | |
) | |
print("Animation saved as 'sine_wave_animation.gif'") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment