【问题标题】:Animation of a polar circle in pythonpython中的极圈动画
【发布时间】:2025-11-22 23:00:03
【问题描述】:

这是我的 python 文件,用于模拟一个圆的振荡动力学,该圆永久地扩展和收缩:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    theta = np.linspace(0, 2 * np.pi, 100)
    r = np.sqrt(np.abs(np.sin(0.1 * i)))
    x = r * np.cos(theta) + 1
    y = r * np.sin(theta)
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)

plt.show()

但是参数定义有缺陷,结果不是动画圆,而是省略号。

我该如何解决这个问题?

【问题讨论】:

    标签: python animation matplotlib


    【解决方案1】:

    尝试添加plt.gca().set_aspect('equal', adjustable='box') 并修改您的ylim,如下所示:

    import numpy as np
    from matplotlib import pyplot as plt
    from matplotlib import animation
    
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 2), ylim=(-1, 1))
    line, = ax.plot([], [], lw=2)
    
    def init():
        line.set_data([], [])
        return line,
    
    def animate(i):
        theta = np.linspace(0, 2 * np.pi, 100)
        r = np.sqrt(np.abs(np.sin(0.1 * i)))
        x = r * np.cos(theta) + 1
        y = r * np.sin(theta)
        line.set_data(x, y)
        return line,
    
    anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
    
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()
    

    这将显示如下:

    【讨论】:

      【解决方案2】:

      您的坐标轴长度不同(边界框),试试这个:

      import numpy as np
      from matplotlib import pyplot as plt
      from matplotlib import animation
      
      fig = plt.figure()
      ax = plt.axes(xlim=(-2, 2), ylim=(-2, 2))
      line, = ax.plot([], [], lw=2)
      
      def init():
          line.set_data([], [])
          return line,
      
      def animate(i):
          theta = np.linspace(0, 2 * np.pi, 100)
          r = 2*np.sqrt(np.abs(np.sin(0.1 * i)))
          x = r * np.cos(theta)
          y = r * np.sin(theta)
          line.set_data(x, y)
          return line,
      
      anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
      
      plt.show()
      

      【讨论】: