0

我目前正在尝试创建一个应该绘制动画奈奎斯特图并将其保存为 gif 文件的 python 代码。

问题是,我不知道如何使动画功能起作用。这是我在互联网上找到的有效代码:

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,

您可能知道,linspacesin是返回具有顺序值的数组的函数。我的代码中的realimag变量也是具有顺序值的数组。w变量也是一个数组,对应于realimag的值。我希望为每个w值绘制realimag,从而成为动画的“步骤”。我的代码有什么问题?

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()
4

1 回答 1

0

在您的代码中,您总是在绘制当前数据(实数和图像),但根据 matplotlib,您需要使用在每次迭代中更新的数据列表。 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()
于 2018-04-08T22:48:41.563 回答