1. Background
I draw a quadratic function curve (ax^2+bx+c, a>0) which has a minimum value, and I use an iterable method to search this value. After every step, there generates a point. What I want to do is draw this point dynamically.
2. Pseudocode
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. Solution
3.1 interactive plot
3.1.1 Exampleimport 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 Note
- It works, but it runs slowly.
- This method generates a track, which is redundant.
3.2 Animation
3.2.1 Example
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 Note
This method works without any track, but the entire moving path of point has to be known before drawing.
So, suppose there is an artist, it draws every time it receives a new point; it waits if no point is received. How to implement?
