Plotting vertical lines in matplotlib.animation over a scatter plot

Viewed 332

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.

1 Answers

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

Related