使用红点

时间:2017-04-22 12:41:13

标签: python matplotlib graph

我正在尝试为正在绘制的正弦函数设置动画,但在新绘制的图形部分上有一个红点。我已经完成了绘图工作,但红点仍然被绘制了好几次。这是我的代码:

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()

基本上我需要擦除红点并重新绘制每一帧。

2 个答案:

答案 0 :(得分:2)

与更新线条一样,您可以使用先前定义的线图的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() 方法更新红点。

{{1}}

enter image description here

答案 1 :(得分: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()