2017-04-22 4 views
1

新しく描かれたグラフ部分に赤い点が描かれている正弦関数をアニメートしようとしています。私は作品を持っているが、赤い点は何度もプロットされている。これは私のコードです:赤い点で正弦関数をアニメーション化する

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

X = np.linspace(0, 2*np.pi, 200) 
Y = np.sin(X) 


fig, ax = plt.subplots(1,1) 
ax.set_xlim([0, 6*np.pi]) 
ax.set_ylim([-1.1, 1.1]) 

sinegraph, = ax.plot([], []) 

def sine(i): 
    sinegraph.set_data(X[:i],Y[:i]) 
    ax.plot(X[i], Y[i], 'o', color='red') 

anim = animation.FuncAnimation(fig, sine, frames=400, interval=50) 
plt.show() 

基本的には、赤い点をすべてのフレームで消去して再描画する必要があります。

+0

'plt.cla()'を追加し、sine関数に軸の制限を設定しますか?アニメーション中に赤い円を1つだけ表示したいですか? – Serenity

答えて

1

線を更新するのと同じように、以前定義した線プロットのset_data()メソッドを使用して赤い点を更新することができます。ここで

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

X = np.linspace(0, 2*np.pi, 100) 
Y = np.sin(X) 

fig, ax = plt.subplots(1,1) 
ax.set_xlim([0, 2*np.pi]) 
ax.set_ylim([-1.1, 1.1]) 

sinegraph, = ax.plot([], []) 
dot, = ax.plot([], [], 'o', color='red') 

def sine(i): 
    sinegraph.set_data(X[:i],Y[:i]) 
    dot.set_data(X[i],Y[i]) 

anim = animation.FuncAnimation(fig, sine, frames=len(X), interval=50) 
plt.show() 

enter image description here

0

、私はあなたのコードに次の変更を加えたし、私はそれが今、あなたはそれが何を意図したものでないと考えています。

ポインタをプロットするマーカー関数を追加しました。

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

X = np.linspace(0, 2*np.pi, 200) 
Y = np.sin(X) 


fig, ax = plt.subplots(1,1) 
ax.set_xlim([0, 6*np.pi]) 
ax.set_ylim([-1.1, 1.1]) 

sinegraph, = ax.plot([], []) 

def marker(i): 
    ax.plot(X[i-1],Y[i-1],'o',color='red',markersize=5) 
    ax.plot(X[i],Y[i],'o',color='black',markersize=5) 


def sine(i): 
    sinegraph.set_data(X[:i],Y[:i]) 
    ax.plot(X[i], Y[i], 'o', color='red',markersize=5) 
    if i>0: 
     marker(i) 

anim = animation.FuncAnimation(fig, sine, frames=400, interval=50) 
plt.show() 
関連する問題