为了账号安全,请及时绑定邮箱和手机立即绑定

VSCode 中的 Python:绘图中的数据未更新

VSCode 中的 Python:绘图中的数据未更新

翻翻过去那场雪 2022-10-05 18:33:52
我想在循环中绘制数据以唤起新数据的“实时更新”。但是我只得到了我的情节的一次更新,并且没有其他数据被添加到情节中。我做错了什么?import numpy as npimport matplotlib.pyplot as pltimport timefig=plt.figure()ax1=fig.add_subplot(1,1,1)x=[]y=[]for n in range(20):    x.append(n)    y.append(n*2)    ax1.clear()    ax1.scatter(x,y)    #fig.canvas.draw()    plt.autoscale(enable=True, axis='both')    plt.show()    time.sleep(0.1)
查看完整描述

1 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

你必须使用FuncAnimation。这将是您的示例的实现 -


import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

import time


fig=plt.figure()

ax1=fig.add_subplot(1,1,1)


x=list(range(20))

y=[n*2 for n in x]


def animate(i):

    ax1.clear()

    ax1.scatter(x[:i],y[:i])

    plt.autoscale(enable=True, axis='both')


ani = FuncAnimation(fig, animate, interval=100)

plt.show()

更新

为了处理无法在数组中预先计算的数据,如上所示,您可以使用 FuncAnimation 的 frames 参数,如下所示 -


import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

import time


fig=plt.figure()

ax1=fig.add_subplot(1,1,1)


x=[]

y=[]


def frames():

    for i in range(20):

        yield i, i*2


def animate(args):

    ax1.clear()

    x.append(args[0])

    y.append(args[1])

    ax1.scatter(x, y)

    plt.autoscale(enable=True, axis='both')


ani = FuncAnimation(fig, animate, frames=frames, interval=100)

plt.show()


查看完整回答
反对 回复 2022-10-05
  • 1 回答
  • 0 关注
  • 245 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号