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

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

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

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

Python 3.x

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

Q&A

解決済

1回答

3821閲覧

matplotlibで複数の直線をアニメーション描画

退会済みユーザー

退会済みユーザー

総合スコア0

Matplotlib

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

Python 3.x

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

0グッド

0クリップ

投稿2019/08/10 17:09

やりたいこと

matplotlibを使ってアニメーションを描画したいです。
静的なものはおおまかにできていますが、動的なものができません。
ランダムで長さ1のタテ線またはヨコ線を表示するアニメーション描画がしたいです。

左が完成イメージで、右が現状です。
書いたのに反映されてない部分もあり、めちゃくちゃになります。
エラーは出ず、動き続けます。

イメージ説明 イメージ説明

プログラム

Python3

1 2 3from matplotlib.figure import Figure 4import numpy as np 5import matplotlib.pyplot as plt 6import matplotlib.animation as animation 7import random 8 9fig = plt.figure(figsize=(5, 5)) 10ax = plt.gca() 11 12y_symbol = ['A','B','C','D','E'] 13 14for i in range(5): 15 for j in range(5): 16 plt.text(i + 0.5, j + 0.5, y_symbol[i] + str(j+1) , size=14, ha='center',color='gray') 17 18plt.text(0.5,0.8,'START→', size=9, ha='center',color='gray') 19 20# 描画範囲の設定と目盛りを消す設定 21ax.set_xlim(0,5) 22ax.set_ylim(5,0) # y軸を反転させる 23# x軸の目盛設定 24ax.set_xticks([0,1, 2, 3, 4, 5]) 25# y軸の目盛設定 26ax.set_yticks([0,1,2,3,4,5]) 27#目盛を丈上部に配置 28ax.xaxis.tick_top() 29#グリッドを表示 30ax.grid() 31 32plt.tick_params(axis='both', which='both', bottom='off', top='off', 33 labelbottom='off', right='off', left='off', labelleft='off') 34 35# A0に緑丸を描く 36line, = ax.plot([0.5], [0.5], marker="o", color='greenyellow', markersize=50) 37line2, = ax.plot([2.5], [2.5], marker="o", color='greenyellow', markersize=50) 38 39xy = [] 40XY = [] 41#animateに呼び出される 42def SelectData(t) : 43 #V_wall、H_wallについて 44 #[[[x,y], [X,Y]],,,],,,]となっていて 45 #点[x,y]と[X,Y]を結ぶと長さ1の直線になる 46 V_wall = [[[[i,y],[i,y+1]]for y in range(6)] for i in range(6)] #タテ線 47 H_wall = [[[[x,i],[x+1,i] ]for x in range(6)] for i in range(6)] #ヨコ線 48 49 i = random.randint(0,5) 50 j = random.randint(0,5) 51 if t == 1 : 52 update_xy = V_wall[i][j][0] 53 update_XY = V_wall[i][j][1] 54 else : 55 update_xy = H_wall[i][j][0] 56 update_XY = H_wall[i][j][1] 57 return update_xy,update_XY 58 59#animation.FuncAnimationに呼び出される 60def animate(data,x,y): 61 t=random.randint(0,1) 62 plt.cla() 63 update_xy,update_XY = SelectData(t) 64 print(update_xy ," " ,update_XY) #数値確認用 65 xy.append(update_xy) 66 XY.append(update_XY) 67 plt.plot(xy, XY, color='red', linewidth=2) 68 69ani = animation.FuncAnimation(fig, animate, fargs = (xy,XY), interval=1000) 70plt.show() 71

宜しくお願いします。

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

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

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

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

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

guest

回答1

0

ベストアンサー

まずは複数の線分を描画する単純例を示します。
参考:pyplot combine multiple line labels in legend

Python

1import matplotlib.pyplot as plt 2import numpy as np 3 4a = np.empty((0,4)) 5a = np.vstack((a,[ 1, 1, 2, 1])) 6a = np.vstack((a,[ 2, 2, 3, 2])) 7a = np.vstack((a,[ 3, 3, 4, 3])) 8 9plt.plot(a[:,::2].T, a[:,1::2].T, 'r') 10plt.plot([],[], 'r') 11 12plt.show()

イメージ説明

これを踏まえてざくっと提示コードを書き換えたコードを示します。

Python

1import numpy as np 2import matplotlib.pyplot as plt 3import matplotlib.animation as animation 4import random 5 6# 描画領域を初期化 7def init_plot(): 8 plt.cla() 9 10 y_symbol = ['A','B','C','D','E'] 11 for i in range(5): 12 for j in range(5): 13 plt.text(i + 0.5, j + 0.5, y_symbol[i] + str(j+1) , size=14, ha='center',color='gray') 14 15 plt.text(0.5,0.8,'START→', size=9, ha='center',color='gray') 16 17 # 描画範囲の設定と目盛りを消す設定 18 ax.set_xlim(0,5) 19 ax.set_ylim(5,0) # y軸を反転させる 20 # x軸の目盛設定 21 ax.set_xticks([0,1, 2, 3, 4, 5]) 22 # y軸の目盛設定 23 ax.set_yticks([0,1,2,3,4,5]) 24 #目盛を丈上部に配置 25 ax.xaxis.tick_top() 26 #グリッドを表示 27 ax.grid() 28 29 plt.tick_params(axis='both', which='both', bottom='off', top='off', 30 labelbottom='off', right='off', left='off', labelleft='off') 31 32 # A0に緑丸を描く 33 line, = ax.plot([0.5], [0.5], marker="o", color='greenyellow', markersize=50) 34 line2, = ax.plot([2.5], [2.5], marker="o", color='greenyellow', markersize=50) 35 36 37#animateに呼び出される 38def SelectData(t) : 39 #V_wall、H_wallについて 40 #[[[x,y], [X,Y]],,,],,,]となっていて 41 #点[x,y]と[X,Y]を結ぶと長さ1の直線になる 42 V_wall = [[[[i,y],[i,y+1]] for y in range(6)] for i in range(6)] #タテ線 43 H_wall = [[[[x,i],[x+1,i] ]for x in range(6)] for i in range(6)] #ヨコ線 44 45 i = random.randint(0,5) 46 j = random.randint(0,5) 47 if t == 1 : 48 u1 = V_wall[i][j][0] 49 u2 = V_wall[i][j][1] 50 else : 51 u1 = H_wall[i][j][0] 52 u2 = H_wall[i][j][1] 53 return [u1[0], u1[1], u2[0], u2[1]] 54 55 56#animation.FuncAnimationに呼び出される 57def animate(data): 58 t = random.randint(0,1) 59 line = SelectData(t) 60 print(line) #数値確認用 61 62 # 1線分を追加 63 global lines 64 lines = np.vstack((lines,line)) 65 66 init_plot() 67 plt.plot(lines[:,::2].T, lines[:,1::2].T, color='red', linewidth=2) 68 69fig = plt.figure(figsize=(5, 5)) 70ax = plt.gca() 71lines = np.empty((0,4)) 72 73ani = animation.FuncAnimation(fig, animate, interval=1000) 74plt.show()

イメージ説明

ちょっと単純&汎化したコードと動画も示します。

Python

1import numpy as np 2import matplotlib.pyplot as plt 3import matplotlib.animation as animation 4import random 5 6N = 10 7 8# 描画領域を初期化 9def init_plot(): 10 plt.cla() 11 ax.set_xlim(-1,N+2) 12 ax.set_ylim(-1,N+2) # y軸を反転させる 13 14#animateに呼び出される 15def SelectData(t) : 16 #V_wall、H_wallについて 17 #[[[x,y], [X,Y]],,,],,,]となっていて 18 #点[x,y]と[X,Y]を結ぶと長さ1の直線になる 19 V_wall = [[[[i,y],[i,y+1]] for y in range(N+1)] for i in range(N+1)] #タテ線 20 H_wall = [[[[x,i],[x+1,i] ]for x in range(N+1)] for i in range(N+1)] #ヨコ線 21 22 i = random.randint(0,N) 23 j = random.randint(0,N) 24 if t == 1 : 25 u1 = V_wall[i][j][0] 26 u2 = V_wall[i][j][1] 27 else : 28 u1 = H_wall[i][j][0] 29 u2 = H_wall[i][j][1] 30 return (u1[0], u1[1], u2[0], u2[1]) 31 32 33#animation.FuncAnimationに呼び出される 34def animate(data): 35 t = random.randint(0,1) 36 line = SelectData(t) 37 print(line) #数値確認用 38 39 # 初出現なら線分を追加 40 if not line in line_set: 41 global lines 42 lines = np.vstack((lines,line)) 43 line_set.add((line)) 44 print('add line.') 45 46 init_plot() 47 plt.plot(lines[:,::2].T, lines[:,1::2].T, color='red', linewidth=2) 48 49fig = plt.figure(figsize=(5, 5)) 50ax = plt.gca() 51lines = np.empty((0,4)) 52line_set = set() # 線分重複チェック用 53 54ani = animation.FuncAnimation(fig, animate, interval=500) 55plt.show()

イメージ説明

投稿2019/08/11 00:01

編集2019/08/11 00:28
can110

総合スコア38266

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

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

退会済みユーザー

退会済みユーザー

2019/08/11 06:14

できました!ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問