1. 背景
我绘制了一个具有最小值的二次函数曲线(ax^2+bx+c,a>0),并使用可迭代的方法来搜索该值。每一步之后,都会产生一个点。我想要做的是动态地绘制这一点。
2.伪代码
f(x)=ax^2+bx+c, a>0
g(t) is the mentioned method which is used to search the minimum value
plot f(x)
plot initial point (x0,y0)
for t in range(10000):
new_x,new_y = g(t)
move (x0,y0) to new position (new_x,new_y)
3.解决方案
3.1 互动情节
3.1.1 示例import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.use("TkAgg")
plt.figure()
plt.grid(True)
plt.ion()
ft = np.linspace(0, 100, 1000)
plt.plot(ft, ft ** 2 + 1, c='r')
for t in range(100):
plt.scatter(t, t ** 2 + 1, marker='.', c='b')
plt.pause(1e-6)
plt.ioff()
plt.show()
3.1.2 注意事项
- 它有效,但运行缓慢。
- 该方法生成一个轨道,这是冗余的。
3.2 动画
3.2.1 示例
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
matplotlib.use("TkAgg")
def update_points(num):
point_ani.set_data(x[num], y[num])
return point_ani,
x = np.linspace(0, 100, 1000)
y = x**2+1
fig = plt.figure(tight_layout=True)
plt.plot(x, y)
point_ani, = plt.plot(x[0], y[0], "ro")
plt.grid(ls="--")
ani = animation.FuncAnimation(fig,
update_points,
interval=1,
blit=True)
plt.show()
print('finish')
3.2.2 注意事项
这种方法可以在没有任何轨迹的情况下工作,但是在绘制之前必须知道点的整个移动路径。
所以,假设有一个艺术家,它每次收到一个新点就画;如果没有收到点,它会等待。如何实施?