matplotlib 里面的animation库可以帮助我们动态的绘制图像,下面演示了动态绘图的代码,绘制了一条实线和一条虚线。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class DynamicDrawer():
def __init__(self):
# draw 2 lines, a line and a dot line
self.line_x, self.line_y, self.dot_x, self.dot_y = \
[[] for _ in range(4)]
self.fig, self.ax = plt.subplots()
self.line, = plt.plot([], [], '.-', label='Line')
self.dot_line = plt.scatter([], [], c='g', s=1, label='Dot Line')
def init_plot(self):
plt.suptitle('Title of dynamic plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='best')
self.ax.set_xlim(-10, 10) # here you need to set a reasonable range
self.ax.set_ylim(-10, 10)
return self.line, self.dot_line
def update(self, data, factor):
# data is passed from frames=gen_function
# factor is passed from fargs parameter
line_xy = data[0]
dot_xy = data[1]
self.line_x.append(line_xy[0])
self.line_y.append(line_xy[1])
self.dot_x.append(dot_xy[0])
self.dot_y.append(dot_xy[1])
# update lines
self.line.set_data(self.dot_x, self.dot_y)
self.dot_line.set_offsets(np.c_[self.dot_x, self.dot_y])
def gen_function(self):
# process your data
yield line_data, dot_data
def draw_dynamic_rpe(self):
# fargs should be tuple or None, optional
# frames should be iterable, int, generator function, or None, optional
K = 0.1
ani = FuncAnimation(fig=self.fig, func=self.update, frames=gen_function, fargs=(K,), init_func=self.init_plot, interval=20)#, save_count=100)#, blit=True)
plt.show()
if __name__ == '__main__':
dynamic_drawer = DynamicDrawer()
dynamic_drawer.draw_dynamic_rpe()
[官方的documentation在这里。]
(https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html)