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)

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

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)

最新更新