如何在 Bash 终端中显示 Python 动画

如何在 Bash 终端中显示 Python 动画

首先我要说的是,我不知道自己在做什么。我们大学安装了 Linux,我试图在我的个人设备(Windows 10)上安装类似的东西,不出所料,我遇到了很多麻烦。

我终于设法让 python 程序正常运行,但我不知道如何实际显示动画(或者是否有可能)。

以下是代码(按课堂上的方法输入):

$ ls
    animation.py  binarydata.dat  binary.f
$ gfortran -o binary binary.f
$ ./binary
$ python animation.py body1.dat body2.dat
    Loading files: body1.dat body2.dat
    Plotting orbits...
$ 

我实际上该如何显示动画?

动画的python代码:

import matplotlib
matplotlib.use('Agg')
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import sys

try:
    datafilename1 = sys.argv[1]
    datafilename2 = sys.argv[2]
except:
    quit('Quitting... No input file give.')

print 'Loading files:',datafilename1,datafilename2
data1 = np.loadtxt(datafilename1,usecols=(0,1),skiprows=1)
data2 = np.loadtxt(datafilename2,usecols=(0,1),skiprows=1)
L1 = len(data1)
L2 = len(data2)
#m1size = np.genfromtxt(datafilename1,max_rows=1)
#m2size = np.genfromtxt(datafilename2,max_rows=1)
m1size= np.loadtxt(datafilename1)
m2size= np.loadtxt(datafilename2)
m1size = m1size[0,0]
m2size = m2size[0,0]

print "Plotting orbits..."

X1 = data1[:,0]
Y1 = data1[:,1]
X2 = data2[:,0]
Y2 = data2[:,1]
n = min(len(X1),len(X2))

# Choose how many lines of the data file to skip between each frame.
# i.e. Set the speed of the animation
# Use this if you have a lot of small steps.
speed = 1
n_frames = int(n/speed)

# First set up the figure, the axis, and the plot element we want to animate
# markersize = 50
fig = plt.figure()
ax = plt.axes()
orbit1 = ax.plot(X1,Y1,color='blue')
orbit2 = ax.plot(X2,Y2,color='green')
COM    = ax.plot(0,0,'+',color='red',ms=min(m1size,m2size)/2,mew=2) # Centre of mass

# ax.set_xlim(xmin=min(min(X1),min(X2)),xmax=max(max(X1),max(X2)))
# ax.set_ylim(ymin=min(min(Y1),min(Y2)),ymax=max(max(Y1),max(Y2)))
ax.axis('equal')
body1, = ax.plot([],[],color='lightblue',marker='o',ms=m1size)
body2, = ax.plot([],[],color='lightgreen',marker='o',ms=m2size)

# initialization function: plot the background of each frame
def init():
    body1.set_data([], [])
    return body1,

# animation function.  This is called sequentially
def animate(i):
    x1 = X1[i*speed]
    y1 = Y1[i*speed]
    x2 = X2[i*speed]
    y2 = Y2[i*speed]
    body1.set_data(x1,y1)
    body2.set_data(x2,y2)
    return body1,

# call the animator.  blit=True means only re-draw the parts that have changed.
# Note: when using the Mac OS X Backend, blit=True will not work!!
#       Need to manually set matplotlib.use('TkAgg') first....
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=n_frames, interval=1, blit=False)

plt.show()

相关内容