下のプログラムを実行するときに、movie.save()の文をコメントアウトすると何も出ませんが、有効にするとlist index out of rangeのエラーが出てきてしまいます。
#プログラム
python
import tkinter as tk from scipy.spatial import Delaunay, \ delaunay_plot_2d, Voronoi, voronoi_plot_2d, ConvexHull import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import ( \ FigureCanvasTkAgg, NavigationToolbar2Tk) import numpy as np import matplotlib.animation as ani root = tk.Tk()#ウインドの作成 root.title("Sheep and dog")#ウインドのタイトル root.geometry("800x700") #ウインドの大きさ #シミュレーションのサイズ n = 20 #生物Aの数 K = 10 #シミュレーションの時間ステップ数 np.random.seed(77) x_i = np.random.randint(-48., 48., (n, 2)) #生物Aの初期値。n×2行列 z = np.array([-50., -50.]) #生物Bの初期値 fig = plt.Figure() #描画の用意 ax = fig.add_subplot(111) ax.set_xlim(-50,50) ax.set_ylim(-50,50) ax.set_xlabel("x")#x軸のラベル ax.set_ylabel("y")#y軸のラベル line = ax.scatter(x_i[0], x_i[1]) def animate(i): line.set_xdata(np.array(x_room[i,:,0])) line.set_ydata(np.array(x_room[i,:,1])) frame=f"{i:.2f}" ax.set_title('frames= '+str(frame)) return line x_room, z_room = [], [] for k in range(K): if len(x_room) == 0: x_room.append(x_i) z_room.append(z) xk = x_i + np.random.rand zk = z + np.random.rand x_room.append(xk) z_room.append(zk) x_i = xk z = zk print() print(f'{len(x_room)} {len(x_room[0])} {len(x_room[0][0])}') #tkinterのウインド上部にグラフを表示する canvas = FigureCanvasTkAgg(fig, master=root) movie= ani.FuncAnimation(fig, animate,interval=10,frames=1) canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) movie.save("animation_test.gif",writer='pillow')
errorはdef文内の
python
line.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が出ます。この対処法についてアドバイスをお願いします。
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' というエラーになります。
melianさん、大変丁寧にご回答して頂き本当にありがとうございます。エラーを解決することができ、無事アニメーションが保存されました。
重ねて質問したいのですが、アニメーションにzの時間変化も組み込むにはどうプログラム文を変更すれば良いでしょうか。関数animateのscatの引数をx_room[i, :, :] + z_room[i]にしてみたのですが全然違う結果になってしまいました。zは見やすくするためにx_iと色を変えた点で表したいと思っています。
まだ回答がついていません
会員登録して回答してみよう