0

I'm trying to animate some function. My x values are constant (the range doesn't change throughout the animation):

x = np.linspace(0,1,N)

And I have my y values stored in a file as frames, separated with a new line:

1 
2
3

1.2
1.9
2.8

How can I show all my values from the frame at once and then move to another frame?

NotStudent
  • 39
  • 1
  • 10

2 Answers2

2

I start by creating mock data in a file called data.txt with the format you specified:

import numpy as np

def your_func(x, a):
    return np.sin(x + a)

n_cycles = 4
n_frames = 100

xmin = 0
xmax = n_cycles*2*np.pi
N = 120

x = np.linspace(xmin, xmax, N)

with open('data.txt', 'w') as fout:
    for i in range(n_frames):
        alpha = 2*np.pi*i/n_frames
        y = your_func(x, alpha)
        for value in y:
            print(f'{value:.3f}', file=fout)
        print(file=fout)

The data file looks like this:

0.000  # First frame
0.210
...
-0.210
-0.000

0.063  # Second frame
0.271
...
-0.148
0.063

...

-0.063  # Frame 100
0.148
...
-0.271
-0.063

Then I read those data from disk:

def read_data(filename):
    with open(filename, 'r') as fin:
        text = fin.read()
    values = [[]]
    for line in text.split('\n'):
        if line:
            values[-1].append(float(line))
        else:
            values.append([])
    return np.array(values[:-2])

y = read_data('data.txt')

The animation is generated as follows:

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

def plot_background():
    line.set_data([], [])
    return line,

def animate(i):
    line.set_data(x, y[i])
    return line,

fig = plt.figure()
ax = plt.axes(xlim=(x[0], x[-1]), ylim=(-1.1, 1.1))
line, = ax.plot([], [], lw=2)

anim = FuncAnimation(fig, animate, init_func=plot_background,
                     frames=n_frames, interval=10, blit=True)

anim.save(r'animated_function.mp4', 
          fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

animation

For a more detailed explanation, take a look at this blog.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
1

Based upon my understanding of what you've asked, this question has already been answered. The link is https://stackoverflow.com/a/33275455/8513445.

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

x = np.linspace(0,1,6)
y = [1,2,3,1.2,1.9,2.8]

fig = plt.figure()
plt.xlim(0, 4)
plt.ylim(0, 4)
graph, = plt.plot([], [], 'o')

def animate(i):
    graph.set_data(x[:i+1], y[:i+1])
    return graph

ani = FuncAnimation(fig, animate, frames=12, interval=200)
plt.show()
M. Small
  • 138
  • 5