matplotlib实时动态图

分享
手机游戏开发者 2024-9-24 15:12:11 50 0 来自 中国
我一直用的VScode + jupyter notebook编码,在举行神经网络实验的时间经常会用到使用matplotlib举行图标的绘制。尤其是在观测准确率的变化的时间须要动态观察数据。
实现matplotlib实时动态图的方法有三种:
(1)ion和ioff

这是最简朴的一种,他会跳出一个框,内里的数据会动态革新,而不是静态的图片。可以使用在下令行和pycharm等。
但是在VScode + jupyter notebook中,须要添加%matplotlib inline,而且它是一张一张图片的输出。

  • 代码实现
import matplotlib.pyplot as plti=0x=[]y=[]plt.ion()while i<100:    plt.clf()  #打扫上一幅图像    x.append(i)    y.append(i**2)    plt.plot(x,y)    i=i+1    plt.pause(0.01)  # 暂停0.01秒    plt.ioff()  # 关闭画图的窗口plt.show()(2)可以使用FuncAnimation

这里要求matplotlib的版本在3.X及以上,在使用jupyter的时间还须要使用%matplotlib notebook.
但是VScode并不支持matplotlib的natebook模式。
官方表明:
https://www.jianshu.com/p/04e240966bb4
编码教程:https://www.bilibili.com/video/BV1Pt4y1s7Pj?spm_id_from=333.880.my_history.page.click&vd_source=9e5b81656aa2144357f0dca1094e9cbe
(3)自制一个Animator

这个可以完善的在VScode + jupyter notebook中完善运行。
代码:
from IPython import displayfrom matplotlib import pyplot as pltfrom matplotlib_inline import backend_inlineclass Animator():    """初始化横轴,x/ylabel,"""    def __init__(self, xlim, xlabel=None, ylabel=None, legend=None,ylim=None, xscale='linear', yscale='linear',                 fmts=('-', 'm--', 'g-.', 'r:'),figsize=(3.5, 2.5)) -> None:        self.xlabel = xlabel        self.ylabel = ylabel        self.xscale = xscale        self.yscale = yscale        self.xlim = xlim        self.ylim = ylim        self.legend = legend        # 图例表现        if legend is None:            legend = []        # 使用svg图像表现        backend_inline.set_matplotlib_formats('svg')        self.fig, self.axes = plt.subplots(figsize=figsize)        self.x = None        self.y = None        self.fmts = fmts    def set_axes(self):        # 设置轴上的属性        self.axes.set_xlabel(self.xlabel)        self.axes.set_ylabel(self.ylabel)        self.axes.set_xscale(self.xscale)        self.axes.set_yscale(self.yscale)        self.axes.set_xlim(self.xlim)        self.axes.set_ylim(self.ylim)        if self.legend:            self.axes.legend(self.legend)        self.axes.grid()    def show(self,x,y):        self.axes.cla()        for i in range(len(x)):            self.axes.plot(x,y,self.fmts)        self.set_axes()        display.display(self.fig)        display.clear_output(wait=True)    使用也很简朴:
fig = Animator(xlim=(-0.1,10.1),legend=["x1","x2"])def delay():    for i in range(999999):        for j in range(9):            a=1x = [[],[]]y = [[],[]]print(type(x))for i in range(11):    x[0].append(i)    y[0].append(i**2)    x[1].append(i)    y[1].append(i*2)    print(x)    fig.show(x,y)    delay()
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 22:34, Processed in 0.168054 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表