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)
解决方案
您可以从头开始动态重绘绘图。
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)
推荐阅读
- c++ - Qt:显示 IP-CAMERA 流的问题
- jquery - jQuery preg replacing through matches loop?
- visual-studio-code - 扩展主机在 Windows 10 上的 VS Code 中意外终止
- java - MissingCsrfTokenException:无法验证提供的 CSRF 令牌,因为找不到您的会话
- php - 是否可以在 wamp 或 xampp ( windows ) 上安装 php gearman 扩展
- javascript - 如何将 mailerlite.com 注册表单与 React 集成?
- pandas - 跨三维绘制熊猫面板列
- batch-file - 从路径中删除当前工作目录
- java - Java 6 guava 谓词到 Java 8 谓词和 Lambda
- cassandra - DSE 配置中的授权错误