【Python】【matplotlib】动画
来源:互联网 发布:阿迪达斯淘宝旗舰店 编辑:程序博客网 时间:2024/06/14 20:48
figure.canvas.draw()
import matplotlib.pyplot as pltimport numpy as npdef update_data(line): x[:] += 0.1 plt.setp(line, 'ydata', np.sin(x)) fig.canvas.draw()fig, ax = plt.subplots()x = np.linspace(0, 10, 1000)line, = ax.plot(x, np.sin(x), lw=2)timer = fig.canvas.new_timer(interval=50)timer.add_callback(update_data, line)timer.start()plt.show()
- figure.canvas.draw()用来重新绘制整张图表,在上一篇博客中有大量应用
- setp,设定曲线的数据
- timer定时器,用法参见代码
使用缓存快速重绘
figure.canvas.draw()重绘整个图表,因此速度慢,占用资源多。
下面这段代码,只更新动态对象,而静态对象保存起来
import matplotlib.pyplot as pltimport numpy as npfig, ax = plt.subplots()x = np.linspace(0, 10, 1000)ax.plot(x,np.cos(x))line, = ax.plot(x, np.sin(x), lw=2,animated=True)#1. 要作为动画的元素,animated属性设为Truefig.canvas.draw()#2. 重绘图表,忽略animated=True的对象background=fig.canvas.copy_from_bbox(ax.bbox)#3. 保存图像信息到background中def update_data(line): x[:] += 0.1 plt.setp(line, 'ydata', np.sin(x)) fig.canvas.restore_region(background)#4. 恢复background中的信息(也就擦除了所有动态元素) ax.draw_artist(line)#5. 绘制更新后的动态对象 fig.canvas.blit(ax.bbox)#6. 绘制更新后的内容timer = fig.canvas.new_timer(interval=50)timer.add_callback(update_data, line)timer.start()plt.show()
注意代码中注释的6个步骤:
1. 要作为动画的元素,animated属性设为True
2. 重绘图表,忽略animated=True的对象
3. 保存图像信息到background中
4. 恢复background中的信息(也就擦除了所有动态元素)
5. 绘制更新后的动态对象
6. 绘制更新后的内容
animation模块
animation模块对上述过程进行了封装,使得画动画变得方便一些。
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.animation import FuncAnimationfig, ax = plt.subplots()x = np.linspace(0, 10, 200)y = np.sin(x)line, = ax.plot(x, y, lw=2, animated=True)def update_line(i): y = np.sin(x + i / 50) plt.setp(line, 'ydata', y) return [line]ani = FuncAnimation(fig, update_line, blit=True, interval=25, frames=1000)plt.show()
- blit=True表示使用缓存快速重绘
- frames参数设置最大帧数,update_line()的输入值i将在0到frames之间循环变化,frames也可以是一个list或array
- interval时间间隔
动画保存
step1:下载ffmpeg,FFmpeg for Windows,并解压缩
step2: 代码中添加一行:
plt.rcParams['animation.ffmpeg_path'] = r'C:\Users\guofei\Downloads\ffmpeg\bin\ffmpeg'
step3: 保存
ani.save('test.mp4',fps=25)
效果:
阅读全文
1 0
- 【Python】【matplotlib】动画
- Python/Matplotlib实现雨点图动画
- python matplotlib
- Python-Matplotlib
- Python matplotlib
- python-matplotlib
- python-matplotlib
- Python matplotlib
- python-matplotlib
- matplotlib里的动画
- matplotlib 绘制动画
- Matplotlib绘制动画
- matplotlib制作动画
- python 数据可视化大全(matplotlib库、坐标系、标注、柱状图、等高线、3D、动画)
- matplotlib绘制动画的示例
- matplotlib简易入门教程及动画
- matplotlib绘制动画的示例
- matplotlib模块数据可视化-动画
- CodeForces
- Python3常用内置函数
- 前端面试题
- 论文水记|How to Train Triplet Networks with 100K Identities?
- 简单计算器 hiho一下第169周
- 【Python】【matplotlib】动画
- 基础的01字串 蓝桥杯基础题
- 51nod 1072 威佐夫游戏
- 坚持#第194天~了解云计算
- Spring介绍
- mysql的间隙锁
- Debian使用的dpkg与apt-get软件管理机制详解
- No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt
- mysql 存小数用decimal