0

I would like to create an animation of the function f(x,t)=cos(kx-wt) where x would be an array # from 0 to 2*pi, k any constant, w any other constant and each frame would be a value of t different from, say, 0 to 10.

I'm starting to learn about python and the matplotlib library now, I looked in the documentation but I can't understand or I couldn't find a similar problem.

One way I thought of doing it was:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(5,2))

T = np.linspace(0,10,100)
K = 3.
w = 1.
x = np.linspace(0, 2\*np.pi, 100)

for t in T:
    cos = np.cos(K*x - w*t)
    ax.plot(x, cos)
    plt.pause(0.001)

plt.show()

but the axes are printed one after the other, and not quite what I imagined. I would like each curve of this separated in a frame and not all together.

cheersmate
  • 2,385
  • 4
  • 19
  • 32
Luigui
  • 1
  • 1

1 Answers1

1

The following, based heavily on this Matplotlib animation example, should hopefully do what you want. I've tried to add comments to help your understanding, but please comment if there's anything you don't understand.

from functools import partial

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

# create the figure and axes objects on which to plot
fig, ax = plt.subplots()

# generate your x-data
x = np.arange(0, 2 * np.pi, 0.01)

# set your constants
K = 3.0
w = 1.0

# define the function that you want to plot
def plotfunc(x, t, K, w):
    return np.cos(K * x - w * t)

# define t
T = np.linspace(0, 2 * np.pi, 100)

# plot the initial function at t=0 ("line" holds the data that was
# plotted which will be updated later in the animate function)
line, = ax.plot(x, plotfunc(x, T[0], K, w))

# define animation function
def animate(i, x=None, t=None, K=None, w=None, line=None):
    # get index in t (modded with length of t, so that it repeats)
    tidx = (i + 1) % len(t)

    # update the y-axis data in the Line2D (line) object
    line.set_ydata(plotfunc(x, t[tidx], K, w))
    return line,

# set "partial" version of the animate function that presets all
# the keyword arguments to animate (apart from i)
anifunc = partial(animate, x=x, t=T, K=K, w=w, line=line)

# make the animation
ani = animation.FuncAnimation(
    fig,  # pass the figure object
    anifunc,  # pass the animation function
    interval=20,
    blit=True,
)

plt.show()
Matt Pitkin
  • 3,989
  • 1
  • 18
  • 32