I have a simple animation plot like so:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 100), ylim=(0, 100))
line, = ax.plot([], [], lw=2)
x = []
y = []
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x.append(i + 1)
y.append(10)
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)
plt.show()
Now, this works okay, but I want it to expand like one of the subplots in here http://www.roboticslab.ca/matplotlib-animation/ where the x-axis dynamically extends to accommodate the incoming data points.
How do I accomplish this?
To increase the space for X-axis labels in Matplotlib, we can use the spacing variable in subplots_adjust() method's argument.
To plot the graph, use the plot() function. To set the limit of the x-axis, use the xlim() function. To set the limit of the y-axis, use the ylim() function.
Matplotlib automatically arrives at the minimum and maximum values of variables to be displayed along x, y (and z axis in case of 3D plot) axes of a plot. However, it is possible to set the limits explicitly by using set_xlim() and set_ylim() functions.
The xlim() function in pyplot module of matplotlib library is used to get or set the x-limits of the current axes.
I came across this problem (but for set_ylim) and I had some trial and error with the comment of @ImportanceOfBeingErnest and this is what I got, adapted to @nz_21 question.
def animate(i):
x.append(i + 1)
y.append(10)
ax.set_xlim(min(x), max(x)) #added ax attribute here
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=500, interval=20)
Actually in the web quoted by @nz_21 there is a similar solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With