内容描述
Matplotlib动态图绘制
代码
import matplotlib.pyplot as plt
import math
class Dynamic_Plot_Process_Data():
def __init__(self) -> None:
plt.ion()
self.__array_list = []
def create_list(self, list_name):
setattr(self, list_name, [])
self.__array_list.append(list_name)
def append_data(self, list_name, data):
if hasattr(self, list_name):
getattr(self, list_name).append(data)
else:
raise ValueError('类中不含有“{}”属性,请先用create_list函数创建对应列表属性')
def plot_loss(self):
color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
line_style = ['-', '--', '-.', ':']
for i in range(len(self.__array_list)):
plt.plot(getattr(self, self.__array_list[i]), color=color_list[i], linestyle=line_style[i % len(line_style)])
plt.legend(self.__array_list)
plt.pause(0.1)
if __name__ == '__main__':
# 初始化绘图函数
init = Dynamic_Plot_Process_Data()
# 初始化待存储数据的列表信息
init.create_list('store_y1')
init.create_list('store_y2')
init.create_list('store_y3')
x = 1
while True:
y1 = math.sin(x)
init.append_data('store_y1', y1)
y2 = math.sin(x) + math.cos(x)
init.append_data('store_y2', y2)
y3 = math.sin(x) + math.tan(x)
init.append_data('store_y3', y3)
x += 1
init.plot_loss()