有人帮助我编写了这段代码。它可以很好地读取140个输入文件中的数据,并制作出精美的动画。问题是,如果输入的长度不相等,它将无法正常工作。问题在于代码将数据保存在数组中。有人可以帮我解决吗?我有140个不同长度的输入文件。
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
from matplotlib.widgets import Slider
def update_line(num, xs, ys, line, samp):
# This function updates the graph
line.set_data(xs[num], ys[num])
#samp.set_val(num+1)
samp.set_val(-1.5+num*0.025)
return line
# Initialize the animation writer
Writer = animation.writers['ffmpeg']
writer = Writer(fps=10, metadata=dict(artist="Me"), bitrate=-1)
# Reading column 0 as X, and 2 as Y
xcol = 0
ycol = 2
xin=-1.5
# This array holds the array of Xs and Ys
# Frame 0 (0.con) will be stored in xs[0], and ys[0]
# Frame 1 (0.con) will be stored in xs[1], and ys[1]
# and so on ...
xs = []
ys = []
# Store number of files in this variable
number_of_files = 141
# Let's loop through files and read them, then store them in xs, and ys
for n in np.arange(0, number_of_files, 1):
# Set file names
filename = str(n) + str('.con')
# Read data from files 0.con, 1.con, 2.con
df = pd.read_csv(filename, sep='\t')
# Convert to numpy array
data = np.array(df)
# Grab x column and y column -> (t, theta)
t = data[:,xcol]
theta = data[:,ycol]
# Once done append them to the end of xs, and ys
xs.append(t)
ys.append(theta)
# Some figure initializations
fig = plt.figure()
ax = fig.add_subplot(111)
l, = ax.plot([], [], 'r-')
# Let's make sure there is no 0 in data
# Cause if it does the log(0) will be -inf (invalid)
for i in range(len(ys)):
for j in range(len(ys[i])):
if ys[i][j] == 0:
# I will just put a smallest number in set
ys[i][j] = 0.00000000000000000000000000000000000000000000000000001
# Just printing max and min for checking. You can remove the following lines
print("Min xs: " + str(np.min(xs)))
print("Max xs: " + str(np.max(xs)))
print("Min ys: " + str(np.min(ys)))
print("Max ys: " + str(np.max(ys)))
# Set min and max of axes to min and max of data
# You can set these value manually as well
#minxs = np.min(xs)
#maxxs = np.max(xs)
#minys = np.min(ys)
#maxys = np.max(ys)
ax.set_xlim(0.001, 10)
ax.set_ylim(10, 100000000000)
# Some more configuration of the plot
plt.yscale('log')
plt.xscale('log')
plt.xlabel('Energy')
plt.ylabel(r'Transmitted SED')
plt.grid(True)
# Add slider
axcolor = 'lightgoldenrodyellow'
axprog = plt.axes([0.19, 0.9, 0.65, 0.03], facecolor=axcolor)
samp = Slider(axprog, 'log xi',valmax=2, valmin=-1.5, valstep=0.025)
# new value to set the red vertical line to
samp.vline.set_xdata([0,0])
samp.vline.set_color("pink")
# Do the animation and save!
line_ani = animation.FuncAnimation(fig, update_line, frames=number_of_files, fargs=(xs, ys, l, samp))
line_ani.save('test2.mp4', writer=writer)