''' - 大家好,我有一个小问题非常感谢任何帮助,我有一个可以捕获温度和湿度的硬件,我正在使用 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()