Skip to main content
 首页 » 编程设计

python之在 matplotlib 中调整实时绘图(串行数据流)的 x 轴范围

2025年05月04日8www_RR

我一直在研究 matplotlib 示例页面上的这段代码。我试图让 x 轴保持给定的窗口。例如, Canvas 将从 x = 0 到 30、1 到 31、2 到 32 绘制。现在我的 x 继续增长。我无法定义设置的窗口大小。谁能指出我正确的方向。

根据我的试验,似乎无论 x 有什么值,y 都需要具有相同的长度。那么对于我的程序,我只想绘制一个串行数据流。我要走这条路了吗?

import time 
import matplotlib 
matplotlib.use('TkAgg') # do this before importing pylab 
import matplotlib.pyplot as plt 
import random 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
 
y = [] 
 
def animate(): 
 
    while(1): 
        data = random.random() 
        y.append(data) 
        x = range(len(y)) 
 
        line, = ax.plot(y) 
        line.set_ydata(y) 
        fig.canvas.draw() 
 
win = fig.canvas.manager.window 
fig.canvas.manager.window.after(100, animate) 
plt.show() 

请您参考如下方法:

您还可以同时更改 x 和 y 数据,然后更新绘图范围。我不知道你打算运行多长时间,但你可能应该考虑在某个时候转储不需要的 y 数据。

import matplotlib 
matplotlib.use('TkAgg') # do this before importing pylab 
import matplotlib.pyplot as plt 
import random 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
 
x = range(30) 
y = [random.random() for i in x] 
line, = ax.plot(x,y) 
 
def animate(*args): 
    n = len(y) 
    for 1: 
        data = random.random() 
        y.append(data) 
 
        n += 1 
        line.set_data(range(n-30, n), y[-30:]) 
        ax.set_xlim(n-31, n-1) 
        fig.canvas.draw() 
 
fig.canvas.manager.window.after(100, animate) 
plt.show()