Reputation: 111
I have an animation in Python and I would like to add a time label that updates. I already have a NumPy array called time, and so I thought it would be as easy as inserting the variable into the label.
fig, ax = plt.subplots()
line, = ax.plot([], lw=2)
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
plotlays, plotcols = [1], ["blue"]
lines = []
for index in range(1):
lobj = ax.plot([], [], lw=2, color=plotcols[index])[0]
lines.append(lobj)
def animate(i):
xlist = [xvals]
ylist = [psisol[i,:].real]
time_text.set_text('time = %0.2f' % time[i])
for lnum, line in enumerate(lines):
line.set_data(xlist[lnum], ylist[lnum])
return lines
I've taken it from Jake Vanderplas's Double Pendulum tutorial here, and also I looked at this StackOverflow post. While the program executes, the plot area stays gray. If I comment out the text code, the program runs perfectly fine and plots and animates. Not sure what else to try.
Thanks for any help.
Upvotes: 1
Views: 2120
Reputation: 2921
I edited the tutorial you took from, to have an animated text inside the graph. Next time, please provide reproducible code (what is xvals
? psisol
? + there are no imports)
"""
Matplotlib Animation Example
author: Jake Vanderplas
email: [email protected]
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""
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, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
time_text.set_text('')
return line,
# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
time_text.set_text(str(i))
return tuple([line]) + tuple([time_text])
# 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()
Upvotes: 1