实时的Matplotlib绘图

4

你好,我在使用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秒钟左右更新一次的数据,然后绘制更新。谢谢!

抱歉,我在代码中错过了日期,所以X轴将是datetime.datetime.now(),以提供连续的线条。也许我需要添加时间延迟? - JRH31
2个回答

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()

animated graph

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

你可以通过修改interval参数来加快速度。


如果你想要随时间绘制值,一种可能的方法是使用deque()来保存y值,然后使用x轴来保存几秒前的值:

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()

给你:

moving time plot

(该内容为图片,无法直接翻译。)

嗨,马丁,谢谢!我测试了这段代码,似乎X轴也是随机的,对吧?把X轴变成时间轴有多容易呢? - JRH31
x轴在这里只是一个范围,可以是任何你想要的东西。例如:x = np.arange(0, max_x) - Martin Evans

0

你实例化了GetRandomInt,它实例化了PlotData,而PlotData又实例化了GetRandomInt,然后GetRandomInt又实例化了PlotData,如此循环。这就是你问题的根源。


我正在尝试进行一些连续的绘图,直到用户最好关闭应用程序。不确定最佳方法是什么。 - JRH31
@BlueTomato 我刚刚编辑了代码,可能更合理一些。但它仍然崩溃:S - JRH31

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接