数据可视化之使用moviepy制作gif
- 作业需求推动写此py
- 第二次使用面向对象编程
- 第二次使用pycharm
- 两次第二次感觉极好
- 往往有需求才有动力
- 废话不多说,上代码。有用的是make_gif那一段。
import os
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from moviepy.editor import VideoClip
from moviepy.video.io.bindings import mplfig_to_npimage
#plt.rcParams['savefig.dpi'] = 200
if not os.path.exists('./gifs'):
os.mkdir('./gifs')
class Gif:
def __init__(self, dir_path):
self.dir_path = dir_path
self.type = self.dir_path.split('/')[-1]
self.clf_list = [[], [], [], []]
self.tail_list = [[], [], [], []]
self.mat_list = [[], [], [], []]
self.change_list = ['Thickness of Layer 1', 'Thickness of layer 2',
'Elastic Modulus of Layer 1', 'Elastic Modulus of Layer 4']
def classify_csv(self):
clf_list = [[], [], [], []]
for fn in os.listdir(self.dir_path):
if re.findall('L2T-(.*)_z', fn)[0] == '300.0_L1E-7000.0_L4E-45.0':
clf_list[0].append(fn)
if re.findall('L1T-(.*)_L2T',fn)[0] == '150.0':
if re.findall('L1E-(.*)_z', fn)[0] == '7000.0_L4E-45.0':
clf_list[1].append(fn)
if (re.findall('L2T-(.*)_L1E', fn)[0] == '300.0') & (re.findall('L4E-(.*)_z', fn)[0] == '45.0'):
clf_list[2].append(fn)
if re.findall('L2T-(.*)_L4E',fn)[0] == '300.0_L1E-7000.0':
clf_list[3].append(fn)
self.clf_list = clf_list
def csv2mat(self):
clf_list = self.clf_list
for i in range(4):
for j in range(len(clf_list[i])):
df = pd.read_csv(self.dir_path + '/' + clf_list[i][j])
self.mat_list[i].append(np.array(df.iloc[:, 1:]))
def title_tail(self):
tail_list = [[], [], [], []]
clf_list = self.clf_list
rem = ['L1T-(.*)_L2T', 'L2T-(.*)_L1E',
'L1E-(.*)_L4E', 'L4E-(.*)_z']
for i in range(len(clf_list)):
for j in range(len(clf_list[i])):
tail_list[i].append(re.findall(rem[i], clf_list[i][j])[0])
self.tail_list = tail_list
def make_gif(self, flag):
mats = self.mat_list[flag]
fps = 2
duration = int(len(mats) / fps)
fig, ax = plt.subplots(figsize=(16, 9), dpi=100)
con1 = ax.contour([str(i * 2) for i in range(37)], [str(2 * i) for i in range(21)], mats[1], cmap='winter')
fig.colorbar(con1)
title_root = self.type + '-' + self.change_list[flag]
title_tail = self.tail_list[flag]
def make_frame(t):
ax.clear()
n = int(t / duration * len(mats))
con = ax.contourf\
([str(i * 2) for i in range(37)], [str(2 * i) for i in range(21)], np.flip(mats[n], 0), cmap='winter')
ax.clabel(con)
ax.set_title(title_root + '---' + title_tail[n])
ax.set_xlabel('X (cm)')
ax.set_ylabel('Y (cm)')
return mplfig_to_npimage(fig)
animation = VideoClip(make_frame, duration=duration)
# animation.write_videofile('try2.mp4', fps=fps)
animation.write_gif('./gifs/{}.gif'.format(title_root), fps=fps)
def render(self):
self.classify_csv()
self.csv2mat()
self.title_tail()
# print(self.tail_list)
for flag in range(4):
self.make_gif(flag)
if __name__ == '__main__':
dir_list = ['txy (kPa)', 'txz (kPa)', 'tyz (kPa)',
't1 (kPa)', 't2 (kPa)', 't3 (kPa)',
'gxy (me)', 'gxz (me)', 'gyz (me)',
'g1 (me)', 'g2 (me)', 'g3 (me)']
for d in dir_list[:]:
gif = Gif('./data/{}'.format(d))
gif.render()
- 做出来的效果是这样的:
图片2020年9月更新。