我目前正在尝试创建一个python代码,该代码应该绘制一个动画的奈奎斯特图并将其保存为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 变量也是一个数组,对应于 real 和 imag 的值。我希望为每个 w 值绘制真实和 imag ,从而成为" step"动画片我的代码出了什么问题?
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()
答案 0 :(得分:0)
在您的代码中,您始终在绘制当前数据(真实和图像),但根据matplotlib,您需要使用在每次迭代中更新的数据列表。 Matplotlib - Animation
在下面的代码中,我创建了列表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()