I have a data files containing x and y cordinate of a dynamical system. I want to create animation of it in python.

I have tried matplotlib.animation as animation.

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

fig = plt.figure()
ax = plt.axes(xlim=(0, 1), ylim=(-.1, .1))

filename = '{}{}'.format("file_1234",".txt")
data1=np.loadtxt(filename)
s1=data1[:,0]
t1=data1[:,1]
line, = ax.plot(s1, t1)
def init():  # only required for blitting to give a clean slate.
    line.set_ydata([np.nan] * len(s1))
    return line,


def animate(i):
    line.set_data(s1[i],t1[i])
    #~ line.set_ydata(t1[i])
    #~ line.set_ydata(t1)
    return line,


ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=2, blit=True, save_count=50)

plt.show()

I have tried this code but unable to get exact phase space. please help me in finding mistakes.

1 Answers

0
Sourabh Mittal On Best Solutions
enter code here
import numpy as np   

import matplotlib.pyplot as plt     

import matplotlib.animation as animation                         

fig = plt.figure()                      

ax = plt.axes(xlim=(0, 1), ylim=(-.25, .2))                         

filename = '{}{}'.format("file_1",".txt")

data1=np.loadtxt(filename)


filename = '{}{}'.format("file_2",".txt")      

data2=np.loadtxt(filename)

colors1 = ['b', 'b', ]

colors = ['r', 'r']

lines = sum([ax.plot([], [], [], '-', c=c)
         for c in colors], [])

pts = sum([ax.plot([], [], [], 'o', c=c)
       for c in colors], [])

lines1 = sum([ax.plot([], [], [], '-', c=c)
         for c in colors1], [])

pts1 = sum([ax.plot([], [], [], 'o', c=c)
       for c in colors1], [])

def init():

    for line, pt, line1, pt1 in zip(lines, pts, lines1, pts1):

        line.set_data([], [])

        pt.set_data([], [])

        line1.set_data([], [])

        pt1.set_data([], [])     

    return lines + pts + lines1 + pts1


def animate(i):

    for line, pt, line1, pt1, xi, yi in zip(lines, pts, lines1, pts1, data1, data2):

        x, y = data1[:i].T

        p, q = data2[:i].T

        line.set_data(x, y)
        pt.set_data(x[-1:], y[-1:])
        line1.set_data(p, q)
        pt1.set_data(p[-1:], q[-1:])

    return lines + pts + lines1 + pts1

anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=7000, interval=10, blit=True)

Writer = animation.writers['ffmpeg']
writer = Writer(fps=500, metadata=dict(artist='Me'), bitrate=100)
anim.save('video.mp4', writer=writer)
plt.show()