如何基于股票数据实现Pandas直方图的Matplotlib动画?
问题原因&修复方案
核心错误点
- 数据列名匹配错误:通过
pandas_datareader从Yahoo接口拉取的股票数据列名为Open/High/Low/Close/Adj Close/Volume,不存在和股票代码同名的ALB列,指定column=stock会找不到目标数据,自然无法渲染直方图。 - pandas hist的轴绑定错误:
df.hist()默认会自动创建新的画布和轴对象,不会复用你提前定义的fig关联的轴,导致动画绑定的画布一直是空的。 - FuncAnimation参数使用错误:你要迭代的帧序列
[1,30,60,90,120]应该传给frames参数,fargs是用来传递除了帧参数之外的额外固定参数的,参数传错导致更新函数接收不到正确的步长值。 - 动画对象未持有引用:创建的
FuncAnimation对象没有赋值给变量,会被Python的垃圾回收机制自动清理,动画无法正常运行。 - 切片写法不规范:
df[:][step:step+30]的写法存在歧义,应该用df.iloc[step:step+30]明确按行索引切片,避免后续索引逻辑出错。
修复后的可运行代码
import pandas_datareader as web import pandas as pd import matplotlib.pyplot as plt import matplotlib.animation as animation # 提前定义好共用的轴,让pandas hist直接用这个轴渲染 fig, ax = plt.subplots() stock = 'ALB' # 指定要统计直方图的字段,比如收盘价Close target_col = "Close" df = web.DataReader(stock, 'yahoo', "2021-01-01", "2021-11-14") def update_hist(step): ax.cla() # 明确按行切片取30天数据 df_step = df.iloc[step:step+30] # 指定用提前创建的ax渲染直方图,不要自动创建新轴 df_step.hist(column=target_col, ax=ax) # 加标题方便看时间段 ax.set_title(f"{stock} {target_col} 直方图 第{step}天起30天周期") # 帧序列传给frames,动画对象赋值给变量ani防止被回收 ani = animation.FuncAnimation(fig, update_hist, frames=[1, 30, 60, 90, 120], interval=1000) plt.show()
内容的提问来源于stack exchange,提问作者Martin Kunze
相关产品推荐
相关产品推荐

