回答編集履歴

1

Update

2021/12/17 15:32

投稿

melian
melian

スコア19805

test CHANGED
@@ -94,4 +94,116 @@
94
94
 
95
95
 
96
96
 
97
+ **追記**
98
+
99
+
100
+
101
+ > アニメーションにzの時間変化も組み込むにはどうプログラム文を変更すれば良いでしょうか。zは見やすくするためにx_iと色を変えた点で表したいと思っています。
102
+
103
+
104
+
105
+ `np.concatenate` を使います。また、色の指定には `scat.set_facecolor` を使います。
106
+
107
+ `z` の最初の位置が `(-50, -50)` になっていますので、`z_room[k] = z_room[k-1] + np.random.rand(1, 2)` としています(右上方向へ移動)。
108
+
109
+
110
+
111
+ ```python
112
+
113
+ import tkinter as tk
114
+
115
+ import matplotlib.pyplot as plt
116
+
117
+ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
118
+
119
+ import numpy as np
120
+
121
+ import matplotlib.animation as ani
122
+
123
+
124
+
125
+ root = tk.Tk() #ウインドの作成
126
+
127
+ root.title("Sheep and dog") #ウインドのタイトル
128
+
129
+ root.geometry("800x700") #ウインドの大きさ
130
+
131
+
132
+
133
+ #シミュレーションのサイズ
134
+
135
+ n = 20 #生物Aの数
136
+
137
+ K = 100 #シミュレーションの時間ステップ数
138
+
139
+
140
+
141
+ np.random.seed(77)
142
+
143
+ x_i = np.random.randint(-48., 48., (n, 2)) #生物Aの初期値。n×2行列
144
+
145
+ z = np.array([-50., -50.]) #生物Bの初期値
146
+
147
+ x_color, z_color = 'blue', 'red'
148
+
149
+ scat_colors = [x_color] * n + [z_color]
150
+
151
+
152
+
153
+ x_room, z_room = np.zeros((K, n, 2)),np.zeros((K, 1, 2))
154
+
155
+ x_room[0], z_room[0] = x_i, z
156
+
157
+ for k in range(1, K):
158
+
159
+ x_room[k] = x_room[k-1] + 2*np.random.rand(n, 2)-1
160
+
161
+ z_room[k] = z_room[k-1] + np.random.rand(1, 2)
162
+
163
+
164
+
165
+ fig, ax = plt.subplots() #描画の用意
166
+
167
+ ax.set_xlim(-50,50)
168
+
169
+ ax.set_ylim(-50,50)
170
+
171
+ ax.set_xlabel("x") #x軸のラベル
172
+
173
+ ax.set_ylabel("y") #y軸のラベル
174
+
175
+ scat = ax.scatter(x_i[0], x_i[1])
176
+
177
+
178
+
179
+ def animate(i):
180
+
181
+ scat.set_offsets(np.concatenate([x_room[i,:,:], z_room[i]]))
182
+
183
+ scat.set_facecolor(scat_colors)
184
+
185
+ frame = f"{i:.2f}"
186
+
187
+ ax.set_title('frames= '+str(frame))
188
+
189
+ return scat
190
+
191
+
192
+
193
+ #tkinterのウインド上部にグラフを表示する
194
+
195
+ canvas = FigureCanvasTkAgg(fig, master=root)
196
+
197
+ movie= ani.FuncAnimation(fig, animate, interval=100, frames=K)
198
+
199
+ canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
200
+
201
+
202
+
203
+ movie.save("animation_test.gif", writer='pillow')
204
+
205
+ ```
206
+
207
+
208
+
97
- ![scatter](f51933e4fe5d307854e5bf463831651a.gif)
209
+ ![イメージ説明](88bd5d76bd4167eba37a582965e41243.gif)