繁体   English   中英

实时Matplotlib绘图

[英]Real-Time Matplotlib Plotting

嗨,我在实时绘制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秒左右更新一次的数据,然后绘制更新。 谢谢!

要绘制连续的随机线图集,您需要在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()

动画图

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

您可以通过修改interval参数来尽可能快地提高速度。


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

from collections import deque
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.ticker import FuncFormatter

def init():
    line.set_ydata([np.nan] * len(x))
    return line,

def animate(i):
    # Add next value
    data.append(np.random.randint(0, max_rand))
    line.set_ydata(data)
    plt.savefig('e:\\python temp\\fig_{:02}'.format(i))
    print(i)
    return line,

max_x = 10
max_rand = 5

data = deque(np.zeros(max_x), maxlen=max_x)  # hold the last 10 values
x = np.arange(0, max_x)

fig, ax = plt.subplots()
ax.set_ylim(0, max_rand)
ax.set_xlim(0, max_x-1)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: '{:.0f}s'.format(max_x - x - 1)))
plt.xlabel('Seconds ago')

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

plt.show()

给你:

移动时间图

您实例化GetRandomInt,实例化PlotData,实例化GetRandomInt,实例化PlotData,...等等。这就是问题的根源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM