简体   繁体   中英

Matplotlib Animation: how to dynamically extend x limits?

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?

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.

There is a workaround for this even when blit=True if you send a resize event to the canvas, forcing MPL to flush the canvas. To be clear, the fact that the code in @fffff answer doesn't work with blit is a bug in the MPL codebase, but if you add fig.canvas.resize_event() after setting the new x-axis, it will work in MPL 3.1.3. Of course, you should only do this sporadically to actually get any benefit from blitting --- if you're doing it every frame, you're just performing the non-blit procedure anyway, but with extra steps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM