Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 508
nz_21 Avatar asked Nov 22 '18 04:11

nz_21


People also ask

How do I make X axis longer in Matplotlib?

To increase the space for X-axis labels in Matplotlib, we can use the spacing variable in subplots_adjust() method's argument.

What are the two ways to adjust axis limits of the plot using Matplotlib?

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.

How do you limit the range of values on each of the axes Matplotlib?

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.

What method yields x value limits Matplotlib?

The xlim() function in pyplot module of matplotlib library is used to get or set the x-limits of the current axes.


1 Answers

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.

like image 98
fffff Avatar answered Sep 28 '22 08:09

fffff