I want to plot a continuous stream of data. Here's a simplified version of what I'm doing.
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()
The code works as expected and the whole existing data is plotted while at the end of each iteration a new datapoint is added. The result is a growing plot. But I want to implement that only a certain section of the plot is shown which moves along with the generated data. E.g., in the first iteration the figure should show the section of the x-axis from 0-10, in the second iteration it should show the section of the x-axis from 1-11, and so on.
CodePudding user response:
Not sure why you thought that the linked example was not relevant. If matplotlib doesn't auto-update the x-axis, then we have to ask it politely. A simple implementation could look like this:
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()