绘制一段定义长度的数据流
Plotting a section of defined length of a data stream
我想绘制连续的数据流。这是我正在做的事情的简化版本。
x_values = []
y_values = []
index = count()
def animate(i):
x_values.append(next(index))
y_values.append(random.randint(0, 5))
plt.cla()
plt.plot(x_values, y_values)
ani = FuncAnimation(plt.gcf(), animate, 1000)
plt.tight_layout()
plt.show()
代码按预期工作,绘制了整个现有数据,同时在每次迭代结束时添加了一个新数据点。结果是一个不断增长的阴谋。但我想实现的是,只显示与生成的数据一起移动的情节的特定部分。例如,在第一次迭代中,图形应显示 x 轴从 0-10 的部分,在第二次迭代中,它应显示 x 轴从 1-11 的部分,依此类推。
不确定您为什么认为链接示例不相关。如果 matplotlib 没有 auto-update x-axis,那么我们必须礼貌地询问它。一个简单的实现可能如下所示:
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import numpy as np
rng = np.random.default_rng()
fig, ax = plt.subplots()
#intialize x and y arrays with number of display points
points = 100
x = np.linspace(0, 1, points)
x_offset = x[1]
y = np.zeros(points)
l, = ax.plot(x, y)
ax.set_ylim(-2, 2)
def update(i):
#set random new y-value within display range
while True:
y_new = y[-1] + 0.2 * rng.random() - 0.1
if -2 < y_new < 2:
y[:] = np.roll(y, -1)
y[-1] = y_new
break
#shift x-values
x_new = x[-1] + x_offset
x[:] = np.roll(x, -1)
x[-1] = x_new
#update line with new values
l.set_ydata(y)
l.set_xdata(x)
#and update x axis
ax.set_xlim(x[0], x[-1])
return l,
ani = anim.FuncAnimation(fig, update, frames=100 , interval=50, repeat=True)
plt.show()
我想绘制连续的数据流。这是我正在做的事情的简化版本。
x_values = []
y_values = []
index = count()
def animate(i):
x_values.append(next(index))
y_values.append(random.randint(0, 5))
plt.cla()
plt.plot(x_values, y_values)
ani = FuncAnimation(plt.gcf(), animate, 1000)
plt.tight_layout()
plt.show()
代码按预期工作,绘制了整个现有数据,同时在每次迭代结束时添加了一个新数据点。结果是一个不断增长的阴谋。但我想实现的是,只显示与生成的数据一起移动的情节的特定部分。例如,在第一次迭代中,图形应显示 x 轴从 0-10 的部分,在第二次迭代中,它应显示 x 轴从 1-11 的部分,依此类推。
不确定您为什么认为链接示例不相关。如果 matplotlib 没有 auto-update x-axis,那么我们必须礼貌地询问它。一个简单的实现可能如下所示:
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import numpy as np
rng = np.random.default_rng()
fig, ax = plt.subplots()
#intialize x and y arrays with number of display points
points = 100
x = np.linspace(0, 1, points)
x_offset = x[1]
y = np.zeros(points)
l, = ax.plot(x, y)
ax.set_ylim(-2, 2)
def update(i):
#set random new y-value within display range
while True:
y_new = y[-1] + 0.2 * rng.random() - 0.1
if -2 < y_new < 2:
y[:] = np.roll(y, -1)
y[-1] = y_new
break
#shift x-values
x_new = x[-1] + x_offset
x[:] = np.roll(x, -1)
x[-1] = x_new
#update line with new values
l.set_ydata(y)
l.set_xdata(x)
#and update x axis
ax.set_xlim(x[0], x[-1])
return l,
ani = anim.FuncAnimation(fig, update, frames=100 , interval=50, repeat=True)
plt.show()