動圖之一個圓繞另一個圓轉動

專注的阿熊發表於2021-06-29

# -*- coding: utf-8 -*-

"""

Created on Mon Jun 14 20:22:04 2021

@author: Leslie Lee  

"""

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.animation as animation

def coord(time, step, W, w, r1, r2):

     '''

     r1 為動圓半徑 r2 為靜圓半徑 W 為公轉角速度 w 為自轉角速度 time 為離散時間長度

     '''

     t = np.arange(0, time, step)

     x = np.sin(W*t)*r1

     y = np.cos(W*t)*r1

     x1 = np.sin(W*t)*(r1+r2)

     y1 = np.cos(W*t)*(r1+r2)

     x2 = x1 + r1*np.sin(w*t/2)

     y2 = y1 - r1*np.cos(w*t/2)

     return x, y, x1, y1, x2, y2

time = 500

step = 0.05

r1 = 2

r2 = 2

W = np.deg2rad(3.6)*10

w =np.deg2rad(3.6)*10

x,y,x1,y1,x2,y2 = coord(time, step, W, w, r1, r2)

# 建立 fig

fig = plt.figure()

ax = fig.add_subplot(111, autoscale_on=False, xlim=(-8, 8), ylim=(-8, 8))

ax.grid()

line, = ax.plot([], [], 'o-', lw=2)

time_template = 'time = %.1fs' # 格式化輸出 保留一位浮點數

time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

def init():

     line.set_data([], [])

     time_text.set_text('')

     return line, time_text

def animate(i):

     thisx = [0, x[i], x1[i], x2[i]]

     thisy = [0, y[i], y1[i], y2[i]]

     line.set_data(thisx, thisy)

     time_text.set_text(time_template % (i*step))

     return line, time_text

ani = animation.FuncAnimation(fig, animate, np.arange(0, len(y)),

                               interval=25, blit=True, init_func=init)

plt.show()

在動畫的基礎上又將軌跡畫了上去

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.animation as animation

def coord(time, step, W, w, r1, r2):

     '''

     r1 為動圓半徑 r2 為靜圓半徑 外匯跟單gendan5.com W 為公轉角速度 w 為自轉角速度 time 為離散時間長度

     '''

     t = np.arange(0, time, step)

     x = np.sin(W*t)*r1

     y = np.cos(W*t)*r1

     x1 = np.sin(W*t)*(r1+r2)

     y1 = np.cos(W*t)*(r1+r2)

     x2 = x1 + r1*np.sin(w*t/2)

     y2 = y1 - r1*np.cos(w*t/2)

     return x, y, x1, y1, x2, y2

time = 500

step = 0.05

r1 = 2

r2 = 2

W = np.deg2rad(3.6)*10

w =np.deg2rad(3.6)*10

x,y,x1,y1,x2,y2 = coord(time, step, W, w, r1, r2)

fig = plt.figure()

ax = plt.gca()

ax.set_aspect(1)

plt.plot(x, y)

plt.plot(x1, y1)

plt.plot(x2, y2)

line, = ax.plot([], [], 'o-', lw=2)

time_template = 'time = %.1fs' # 格式化輸出 保留一位浮點數

time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

def init():

     line.set_data([], [])

     time_text.set_text('')

     return line, time_text

def animate(i):

     thisx = [0, x[i], x1[i], x2[i]]

     thisy = [0, y[i], y1[i], y2[i]]

     line.set_data(thisx, thisy)

     time_text.set_text(time_template % (i*step))

     return line, time_text

ani = animation.FuncAnimation(fig, animate, np.arange(0, len(y)),

                               interval=25, blit=True, init_func=init)

plt.show()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2778907/,如需轉載,請註明出處,否則將追究法律責任。

相關文章