我目前正在尝试创建一个python代码,该代码应该绘制一个生动活泼的nyquist图,并将其保存为gif文件。
问题是,我不知道如何使动画功能工作。下面是我在互联网上找到的一段代码,它是有效的:
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,如您所知,linspace和sin是用顺序值返回数组的函数。我的代码中的实变量和imag变量也是具有顺序值的数组。W变量也是一个数组,对应于实值和imag值。我希望为每一个w值绘制真实和形象,从而成为动画的“步骤”。我的密码怎么了?
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation as an
import control
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(-2, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
G = control.TransferFunction((1),(1,0))
real, imag, w = control.nyquist(G)
line.set_data(real, imag)
return line,**
# call the animator. blit=True means only re-draw the parts that have changed.
anim = an.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=200, blit=True)
#anim.save('GIF.gif', dpi=100, writer='imagemagick')
plt.title('Nyquist Diagram of 1/s')
plt.ylabel('Imaginary')
plt.xlabel('Real')
plt.grid(True)
plt.show()发布于 2018-04-08 22:48:41
在您的代码中,您总是绘制当前数据(real和imag),但是根据matplotlib,您需要使用在每次迭代中更新的数据列表。素材库-动画
在下面的代码中,我创建了列表realData和imagData,因此在每次迭代中,real和imag都被附加到列表中,这些列表被用作line.set_data参数。
我还在刚开始的时候使用了控制包,因为它已经返回了一个列表,其中包含了绘制所需的所有内容。
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation as an
import control
# First set up the figure, the axis, and the plot element we want to animate
fig, ax = plt.subplots()
realData, imagData = [], []
line, = plt.plot([], [], 'rx', animated=True)
G = control.TransferFunction((1),(1,0))
real, imag, w = control.nyquist(G)
print(real)
print(imag)
def init():
ax.set_xlim(-2, 2)
ax.set_ylim(-10, 10)
return line,
# animation function. This is called sequentially
def animate(i):
realData.append(real[i])
imagData.append(imag[i])
line.set_data(realData, imagData)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = an.FuncAnimation(fig, animate, init_func=init,
frames=range(len(real)), interval=2, blit=True)
#anim.save('GIF.gif', dpi=100, writer='imagemagick')
plt.title('Nyquist Diagram of 1/s')
plt.ylabel('Imaginary')
plt.xlabel('Real')
plt.grid(True)
plt.show()https://stackoverflow.com/questions/49722298
复制相似问题