Skip to main content
 首页 » 编程设计

python之实时 Matplotlib 绘图

2024年09月07日9TianFang

嗨,我在为 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() 

这里的想法是你有一个包含 x 和 y 值的图表。其中 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() 

给你: