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

如何让matplotlib根据实时数据范围自动更新动画的坐标轴上下限

解决方案

你代码的核心问题出在3个地方:

  1. 开启了blit=True参数:该模式下FuncAnimation只会重绘你返回的line对象,坐标轴范围变更属于axes层级的更新,不会被渲染到画布上
  2. 每次animate函数执行时都调用ax.plot()创建新的线条对象,不是更新已有线条的数据,会导致画布上的线条越堆越多
  3. 手动设置坐标轴范围时传入了多余的auto=True参数,该参数仅在开启自动范围适配时生效,手动指定上下限的时候不需要添加

修正后可运行代码

import pandas as pd
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# 初始化数据
df = pd.DataFrame(columns = ['time', 'number'])
start_time = time.time()
df['time'] = [1]*40
df['number'] = [1]*40
counter = 0
while counter<40:
    df.iat[counter, 0] = round(((time.time()-start_time)*10))
    df.iat[counter, 1] = counter
    time.sleep(0.1)
    counter = counter+1

def get_data():
    global counter
    global start_time
    global df
    df.drop(range(10), axis = 0, inplace=True)
    df2 = pd.DataFrame(columns = ['time', 'number'])
    list1 = []
    list2 = []
    for item in range(10):
        time.sleep(0.1)
        list1.append(round(((time.time()-start_time)*10)))
        list2.append(counter)
        counter = counter + 1
    df2['time'] = list1
    df2['number'] = list2
    # 替换已废弃的append方法
    df = pd.concat([df, df2], ignore_index = True)
    df.reset_index(inplace=True, drop = True)
    x_data = df['time']
    y_data = df['number']
    return x_data,y_data

def get_limits():
    global df
    x_min = min(df['time'])
    y_min = min(df['number'])
    x_max = max(df['time'])
    y_max = max(df['number'])
    return x_min, y_min, x_max, y_max

fig, ax = plt.subplots()
# 提前初始化线条对象,后续只更新数据
line, = ax.plot([], [], color="red")

def animate(i):
    x_data, y_data= get_data()
    x_min, y_min, x_max, y_max = get_limits()
    # 更新坐标轴范围,移除多余auto参数
    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    # 更新已有线条的数据,不新建线条
    line.set_data(x_data, y_data)
    return line,

# blit设为False,保证坐标轴更新可被渲染
ani = animation.FuncAnimation(
    fig, animate, interval=50, blit=False, save_count=50)
plt.show()

关键改动说明

  • 初始化阶段提前创建line对象,后续仅更新其data属性,避免重复生成线条
  • 将FuncAnimation的blit参数改为False,保证坐标轴范围变更可以正常渲染到画布
  • 移除ax.set_xlim/ax.set_ylim中的多余参数auto=True
  • 替换了pandas中已废弃的df.append方法为pd.concat,兼容所有pandas版本
  • 如果你觉得动画卡顿,可以调整get_data函数中的sleep逻辑,FuncAnimation本身的interval参数已经可以控制动画更新间隔

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:15:06