1

I have a time series plot and I need to draw a moving vertical line to show the point of interest.

I am using the following toy example to accomplish the same. However, it prints all the lines at the same time while I wanted to show these vertical line plotting one at a time.

import time
ion() # turn interactive mode on

# initial data
x = arange(-8, 8, 0.1);
y1 = sin(x)
y2 = cos(x)
line1, = plt.plot(x, y1, 'r')
xvals = range(-6, 6, 2);
for i in xvals:
    time.sleep(1)
    # update data
    plt.vlines(i, -1, 1, linestyles = 'solid', color= 'red')
    plt.draw()
learner
  • 2,582
  • 9
  • 43
  • 54

2 Answers2

3

If I understood well, you want to use the animation tools of matplotlib. An example (adapted from the doc):

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

X_MIN = -6
X_MAX = 6
Y_MIN = -1
Y_MAX = 1
X_VALS = range(X_MIN, X_MAX+1) # possible x values for the line


def update_line(num, line):
    i = X_VALS[num]
    line.set_data( [i, i], [Y_MIN, Y_MAX])
    return line, 

fig = plt.figure()

x = np.arange(X_MIN, X_MAX, 0.1);
y = np.sin(x)

plt.scatter(x, y)

l , v = plt.plot(-6, -1, 6, 1, linewidth=2, color= 'red')

plt.xlim(X_MIN, X_MAX)
plt.ylim(Y_MIN, Y_MAX)
plt.xlabel('x')
plt.ylabel('y = sin(x)')
plt.title('Line animation')

line_anim = animation.FuncAnimation(fig, update_line, len(X_VALS), fargs=(l, ))

#line_anim.save('line_animation.gif', writer='imagemagick', fps=4);

plt.show()

Resulting gif looks like this:

line animation with matplotlib

stellasia
  • 5,372
  • 4
  • 23
  • 43
  • Thanks for detailed response. I am getting an error while writing to file. `RuntimeError: Error writing to file`. This error is on line_anim.save() function at the end. – learner Jul 08 '15 at 20:11
  • You probably don't have `imagemagick` installed on your machine? – stellasia Jul 08 '15 at 20:14
  • Strange... Can you show the full error message then? Also, on which OS are you working on? – stellasia Jul 09 '15 at 07:11
0

Could you try calling plt.draw after plt.vlines? plt.draw is used to interactively redraw the figure after its been modified.

Err_Eek
  • 1
  • 1