python动画 基于csv导出数据实现动态绘图 Animation

先看效果再看代码吧~
主要难点在于动画与区域绘制

效果

在这里插入图片描述

步骤

  1. 从csv读取数据
  2. 绘图(两种:曲线与区域)
  3. 动画
  4. 保存与显示

代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
import pandas as pd
from scipy import signal


joint = 4
err = 0.17
cutoff = 1.2
metric = "bottle.csv"
length = 360

# read csv
df = pd.read_csv(metric, delimiter=',', header=0, sep='\s+', usecols=['field.effort'+str(joint-1)])
y = df['field.effort'+str(joint-1)]
interv = 25.12 # 46hz -> 21.7


# filter
fs = 1000.0/interv
def butter_lowpass_filter(data, order=3):
		
	wn = 2.0 * cutoff / fs
	b, a = signal.butter(order, wn, 'lowpass', analog = False)
	output = signal.filtfilt(b, a, data, axis=0)

	return output

y_filter = butter_lowpass_filter(y)


plt.style.use('bmh')
fig, ax = plt.subplots(figsize=(5, 2.5))
xdata, ydata, yf_data = [], [], []
ymin, ymax = [], []
ln, = plt.plot([], [], label='joint'+str(joint))
ln_fill = plt.fill_between([], [], [], alpha=0.3, label='threshold')
# ln_filter, = plt.plot([], [], label='filter')
ax.set(xlabel='Time (s)', ylabel='Torque (Nm)')

def init():
    ax.set_xlim(0, (length*interv)/1000)		
    ax.set_ylim(0.2, 0.8)
    return ln,

def update(frame):

    xdata.append((frame*interv)/1000)
    ydata.append(y[frame])
    ln.set_data(xdata, ydata)

    # filter
    # yf_data.append(y_filter[frame])
    # ln_filter.set_data(xdata, yf_data)

    # threshold
    ymin.append(y_filter[frame]-err)
    ymax.append(y_filter[frame]+err)

    dummy_ln = plt.fill_between(xdata, ymin, ymax, alpha=0.3)
    verts = [ path._vertices for path in dummy_ln.get_paths() ]
    codes = [ path._codes for path in dummy_ln.get_paths() ]
    dummy_ln.remove()
    ln_fill.set_verts_and_codes(verts, codes)
    
    return ln, ln_fill,  #返回tuple

ani = FuncAnimation(fig, update, frames=np.arange(0, length), interval=interv,
                    init_func=init, blit=True, repeat=False)
plt.legend(loc='lower left')
plt.subplots_adjust(left=0.12, right=0.96, top=0.93, bottom=0.2)



##### GIF #####
ani.save('bottle.gif', fps=50, writer='pillow')
##### MP4 #####
# ani.save('bottle-range.mp4',
# 		fps=50, dpi=500, writer='ffmpeg')


plt.show()

安装ffmpeg win10教程

保存mp4格式视频需要安装ffmpeg
详细安装教程:
https://blog.csdn.net/qq_43803367/article/details/110308401#commentBox
下载地址:
https://www.gyan.dev/ffmpeg/builds/

Ref

  • 解决错误fillbetween动画绘图错误
TypeError: 'PolyCollection' object is not iterable

https://stackoverflow.com/questions/33828260/how-to-update-artists-in-scrollable-matplotlib-and-multiplot

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值