[PYTHON] Make a gif animation from a serial number file with matplotlib

** What you can do by reading this article ** Matplotlib can create gif animations from serial number data files

I can now make videos with gnuplot (Create videos from serial number data with gnuplot), but I want to be able to make videos with matplotlib anyway. !!

--Environment - macOS mojave 10.14.6 - Python 3.7.5

First, let's animate the sine curve as a practice. The basic method of making a gif animation is described in detail in the next article.

Here is a reference for the basic settings. Easy animation with matplotlib (mp4, gif)

The drawing method is briefly written here and is easy to understand. Make animation with matplotlib

gif_anime.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(111)
#List to put Line2D object
ims = []

for i in range(10):
    x = np.array(range(60))
    Y  = np.sin(x/5 - i * 5)
    im = ax.plot(Y, color='blue')
    ims.append(im) #Add each frame image to ims

#Animation generation
ani = animation.ArtistAnimation(fig, ims, interval=100, blit=True, repeat_delay=1000)

#Save
ani.save("sample.gif", writer="pillow")

#display
plt.show()

You can make a gif animation like this (if it doesn't work, click it and try it in another window. When I uploaded it to Qiita, it stopped looping infinitely, but if I do it at hand, it will loop infinitely). sample.gif

Options such as ʻinterbal`` repeat_delay` are described in detail in the next article. Make graph (Matplotlib) animation with Python (ArtistAnimation)

Next, let's try ** "animate the serial number file of the calculation result" ** as used in the research presentation. It would be easy if I could draw the anime I mentioned earlier. All you have to do is change the for part of the above code to read the calculation result.

anime_gif2.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.cm as cm

fig = plt.figure()
ax = fig.add_subplot(111)
#List to put Line2D object
ims = []

#Axis settings, etc.
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlim(0.1, 10.0)
ax.set_ylim(1, 5000)

#Number of calculation result files
filenum = 10
for i in range(filenum):
    r, sd = np.loadtxt("./data%01d.dat" % (i), comments='#', unpack=True) #Read repeatedly from data00 to data09
    im = ax.plot(r, sd, "-", color='blue', linewidth=1)
    ims.append(im) #Add each frame image to ims

#Animation generation
ani = animation.ArtistAnimation(fig, ims, interval=500, blit=True, repeat_delay=100)

#Save
ani.save("anime.gif", writer="pillow")

#display
plt.show()

sample_anime3.gif

However, in this case, the list called im will be prepared before drawing. As the number of files to be read increases, and when trying to make more 3D animation, drawing becomes difficult. Therefore, I would like to draw each frame of the animation.

anime_gif3.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig = plt.figure()
ax = fig.add_subplot(111)

artists = []
im, = ax.plot([], [])

#Axis settings, etc.
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlim(0.1, 10.0)
ax.set_ylim(1, 5000)

#Number of calculation result files
filenum = 10

#Call this function repeatedly to draw
#I increases by 1 each time you call
def update_anim(i):
    r, sd = np.loadtxt("./data%01d.dat" % (i), comments='#', unpack=True) #Read repeatedly from data00 to data09
    im.set_data(r, sd)
    return im,

ani = FuncAnimation(fig, update_anim, interval=500, blit=True, frames = filenum, repeat_delay=100)

#Save
ani.save("anime.gif", writer="pillow")

#display
plt.show()

reference: Flexible animation creation using animation.FuncAnimation of matplotlib

Now you can draw beautiful animations with matplotlib.

Recommended Posts

Make a gif animation from a serial number file with matplotlib
Make a GIF animation with folder monitoring
Draw a graph with matplotlib from a csv file
Easy animation with matplotlib (mp4, gif)
Make a partially zoomed figure with matplotlib
Animation with matplotlib
Animation with matplotlib
Read line by line from a file with Python
Make a copy of a Google Drive file from Python
[python] Change the image file name to a serial number
Access the file with a relative path from the execution script.
Visualize cavity flow with matplotlib and save as gif animation
Make a fortune with Python
Make a fire with kdeplot
How to make a command to read the configuration file with pyramid
Read a file in Python with a relative path from the program
Get OCTA simulation conditions from a file and save with pandas
Create plot animation with Python + Matplotlib
A python graphing manual with Matplotlib.
Make a Santa classifier from a Santa image
Let's make a GUI with python.
Make a sound with Jupyter notebook
Build a deb file with Docker
Draw a loose graph with matplotlib
Let's make a breakout with wxPython
python / Make a dict from a list.
Make a recommender system with python
Create a 1MByte random number file
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Make a model iterator with PySide
Make a nice graph with plotly
Write a stacked histogram with matplotlib
Create a file uploader with Django
2. Make a decision tree from 0 with Python and understand it (2. Python program basics)
Extract lines that match the conditions from a text file with python
I came up with a way to make a 3D model from a photo.
[Bash] Command to write a file line by line to a serial number file [One liner (?)]
Make a decision tree from 0 with Python and understand it (4. Data structure)
Creating a simple PowerPoint file with Python
Let's make a shiritori game with Python
Make a video player with PySimpleGUI + OpenCV
[Note] Read a file from another directory
Make ASCII art GIF animation in Python
Make a rare gacha simulator with Flask
Make a Notebook Pipeline with Kedro + Papermill
Create a large text file with shellscript
Make a drawing quiz with kivy + PyTorch
Let's make a voice slowly with Python
Make a cascade classifier with google colaboratory
Let's make a simple language with PLY 1
Create a VM with a YAML file (KVM)
[Python] Let's make matplotlib compatible with Japanese
Make a logic circuit with a perceptron (multilayer perceptron)
Make a Yes No Popup with Kivy
Create a deb file from a python package
Import serial number videos together with Aviutl
Make a wash-drying timer with a Raspberry Pi
Let's make a web framework with Python! (1)
Let's make a tic-tac-toe AI with Pylearn 2