質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

保存

保存(save)とは、特定のファイルを、ハードディスク等の外部記憶装置に記録する行為を指します。

Q&A

解決済

1回答

4103閲覧

Animationを保存しようとするとlist index out of rangeとなってしまう。

miyavi-177

総合スコア2

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

保存

保存(save)とは、特定のファイルを、ハードディスク等の外部記憶装置に記録する行為を指します。

0グッド

0クリップ

投稿2021/12/16 02:57

下のプログラムを実行するときに、movie.save()の文をコメントアウトすると何も出ませんが、有効にするとlist index out of rangeのエラーが出てきてしまいます。

#プログラム

python

1 2import tkinter as tk 3from scipy.spatial import Delaunay, \ 4 delaunay_plot_2d, Voronoi, voronoi_plot_2d, ConvexHull 5import matplotlib.pyplot as plt 6from matplotlib.backends.backend_tkagg import ( \ 7 FigureCanvasTkAgg, NavigationToolbar2Tk) 8import numpy as np 9import matplotlib.animation as ani 10 11root = tk.Tk()#ウインドの作成 12root.title("Sheep and dog")#ウインドのタイトル 13root.geometry("800x700") #ウインドの大きさ 14 15#シミュレーションのサイズ 16n = 20 #生物Aの数 17K = 10 #シミュレーションの時間ステップ数 18 19np.random.seed(77) 20x_i = np.random.randint(-48., 48., (n, 2)) #生物Aの初期値。n×2行列 21z = np.array([-50., -50.]) #生物Bの初期値 22 23fig = plt.Figure() #描画の用意 24ax = fig.add_subplot(111) 25ax.set_xlim(-50,50) 26ax.set_ylim(-50,50) 27ax.set_xlabel("x")#x軸のラベル 28ax.set_ylabel("y")#y軸のラベル 29line = ax.scatter(x_i[0], x_i[1]) 30 31def animate(i): 32 line.set_xdata(np.array(x_room[i,:,0])) 33 line.set_ydata(np.array(x_room[i,:,1])) 34 frame=f"{i:.2f}" 35 ax.set_title('frames= '+str(frame)) 36 return line 37 38x_room, z_room = [], [] 39 40for k in range(K): 41 if len(x_room) == 0: 42 x_room.append(x_i) 43 z_room.append(z) 44 45 xk = x_i + np.random.rand 46 zk = z + np.random.rand 47 48 x_room.append(xk) 49 z_room.append(zk) 50 51 x_i = xk 52 z = zk 53 print() 54 55print(f'{len(x_room)} {len(x_room[0])} {len(x_room[0][0])}') 56 57#tkinterのウインド上部にグラフを表示する 58canvas = FigureCanvasTkAgg(fig, master=root) 59movie= ani.FuncAnimation(fig, animate,interval=10,frames=1) 60canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) 61 62movie.save("animation_test.gif",writer='pillow')

errorはdef文内の

python

1line.set_xdata(np.array(x_room[i,:,0]))

でlist index out of rangeと書いてあるのですが、x_roomは11×20×2行列なので要素を超えていないのではないかと思っています。

また、

movie.save("animation_test.gif",writer='pillow')

をコメントアウトしているとそのエラーは出ず、代わりに

UserWarning: Animation was deleted without rendering anything. This is most likely unintended. To prevent deletion, assign the Animation to a variable that exists for as long as you need the Animation. warnings.warn(

とだけ出ます。コメントアウトを外すとlist index out of rangeが出ます。この対処法についてアドバイスをお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

melian

2021/12/16 03:20

x_room が 2-dim numpy.ndarray のリストになっています。 x_room = np.dstack(x_room) とすれば 3-dim array に変換されます。ただ、 line.set_xdata(...) で、 'PathCollection' object has no attribute 'set_xdata' というエラーになります。
miyavi-177

2021/12/17 14:57

melianさん、大変丁寧にご回答して頂き本当にありがとうございます。エラーを解決することができ、無事アニメーションが保存されました。 重ねて質問したいのですが、アニメーションにzの時間変化も組み込むにはどうプログラム文を変更すれば良いでしょうか。関数animateのscatの引数をx_room[i, :, :] + z_room[i]にしてみたのですが全然違う結果になってしまいました。zは見やすくするためにx_iと色を変えた点で表したいと思っています。
guest

回答1

0

ベストアンサー

コメントにも書きましたが、x_room が numpy.ndarray のリストになっている事が原因です。最初から numpy.ndarray にしておく方が良いかと思います。

python

1import tkinter as tk 2import matplotlib.pyplot as plt 3from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 4import numpy as np 5import matplotlib.animation as ani 6 7root = tk.Tk() #ウインドの作成 8root.title("Sheep and dog") #ウインドのタイトル 9root.geometry("800x700") #ウインドの大きさ 10 11#シミュレーションのサイズ 12n = 20 #生物Aの数 13K = 100 #シミュレーションの時間ステップ数 14 15np.random.seed(77) 16x_i = np.random.randint(-48., 48., (n, 2)) #生物Aの初期値。n×2行列 17z = np.array([-50., -50.]) #生物Bの初期値 18 19x_room, z_room = np.zeros((K, n, 2)),np.zeros((K, 1, 2)) 20x_room[0], z_room[0] = x_i, z 21for k in range(1, K): 22 x_room[k] = x_room[k-1] + 2*np.random.rand(n, 2)-1 23 z_room[k] = z_room[k-1] + 2*np.random.rand(1, 2)-1 24 25fig, ax = plt.subplots() #描画の用意 26ax.set_xlim(-50,50) 27ax.set_ylim(-50,50) 28ax.set_xlabel("x") #x軸のラベル 29ax.set_ylabel("y") #y軸のラベル 30scat = ax.scatter(x_i[0], x_i[1]) 31 32def animate(i): 33 scat.set_offsets(x_room[i,:,:]) 34 frame = f"{i:.2f}" 35 ax.set_title('frames= '+str(frame)) 36 return scat 37 38#tkinterのウインド上部にグラフを表示する 39canvas = FigureCanvasTkAgg(fig, master=root) 40movie= ani.FuncAnimation(fig, animate, interval=100, frames=K) 41canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) 42 43movie.save("animation_test.gif", writer='pillow')

追記

アニメーションにzの時間変化も組み込むにはどうプログラム文を変更すれば良いでしょうか。zは見やすくするためにx_iと色を変えた点で表したいと思っています。

np.concatenate を使います。また、色の指定には scat.set_facecolor を使います。
z の最初の位置が (-50, -50) になっていますので、z_room[k] = z_room[k-1] + np.random.rand(1, 2) としています(右上方向へ移動)。

python

1import tkinter as tk 2import matplotlib.pyplot as plt 3from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 4import numpy as np 5import matplotlib.animation as ani 6 7root = tk.Tk() #ウインドの作成 8root.title("Sheep and dog") #ウインドのタイトル 9root.geometry("800x700") #ウインドの大きさ 10 11#シミュレーションのサイズ 12n = 20 #生物Aの数 13K = 100 #シミュレーションの時間ステップ数 14 15np.random.seed(77) 16x_i = np.random.randint(-48., 48., (n, 2)) #生物Aの初期値。n×2行列 17z = np.array([-50., -50.]) #生物Bの初期値 18x_color, z_color = 'blue', 'red' 19scat_colors = [x_color] * n + [z_color] 20 21x_room, z_room = np.zeros((K, n, 2)),np.zeros((K, 1, 2)) 22x_room[0], z_room[0] = x_i, z 23for k in range(1, K): 24 x_room[k] = x_room[k-1] + 2*np.random.rand(n, 2)-1 25 z_room[k] = z_room[k-1] + np.random.rand(1, 2) 26 27fig, ax = plt.subplots() #描画の用意 28ax.set_xlim(-50,50) 29ax.set_ylim(-50,50) 30ax.set_xlabel("x") #x軸のラベル 31ax.set_ylabel("y") #y軸のラベル 32scat = ax.scatter(x_i[0], x_i[1]) 33 34def animate(i): 35 scat.set_offsets(np.concatenate([x_room[i,:,:], z_room[i]])) 36 scat.set_facecolor(scat_colors) 37 frame = f"{i:.2f}" 38 ax.set_title('frames= '+str(frame)) 39 return scat 40 41#tkinterのウインド上部にグラフを表示する 42canvas = FigureCanvasTkAgg(fig, master=root) 43movie= ani.FuncAnimation(fig, animate, interval=100, frames=K) 44canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) 45 46movie.save("animation_test.gif", writer='pillow')

イメージ説明

投稿2021/12/16 16:50

編集2021/12/17 15:32
melian

総合スコア19803

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

miyavi-177

2021/12/17 14:56

melianさん、大変丁寧にご回答して頂き本当にありがとうございます。エラーを解決することができ、無事アニメーションが保存されました。 重ねて質問したいのですが、アニメーションにzの時間変化も組み込むにはどうプログラム文を変更すれば良いでしょうか。関数animateのscatの引数をx_room[i, :, :] + z_room[i]にしてみたのですが全然違う結果になってしまいました。zは見やすくするためにx_iと色を変えた点で表したいと思っています。
melian

2021/12/17 15:33

追加してみました。ご確認下さい。
miyavi-177

2021/12/18 02:17

melianさん、私のような初心者にも懇切丁寧に対応して頂きありがとうございます。とても勉強になりました。引き続きプログラミングの学習を精進していきたいと思います!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問