Matplotlib动态绘图

时间:2018-05-11 22:52:34

标签: python matplotlib

我目前正在开发一个覆盆子项目,我希望在数据显示在终端时动态绘制图形。从我的代码中,图表仅在我关闭窗口时更新,并且它会重新打开图表的更新版本。 “谢谢你

import matplotlib.pyplot as plt`
from time import sleep
from Adafruit_CCS811 import Adafruit_CCS811
ccs =  Adafruit_CCS811()
while not ccs.available():
         pass
temp = (ccs.calculateTemperature() / 3.2) - 32.0
ccs.tempOffset = temp - 25.0
while(True):
     if ccs.available():       
          temp = ccs.calculateTemperature()
          if not ccs.readData():
              print ("CO2: ", ccs.geteCO2(), "ppm, TVOC: ", ccs.getTVOC(), " temp: ", temp)

                plt.plot([ccs.geteCO2(), ccs.getTVOC(), temp])

                plt.pause(0.05)
                plt.show()    
          else:
              print ("ERROR!")
              while(True):
                 pass

      sleep(2)

1 个答案:

答案 0 :(得分:0)

您可以从头开始动态重绘绘图。

from IPython import display

def dynamic_plot(X,Y, figsize=[10,5], max_x=None, min_y=None, max_y=None):
    '''plots dependency between X and Y dynamically: after each call current graph is redrawn'''
    gcf().set_size_inches(figsize)
    cla()
    plot(X,Y)
    if max_x: 
        plt.gca().set_xlim(right=max_x)
    if min_y: 
        plt.gca().set_ylim(bottom=min_y)
    if max_y: 
        plt.gca().set_ylim(top=max_y)

    display.display(gcf())
    display.clear_output(wait=True)  

以及jupyter笔记本的演示用途:

import time

X=[]
Y=[]
for i in range(10):
    X.append(i)
    Y.append(i**.5)
    dynamic_plot(X,Y,[14,10], max_x=10, max_y=4)  
    time.sleep(0.3)