美文网首页
解决matplotlib使用plt.pause动态绘图窗口无法关

解决matplotlib使用plt.pause动态绘图窗口无法关

作者: 沐泠LHY | 来源:发表于2020-12-08 10:00 被阅读0次

    解决思路:循环中判断绘图窗口是否关闭,如果关闭则退出动态绘图的循环

    plt生成figure对象时需要指定一个int类型的id(如不指定,plt内部自动生成),可通过该id获取到figure对象(保存在matplotlib._pylab_helpers.Gcf.figs),当窗口关闭时,plt保存的id会被清除,通过判断id是否存在则可以判断窗口是否关闭

    两种情况如下,具体见注释

    使用plt绘图

    from matplotlib import pyplot as plt
    '''
        使用plt绘图,只会有一个窗口
        因此可以通过判断id数目是否为0来判断绘图窗口是否关闭
    '''
    plt.plot() #需要在循环外面生成绘图窗口
    while True:
        if len(plt.get_fignums())==0:
            break
    
        #进行更新数据和绘图操作
        #...
    else:
        plt.show()
    

    使用figure面向对象绘图

    import matplotlib.pyplot as plt
    '''
        plt.figure()生成fig时指定id,直接通过id是否存在即可判断
        如果不指定id,也可通过fig.canvas.manager.num
        
        顺便一提,直接使用plt绘图时的fig对象可以通过plt.gcf()获取
        因此也可获取其id后通过这种方法判断
    '''
    figID=1
    fig=plt.figure(figID)
    
    while True:
        if not plt.fignum_exists(figID):
            break
    
        #进行更新数据和绘图操作
        #...
    else:
        plt.show()
    

    相关文章

      网友评论

          本文标题:解决matplotlib使用plt.pause动态绘图窗口无法关

          本文链接:https://www.haomeiwen.com/subject/zglfgktx.html