回答編集履歴
1
Update
answer
CHANGED
@@ -46,4 +46,60 @@
|
|
46
46
|
movie.save("animation_test.gif", writer='pillow')
|
47
47
|
```
|
48
48
|
|
49
|
+
**追記**
|
50
|
+
|
51
|
+
> アニメーションにzの時間変化も組み込むにはどうプログラム文を変更すれば良いでしょうか。zは見やすくするためにx_iと色を変えた点で表したいと思っています。
|
52
|
+
|
53
|
+
`np.concatenate` を使います。また、色の指定には `scat.set_facecolor` を使います。
|
54
|
+
`z` の最初の位置が `(-50, -50)` になっていますので、`z_room[k] = z_room[k-1] + np.random.rand(1, 2)` としています(右上方向へ移動)。
|
55
|
+
|
56
|
+
```python
|
57
|
+
import tkinter as tk
|
58
|
+
import matplotlib.pyplot as plt
|
59
|
+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
|
60
|
+
import numpy as np
|
61
|
+
import matplotlib.animation as ani
|
62
|
+
|
63
|
+
root = tk.Tk() #ウインドの作成
|
64
|
+
root.title("Sheep and dog") #ウインドのタイトル
|
65
|
+
root.geometry("800x700") #ウインドの大きさ
|
66
|
+
|
67
|
+
#シミュレーションのサイズ
|
68
|
+
n = 20 #生物Aの数
|
69
|
+
K = 100 #シミュレーションの時間ステップ数
|
70
|
+
|
71
|
+
np.random.seed(77)
|
72
|
+
x_i = np.random.randint(-48., 48., (n, 2)) #生物Aの初期値。n×2行列
|
73
|
+
z = np.array([-50., -50.]) #生物Bの初期値
|
74
|
+
x_color, z_color = 'blue', 'red'
|
75
|
+
scat_colors = [x_color] * n + [z_color]
|
76
|
+
|
77
|
+
x_room, z_room = np.zeros((K, n, 2)),np.zeros((K, 1, 2))
|
78
|
+
x_room[0], z_room[0] = x_i, z
|
79
|
+
for k in range(1, K):
|
80
|
+
x_room[k] = x_room[k-1] + 2*np.random.rand(n, 2)-1
|
81
|
+
z_room[k] = z_room[k-1] + np.random.rand(1, 2)
|
82
|
+
|
83
|
+
fig, ax = plt.subplots() #描画の用意
|
84
|
+
ax.set_xlim(-50,50)
|
85
|
+
ax.set_ylim(-50,50)
|
86
|
+
ax.set_xlabel("x") #x軸のラベル
|
87
|
+
ax.set_ylabel("y") #y軸のラベル
|
88
|
+
scat = ax.scatter(x_i[0], x_i[1])
|
89
|
+
|
90
|
+
def animate(i):
|
91
|
+
scat.set_offsets(np.concatenate([x_room[i,:,:], z_room[i]]))
|
92
|
+
scat.set_facecolor(scat_colors)
|
93
|
+
frame = f"{i:.2f}"
|
94
|
+
ax.set_title('frames= '+str(frame))
|
95
|
+
return scat
|
96
|
+
|
97
|
+
#tkinterのウインド上部にグラフを表示する
|
98
|
+
canvas = FigureCanvasTkAgg(fig, master=root)
|
99
|
+
movie= ani.FuncAnimation(fig, animate, interval=100, frames=K)
|
100
|
+
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
|
101
|
+
|
102
|
+
movie.save("animation_test.gif", writer='pillow')
|
103
|
+
```
|
104
|
+
|
49
|
-

|