You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python基于DataFrame逐行生成折线图动画并导出为GIF

实现DataFrame折线图动画并导出为GIF

需求说明

基于给定的DataFrame数据制作折线图动画:

  • 逐行展示每行数据对应的折线图,切换间隔极短
  • 所有行展示完成后停留在最后一行的图表
  • 将动画导出为GIF文件

解决方案

1. 安装依赖

需要额外安装matplotlib(绘图)和imageio(保存GIF):

pip install matplotlib imageio

2. 完整代码实现

替换原有代码中# Create animated line graph as described in my question之后的内容,使用以下完整代码:

# Import additional dependencies
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import imageio
import numpy as np

# 准备绘图数据:提取月份列作为x轴,所有数值列作为y轴数据源
x_labels = df.columns[1:]  # ['Month 1', 'Month 2', ..., 'Month 6']
y_data = df.iloc[:, 1:].values  # 提取所有数值行数据

# 创建画布和轴对象
fig, ax = plt.subplots(figsize=(8, 5))

# 设置轴标签和固定y轴范围(避免图表跳变过大)
ax.set_xlabel('月份')
ax.set_ylabel('数值')
ax.set_xticks(range(len(x_labels)))
ax.set_xticklabels(x_labels)
y_min = df.iloc[:,1:].min().min() - 0.2
y_max = df.iloc[:,1:].max().max() + 0.2
ax.set_ylim(y_min, y_max)

# 更新函数:绘制当前行的折线
def update(frame):
    ax.clear()  # 清除上一帧内容
    ax.set_xlabel('月份')
    ax.set_ylabel('数值')
    ax.set_xticks(range(len(x_labels)))
    ax.set_xticklabels(x_labels)
    ax.set_ylim(y_min, y_max)
    
    # 获取当前行的数值和日期
    current_y = y_data[frame]
    current_date = df['date'].iloc[frame].strftime('%Y-%m-%d')
    
    # 绘制折线
    ax.plot(x_labels, current_y, marker='o', color='b')
    ax.set_title(f'数据日期:{current_date}')
    return ax,

# 创建动画:interval为帧间隔(毫秒,越小切换越快),repeat=False表示播放一次后停止
ani = FuncAnimation(fig, update, frames=len(df), interval=150, repeat=False)

# 保存为GIF文件
frames = []
for i in range(len(df)):
    update(i)
    fig.canvas.draw()
    image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
    image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    frames.append(image)
# 额外添加几次最后一帧,延长停留时间(可选)
for _ in range(5):
    frames.append(frames[-1])
imageio.mimsave('line_animation.gif', frames, duration=0.15)

# 显示动画(运行时会弹出窗口,可选)
plt.show()

代码说明

  • 数据准备:提取DataFrame中的月份列作为x轴标签,数值列作为绘图数据源
  • 绘图配置:固定y轴范围,避免切换帧时图表上下跳变,提升视觉连贯性
  • 更新逻辑:每次接收帧索引,清除上一帧内容后绘制当前行的折线,并显示对应日期的标题
  • 动画参数:interval=150表示每150毫秒切换一帧(可根据需求调整),repeat=False确保动画播放完所有行后停止在最后一帧
  • GIF导出:通过收集每一帧的图像数据,使用imageio.mimsave生成GIF,最后额外添加几次最后一帧,延长停留时间(可选)

内容的提问来源于stack exchange,提问作者BGG16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:55:02