先看效果再看代码吧~
主要难点在于动画与区域绘制
效果
步骤
- 从csv读取数据
- 绘图(两种:曲线与区域)
- 动画
- 保存与显示
代码
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
- Matplotlib 画动态图: animation模块的使用
https://blog.csdn.net/u013180339/article/details/77002254