matplotlibボタンウィジェットがクリックされた後にのみmatplotlibのアニメーション関数がプロットを開始するコードを書きたいと思います。これが私のステップです:
x座標とy座標の保存に成功しましたが、ボタンを押すと、必要なアニメーションプロットが表示されません。これは私が直面している最初のエラーです。
2番目のエラーは、クリックイベントに、ボタンを押した場所の座標も格納されることです。ボタンを押している間は座標が必要ありません。空のプロットの座標だけです。
from matplotlib.widgets import Button
from matplotlib.animation import FuncAnimation
x_coord,y_coord = [],[]
fig = plt.figure()
axis = fig.add_subplot(111,xlim=(-5,15),ylim=(-5,15))
line, = axis.plot([],[],lw=3)
def init():
line.set_data([],[])
return line,
def animate(i):
x_points = [0,x_coord[i]]
y_points = [0,y_coord[i]]
line.set_data(x_points,y_points)
return line,
def onclick(event):
print(event.xdata,event.ydata)
x_coord.append(event.xdata)
y_coord.append(event.ydata)
def buttonPress(pressevent):
print('pressed')
print(x_coord)
ani = FuncAnimation(fig,animate,init_func=init,frames=len(x_coord),interval=100,blit=False)
cid = fig.canvas.mpl_connect('button_press_event',onclick)
axprev = plt.axes([0.5,0,0.1,0.1])
button = Button(axprev,'press')
button.on_clicked(buttonPress)
plt.show()```
2番目のエラーは簡単に修正できます。次を使用して、クリックが軸領域にあるかどうかをテストできます。 event.inaxes
アニメーションの問題は、関数でアニメーションオブジェクトを作成していることと、関数の最後ですぐにガベージコレクションされることが原因です。[FuncAnimation][2]
州の文書:
インスタンスオブジェクトへの参照を保持することが重要です。アニメーションは、Animationオブジェクトが唯一の参照を保持するタイマー(通常はホストGUIフレームワークから)によって進められます。Animationオブジェクトへの参照を保持していない場合、そのオブジェクト(したがってタイマー)はガベージコレクションされ、アニメーションが停止します。
これを回避する1つの方法は、アニメーションオブジェクトをグローバル変数に保持することです。よりクリーンな方法は、コードをカスタムクラスにカプセル化し、アニメーションをそのクラスのプロパティとして保存することです。
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Button
x_coord, y_coord = [], []
fig = plt.figure()
axis = fig.add_subplot(111, xlim=(-5, 15), ylim=(-5, 15))
line, = axis.plot([], [], lw=3)
ani = None
def init():
line.set_data([], [])
return line,
def animate(i):
x_points = [0, x_coord[i]]
y_points = [0, y_coord[i]]
line.set_data(x_points, y_points)
return line,
def onclick(event):
if event.inaxes is axis:
print(event.xdata, event.ydata)
x_coord.append(event.xdata)
y_coord.append(event.ydata)
def buttonPress(pressevent):
global ani
print('pressed')
print(x_coord)
ani = FuncAnimation(fig, animate, init_func=init, frames=len(x_coord), interval=100, blit=False)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
axprev = plt.axes([0.5, 0, 0.1, 0.1])
button = Button(axprev, 'press')
button.on_clicked(buttonPress)
plt.show()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加