matplotlib 动态显示

matplotlib绘制图,调用plt.show()后会阻塞程序,直至鼠标关闭窗口. 希望不采用阻塞方式运行,动态显示曲线,可以尝试如下代码:

重点
* plt.ion() : 交互式绘图模式
* plt.pause(0.05): 显示绘图


from matplotlib import pyplot as plt

class VISUAL_LOSS(object):
    def __init__(self):
        plt.ion()
        self.trainloss = []
        self.testloss = []
        return
    def update_train(self, round, loss):
        if isinstance(loss, mx.nd.NDArray):
            loss = loss.asnumpy()[0]
        self.trainloss.append((round, loss))
        return
    def update_test(self,round,loss):
        if isinstance(loss, mx.nd.NDArray):
            loss = loss.asnumpy()[0]
        self.testloss.append((round,loss))
    def show(self):
        if len(self.trainloss) > 0:
            x = [d[0] for d in self.trainloss]
            y = [d[1] for d in self.trainloss]
            plt.plot(x,y,"r")
        if len(self.testloss) > 0:
            x = [d[0] for d in self.testloss]
            y = [d[1] for d in self.testloss]
            plt.plot(x,y,"b")
        plt.pause(0.05)
        return

猜你喜欢

转载自blog.csdn.net/z0n1l2/article/details/80868808