实时Matplotlib打印

2024-10-01 11:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我对matplotlib的实时绘图有一些问题。X轴和Y轴上的随机数。随机数是一个静态数,然后乘以一个随机数

import matplotlib.pyplot as plt
import datetime
import numpy as np
import time

def GetRandomInt(Data):
   timerCount=0
   x=[]
   y=[]
   while timerCount < 5000:
       NewNumber = Data * np.random.randomint(5)
       x.append(datetime.datetime.now())
       y.append(NewNumber)
       plt.plot(x,y)
       plt.show()
       time.sleep(10)

a = 10
GetRandomInt(a)

这似乎使python崩溃,因为它无法处理更新-我可以添加一个延迟,但想知道代码是否在做正确的事情?我已经清理了代码来做和我的代码相同的功能,所以我们的想法是我们有一些静态数据,然后我们想每隔5秒更新一些数据,然后绘制更新图。谢谢!在


Tags: 代码import绘图datadatetimetimematplotlibas
2条回答

要绘制一组连续的随机线图,需要在matplotlib中使用动画:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

max_x = 5
max_rand = 10

x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))

def init():  # give a clean slate to start
    line.set_ydata([np.nan] * len(x))
    return line,

def animate(i):  # update the y values (every 1000ms)
    line.set_ydata(np.random.randint(0, max_rand, max_x))
    return line,

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=1000, blit=True, save_count=10)

plt.show()

animated graph

这里的想法是您有一个包含x和{}值的图。其中x只是一个范围,例如0到5。然后调用animation.FuncAnimation(),它告诉matplotlib每隔1000ms调用你的animate()函数,让你提供新的y值。在

您可以通过修改interval参数来任意加快速度。在


一种可能的方法,如果您想绘制随时间变化的值,可以使用deque()来保存y值,然后使用x轴来保存seconds ago

^{pr2}$

给你:

moving time plot

您可以实例化GetRandomInt,它实例化PlotData,后者实例化GetRandomInt,后者实例化PlotData,后者。。。等等,这就是你问题的根源。在

相关问题 更多 >