3

I am wanting to use matplotlib.annimation to sequentially plot data points and plot vertical lines as they become known.

What I have at the moment is the following:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = np.arange(len(data))
y = data


fig = plt.figure()
plt.xlim(0, len(data))
plt.ylim(-8, 8)
graph, = plt.plot([], [], 'o')

def animate(i):
    # line_indicies = func(x[:i+1])
    graph.set_data(x[:i+1], y[:i+1])
    # then I would like something like axvline to plot a vertical line at the indices in line indices 

    return graph

anim = FuncAnimation(fig, animate, frames=100, interval=200)
# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()

I would like to plot vertical lines outputted from a function as described in the comments in the animate function.

The lines are subject to change as more data points are processed.

math111
  • 127
  • 5

1 Answers1

3

I wrote the code with the understanding that I wanted to draw a vertical line along the index of the line graph. I decided on the length and color of the vertical line, and wrote the code in OOP style, because if it is not written in ax format, two graphs will be output.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

data = np.random.randint(-8,8,(100,))
x = np.arange(len(data))
y = data

fig = plt.figure()
ax = plt.axes(xlim=(0, len(data)), ylim=(-8, 8))
graph, = ax.plot([], [], 'o')
lines, = ax.plot([],[], 'r-', lw=2)

def init(): 
    lines.set_data([],[])
    return 

def animate(i):
    graph.set_data(x[:i+1], y[:i+1])
    # ax.axvline(x=i, ymin=0.3, ymax=0.6, color='r', lw=2)
    lines.set_data([i, i],[-3, 2])
    return graph

anim = FuncAnimation(fig, animate, frames=100, interval=200)
# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • Thank you for the answer. There is a slight issue. The lines are subject to change as more points are processed and when I test it out, previous lines remain when I would like them not to be plotted. – math111 May 07 '21 at 15:24
  • As a way to avoid leaving lines behind, we changed from axvline to normal plotting, and introduced an initialization function to modify the lines so that they are initialized after each animation. – r-beginners May 08 '21 at 04:35
  • Looks nice! Question: you define ``init()``, but don't seem to use it? – PatrickT Mar 01 '23 at 17:48
  • Reviewing it now, it is unnecessary. – r-beginners Mar 02 '23 at 01:22