''' -大家好,我有一个小问题,非常感谢您的帮助, 我有一个可以捕获正在使用的温度和湿度的硬件 python显示实时图形
问题:10秒钟后,x轴随时间流逝,请参阅 照片以清楚地了解问题所在
如何解决此问题,x轴未清除为新轴 数据及时输入到x轴上。
另外,我有一个函数可以向数据库添加数据,我想添加 每10秒钟时间更新一次数据。睡眠不起作用
'''
import serial
import sqlite3
import datetime
import time
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import
FigureCanvasTkAgg ,NavigationToolbar2Tk
import threading
style.use('ggplot')
fig=plt.figure()
ax1=fig.add_subplot(111)
x_axis=[] # time in str
y_axis_t=[] # contains live data from sensor
y_axis_h=[]
def add_db(time,t,h,dt):
conn=sqlite3.connect('Temperature.db')
c=conn.cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS data
(Time TEXT,Temperature TEXT,Humidity TEXT,Date TEXT)""")
c.execute(""" INSERT INTO data
(Time, Temperature, Humidity, Date)
VALUES (?, ?, ?, ?)""", (time, t, h, dt))
conn.commit()
c.close()
conn.close()
def read_data():
arduinodata =serial.Serial('COM8',9600,timeout=0.1)
while arduinodata.inWaiting:
val=arduinodata.readline().decode('ascii')
if len(val) == 13 :
return val
def process():
h,t=read_data().split(',')
mytime = datetime.datetime.now()
tm= '{}:{}:{}'.format(mytime.hour,mytime.minute,mytime.second)
dt= '{}/{}/{}'.format(mytime.month,mytime.day,mytime.year)
print(tm,str(t),str(h),str(dt),end='')
x_axis.append(tm)
y_axis_t.append(t)
y_axis_h.append(h)
return tm,str(t),str(h),str(dt)
def animate(i):
ax1.clear()
tm,t,h,dt=process()
# i want to convert x axis time to timestamp how ?
ax1.plot(y_axis_t,label='Temperature',color='r')
ax1.fill_between(x_axis, y_axis_t, color='r', alpha=0.2)
# i want to convert x axis time to timestamp how ?
ax1.plot(x_axis,y_axis_h, label='Humidity',color='b')
ax1.fill_between(x_axis, y_axis_h, color='b', alpha=0.2)
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(45)
plt.xlabel('Time ')
plt.ylabel('Temperature in C and Humidity in %')
plt.title('DHT-11 Sensor Graph ')
plt.legend()
if __name__ == '__main__':
ani=animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
Problem can be seen in figure how x axis gets squeesed as more data come in