使用matplotlib中的animation库动态画图

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值