LoginSignup
12
14

More than 5 years have passed since last update.

matplotlib で線分をアニメーションさせる

Last updated at Posted at 2018-01-30

pyplot の描画をアニメーションをさせるには matplotlib.animation の ArtistAnimation が便利ですね。
ただ、線分を使ったアニメを作ろうとしたら少々戸惑いましたのでご参考まで。

通常、アニメはこんな要領かと思います。

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

x = np.arange(0, np.pi * 2, np.pi / 10.0)
y = np.sin(x)

fig = plt.figure()
imgs = []

for i in range(len(x)):
    img = plt.plot(x[:i+1], y[:i+1], 'b-o')
    imgs.append(img)

anim = animation.ArtistAnimation(fig, imgs, interval=100)
anim.save('result1.gif', 'imagemagick')
plt.show()

result1.gif

また、線分を書くのはこのように、線分を個別に配列にして plot すると簡単です。

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

step = np.pi / 10.0
xs = np.arange(0, np.pi * 2, step)

for x in xs:
    y = np.sin(x)
    plt.plot([x, x + step], [y, y], 'b-o')

plt.savefig('result2.png')
plt.show()

result2.png

さてこれをアニメーションさせたいのですが、この plot のたびに append したのでは変なアニメになってしまいます。

result3.gif

まあこれはあたりまえの話でありまして、希望としては複数の plot をまとめて1フレームとして追加したいわけです。
しかし、下記では失敗します。

for i in range(len(xs)):
    lines = []
    for x in xs[0:i+1]:
        y = np.sin(x)
        img = plt.plot([x, x + step], [y, y], 'b-o')
        lines.append(img)
    imgs.append(lines)
  :
AttributeError: 'list' object has no attribute 'set_visible'

まあそうだよなあ、乱暴だったよなあ。(ああ、python に時間取られるのいやだなあ…)

しかし答えはアハ的なもので、append ではなく extend にすれば通ります。

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

step = np.pi / 10.0
xs = np.arange(0, np.pi * 2, step)

fig = plt.figure()
imgs = []

for i in range(len(xs)):
    lines = []
    for x in xs[0:i+1]:
        y = np.sin(x)
        img = plt.plot([x, x + step], [y, y], 'b-o')
        lines.extend(img)
    imgs.append(lines)

anim = animation.ArtistAnimation(fig, imgs, interval=100)
anim.save('result4.gif', 'imagemagick')
plt.show()

result4.gif

要するに plot の戻りってリストなんですね([Line2D])。

以上です。おそまつさまでした。

この記事の環境

  • Python 3.5.1 :: Anaconda 2.5.0 (x86_64)
12
14
4

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
12
14