首页 > 解决方案 > 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)

标签: pythonmatplotlib

解决方案


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

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 notebook 的演示使用:

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)

推荐阅读