在 Matplotlib 上绕一个大圆的圆周旋转圆?

时间:2021-05-08 23:48:16

标签: python numpy matplotlib animation matplotlib-animation

我正在尝试使用 matplotlib 制作一个程序,该程序将使用任意两个圆(任意半径)并且相邻的圆将围绕主要的较大圆旋转。我看过 matplotlib.animation ,它似乎不起作用。显然动画对形状不起作用?

到目前为止,这是我的代码(我已经删除了动画子例程,因为它们似乎只是使程序变砖)

import matplotlib.pyplot as plt  
import matplotlib.animation
firstcircle = int(input("please input radius for the largest circle"))
secondcircle = int(input("please input radius for the adjacent circle"))
largest = int(firstcircle*2+secondcircle*2)
difference = int(0-(largest))
difference2 = int(0+(largest))


def createList(r1, r2):
    return [item for item in range(r1, r2+1)]


x = (createList(difference,difference2))
y = (createList(difference,difference2))

print(difference)
print(difference2)


def circle():
  theta = np.linspace(0, 2*np.pi, 100)

  r = np.sqrt(firstcircle**2)

  x1 = r*np.cos(theta)
  x2 = r*np.sin(theta)

  theta2 = np.linspace(0, 2*np.pi, 100)
  r1 = np.sqrt(secondcircle**2)
  x3 = r1*np.cos(theta2)+firstcircle+secondcircle
  x4 = r1*np.sin(theta2)

  fig = plt.figure()

  ax = fig.add_subplot(1, 1, 1)
  ax.spines['left'].set_position('center')
  ax.spines['bottom'].set_position('center')
  ax.spines['right'].set_color('none')
  ax.spines['top'].set_color('none')
  ax.xaxis.set_ticks_position('bottom')
  ax.yaxis.set_ticks_position('left')
  ax.plot(x1,x2)
  circlemove ,= ax.plot(x3,x4)  

  ax.set_aspect(1)
  plt.tight_layout()

  plt.xlim(difference,difference2)
  plt.ylim(difference,difference2)


  plt.grid(linestyle='--')

  plt.show()

circle()

1 个答案:

答案 0 :(得分:0)

您可以使用带有函数作为参数的 Matplotlib FuncAnimation(以下代码中的 update)在每个新帧上调用。使用 theta2 作为更新函数的参数(通过 frames 中的 FuncAnimation 参数)并将其与已声明的变量 x3x4 一起使用以给人一种小圆圈围绕大圆圈前进的感觉。接下来,使用 set_data 允许 circlemove 对象为每个新帧显示不同的数据点。

from matplotlib.animation import FuncAnimation
...

    ...
    plt.xlim(difference,difference2)
    plt.ylim(difference,difference2)

    plt.grid(linestyle='--')

    def update(angle):
        r_a = r1 + firstcircle
        x_a = x3 + r_a * np.cos(angle) - firstcircle - secondcircle
        y_a = x4 + r_a * np.sin(angle)
        circlemove.set_data(x_a, y_a)
        return circlemove

    anim = FuncAnimation(fig, update, frames=theta2, repeat=True)
    plt.show()

circle()

rotate_circle

相关问题