数据可视化之不知如何展现变化趋势只好做动图(moviepy制作gif)

数据可视化之使用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月更新。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值