Reputation: 730
''' - Hello Everyone, i have a small issue any help is really appreciated, i have a hardware which captures temperature and humidity i am using python to display live graph
problem: after 10 seconds x-axis get flooded with time please see photo to get a clear picture of the problem
how do I get rid of this issue x-axis is not cleared as new and new data comes in time is squeezed on the x-axis.
also, I have a function that add data to database I want to add that data after every 10 sec time. sleep doesn't work
'''
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
Upvotes: 0
Views: 433