
Python使用matplotlib绘制动画的方法
本文实例讲述了Python使用matplotlib绘制动画的方法。分享给大家供大家参考。具体分析如下:
matplotlib从1.1.0版本以后就开始支持绘制动画
下面是几个的示例:
第一个例子使用generator,每隔两秒,就运行函数data_gen:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
axes1 = fig.add_subplot(111)
line, = axes1.plot(np.random.rand(10))
#因为update的参数是调用函数data_gen,
#所以第一个默认参数不能是framenum
def update(data):
line.set_ydata(data)
return line,
# 每次生成10个随机数据
def data_gen():
while True:
yield np.random.rand(10)
ani = animation.FuncAnimation(fig, update, data_gen, interval=2*1000)
plt.show()
第二个例子使用list(metric),每次从metric中取一行数据作为参数送入update中:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
start = [1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0]
metric =[[0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65],
[0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55],
[0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52]
]
fig = plt.figure()
window = fig.add_subplot(111)
line, = window.plot(start)
#如果是参数是list,则默认每次取list中的一个元素,
#即metric[0],metric[1],...
def update(data):
line.set_ydata(data)
return line,
ani = animation.FuncAnimation(fig, update, metric, interval=2*1000)
plt.show()
第三个例子:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
# note: i is framenumber
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
第四个例子:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 每次产生一个新的坐标点
def data_gen():
t = data_gen.t
cnt = 0
while cnt < 1000:
cnt+=1
t += 0.05
yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)
data_gen.t = 0
# 绘图
fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.set_ylim(-1.1, 1.1)
ax.set_xlim(0, 5)
ax.grid()
xdata, ydata = [], []
# 因为run的参数是调用函数data_gen,
# 所以第一个参数可以不是framenum:设置line的数据,返回line
def run(data):
# update the data
t,y = data
xdata.append(t)
ydata.append(y)
xmin, xmax = ax.get_xlim()
if t >= xmax:
ax.set_xlim(xmin, 2*xmax)
ax.figure.canvas.draw()
line.set_data(xdata, ydata)
return line,
# 每隔10秒调用函数run,run的参数为函数data_gen,
# 表示图形只更新需要绘制的元素
ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10,
repeat=False)
plt.show()
再看下面的例子:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#第一个参数必须为framenum
def update_line(num, data, line):
line.set_data(data[...,:num])
return line,
fig1 = plt.figure()
data = np.random.rand(2, 15)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
#framenum从1增加大25后,返回再次从1增加到25,再返回...
line_ani = animation.FuncAnimation(fig1, update_line, 25,fargs=(data, l),interval=50, blit=True)
#等同于
#line_ani = animation.FuncAnimation(fig1, update_line, frames=25,fargs=(data, l),
# interval=50, blit=True)
#忽略frames参数,framenum会从1一直增加下去知道无穷
#由于frame达到25以后,数据不再改变,所以你会发现到达25以后图形不再变化了
#line_ani = animation.FuncAnimation(fig1, update_line, fargs=(data, l),
# interval=50, blit=True)
plt.show()
希望本文所述对大家的python程序设计有所帮助。
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
解析 loss.backward ():深度学习中梯度汇总与同步的自动触发核心 在深度学习模型训练流程中,loss.backward()是连接 “前向计算 ...
2025-09-02要解答 “画 K-S 图时横轴是等距还是等频” 的问题,需先明确 K-S 图的核心用途(检验样本分布与理论分布的一致性),再结合横轴 ...
2025-09-02CDA 数据分析师:助力企业破解数据需求与数据分析需求难题 在数字化浪潮席卷全球的当下,数据已成为企业核心战略资产。无论是市 ...
2025-09-02Power BI 度量值实战:基于每月收入与税金占比计算累计税金分摊金额 在企业财务分析中,税金分摊是成本核算与利润统计的核心环节 ...
2025-09-01巧用 ALTER TABLE rent ADD INDEX:租房系统数据库性能优化实践 在租房管理系统中,rent表是核心业务表之一,通常存储租赁订单信 ...
2025-09-01CDA 数据分析师:企业数字化转型的核心引擎 —— 从能力落地到价值跃迁 当数字化转型从 “选择题” 变为企业生存的 “必答题”, ...
2025-09-01数据清洗工具全景指南:从入门到进阶的实操路径 在数据驱动决策的链条中,“数据清洗” 是决定后续分析与建模有效性的 “第一道 ...
2025-08-29机器学习中的参数优化:以预测结果为核心的闭环调优路径 在机器学习模型落地中,“参数” 是连接 “数据” 与 “预测结果” 的关 ...
2025-08-29CDA 数据分析与量化策略分析流程:协同落地数据驱动价值 在数据驱动决策的实践中,“流程” 是确保价值落地的核心骨架 ——CDA ...
2025-08-29CDA含金量分析 在数字经济与人工智能深度融合的时代,数据驱动决策已成为企业核心竞争力的关键要素。CDA(Certified Data Analys ...
2025-08-28CDA认证:数据时代的职业通行证 当海通证券的交易大厅里闪烁的屏幕实时跳动着市场数据,当苏州银行的数字金融部连夜部署新的风控 ...
2025-08-28PCU:游戏运营的 “实时晴雨表”—— 从数据监控到运营决策的落地指南 在游戏行业,DAU(日活跃用户)、MAU(月活跃用户)是衡量 ...
2025-08-28Excel 聚类分析:零代码实现数据分群,赋能中小团队业务决策 在数字化转型中,“数据分群” 是企业理解用户、优化运营的核心手段 ...
2025-08-28CDA 数据分析师:数字化时代数据思维的践行者与价值推动者 当数字经济成为全球经济增长的核心引擎,数据已从 “辅助性信息” 跃 ...
2025-08-28ALTER TABLE ADD 多个 INDEX:数据库批量索引优化的高效实践 在数据库运维与性能优化中,索引是提升查询效率的核心手段。当业务 ...
2025-08-27Power BI 去重函数:数据清洗与精准分析的核心工具 在企业数据分析流程中,数据质量直接决定分析结果的可靠性。Power BI 作为主 ...
2025-08-27CDA 数据分析师:数据探索与统计分析的实践与价值 在数字化浪潮席卷各行业的当下,数据已成为企业核心资产,而 CDA(Certif ...
2025-08-27t 检验与 Wilcoxon 检验:数据差异比较的两大统计利器 在数据分析中,“比较差异” 是核心需求之一 —— 如新药疗效是否优于旧药 ...
2025-08-26季节性分解外推法:解锁时间序列预测的规律密码 在商业决策、资源调度、政策制定等领域,准确的预测是规避风险、提升效率的关键 ...
2025-08-26CDA 数据分析师:数据治理驱动下的企业数据价值守护者 在数字经济时代,数据已成为企业核心战略资产,其价值的释放离不开高 ...
2025-08-26