LoginSignup
3
1

More than 3 years have passed since last update.

[python]色が変わっていく時計(アニメーション)

Last updated at Posted at 2019-12-04

はじめに

1秒毎に回転し、60秒で1周する秒針(時計)を作成します。
ただ秒針を描くだけではつまらないので、時計の色が0~60[s]の範囲で、青色から赤色へ次第に変化するようにします。最後にgifとして保存して完成です。

pythonの、アニメーションを作成するライブラリを用います。

完成したアニメーション

20191204second_hand.gif

コード

second_hand.py
%matplotlib nbagg

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.patches as pat

fig = plt.figure()
ax = plt.subplot()

def clock(i):
    circle = [ax.add_patch(pat.Wedge(center=(0, 0), r=1, color=[0+i/60,0,1-i/60], theta1 = 95-i*(360/60), theta2 = 85-i*(360/60)))]
    #center:中心のxy座標,r:ウェッジの半径,color:RGBでの色指定(各色0~1),theta:ウェッジの角度を指定
    #circleをリストにすることに注意してください。あとでimgsに追加できるようにするためです。
    return circle

#リストimgsに、各秒ごとのclockを追加していきます。
imgs=[]
for i in range(60):
    imgs.append(clock(i))

ani = animation.ArtistAnimation(fig, imgs, interval=1000, repeat=True)
plt.axis("scaled")
plt.show()

ani.save("second_hand.gif", writer="imagemagick")#gifとして保存

環境

macOS Catalina
jupyter-notebook

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1