在最近的几个晚上,我一直在努力如何在每个时间步长或每个x步长后将此处的波形转换为某种动画。我该如何修改和编写代码,以便使程序的每一步动画都以某种方式出现。我对python和编程非常陌生,以前从未使用过matplotlib的动画部分。
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
T = 20.0 # t
X = 10.0 # x
n = 300
m = 300
#positions of time and space, xp= x position accross grid, tp = t position accross grid
tp = T / (n - 1)
xp = X / (m - 1)
C = 0.5
U = np.zeros((n, m))
# Set the initial values for each x position
for i in range(0, n):
U[i, 0] = np.exp(- (i * xp - 2.5) ** 2)
for i in range(1, n): # across x
for j in range(1, m): # across t
U[i, j] = (xp * U[i, j - 1] + C * tp * U[i - 1, j]) / (xp + C * tp) # equation for new distribution value
fig = plt.figure(1)
#gives time position instead of time step
tn = np.zeros((m, 1))
for j in range(0, m):
tn[j] = j * tp
#gives x position instead of x step
xn = np.zeros((n, 1))
for j in range(0, n):
xn[j] = j * xp
for i in [0, 50, 100, 150, 200, 250, 299 ]: # selects which position of time
label = 't = ' + str(tn[i][0]) # lables legend
subfig = fig.add_subplot(1, 1, 1)
subfig.plot(xn, U[:, i], label=label)
subfig.legend()
subfig.grid(True)
print(tn)
# Save Image
plt.xlabel('x: position')
plt.ylabel('u: u(x, t)')
plt.title(r'$\frac{\partial u}{\partial t} + C \frac{\partial u}{\partial x} = 0$')
plt.savefig('transport-equation')`
plt是一个很难适应的软件包。通常,图形不是一件容易的事,并且要尽量简化,同时还要提供最大的灵活性。通常,使用plt时,会为您自动生成,更新,清除和处理许多全局变量。使用“ plt.xlabel”时,实际上是将其应用于特定图中的特定轴,这些轴将自动为您确定。如果要在plt中进行更多控制和/或要执行复杂的操作(例如动画),则需要使全局变量明确。
#Create xn and U.
import matplotlib.pyplot as plt
figure = plt.figure() #This is the window that pops open.
axis = figure.add_subplot(1,1,1) #This is a graph/grid.
axis.grid(True) #Add a grid to the axis.
label = 't = ' + str(tn[i][0])
plots = axis.plot(xn,U[:,0],label=label) #These are the plots of data with X and Y.
X和Y数组一次可以生成多个图,因此,图是其中包含一项的列表。为了了解它是如何工作的,您可以实时地实际操作数据并在plt窗口中查看数据的变化。
figure.show()
plots[0].set_ydata(U[:,10])
plots[0].set_ydata(U[:,-1])
# Close the window when done.
要制作动画,我们需要告诉plt将动画应用于给定的图形。然后plt将尝试更新该图及其所附的所有内容。如果您已经打开窗口,则动画仍将应用并起作用,但是您还将保留图形中最初绘制的内容(因此,我们应该关闭窗口并重新编码动画)。 plt不遵循每次执行一行与一次执行所有行相同的约定。在打开窗口之前和之后,plt的行为有所不同。
#Create xn and U.
import matplotlib.pyplot as plt
figure = plt.figure()
axis = figure.add_subplot(1,1,1)
axis.grid(True)
label = 't = ' + str(tn[i][0])
plots = axis.plot(xn,U[:,0],label=label)
def animate_function(frame):
frame %= 300 #frame is an integer that counts from 0.
plots[0].set_ydata(U[:,frame]) #Change which globals you want.
return plots #Return the changed items so plt knows.
#Tell plt to apply this animation function to your figure.
#Tell plt to wait approximately 10ms per frame.
#Tell plt to only update pixels that actually change (called blit).
#Save to a global variable so plt doesn't get upset at you.
ani = animation.FuncAnimation(figure,animate_function,interval=10,blit=True)
#Now open the window and show the figure.
figure.show()